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
|
---|---|---|---|---|---|---|
92,258 | <p>With my multiproject pom I get an error while running release:prepare. There is nothing fancy about the project setup and every release-step before runs fine.
The error I get is:</p>
<pre>
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Unable to tag SCM
Provider message:
The svn tag command failed.
Command output:
svn: Commit failed (details follow):
svn: File '/repos/june/tags/foo-1.0.2/foo.bar.org/pom.xml' already exists
</pre>
<p>Any idea where it comes from and how to get around it?</p>
<p>(sorry for duplicate post - first was closed because I didn't formulate it as a question that can be answered. I hope it's ok now.)</p>
<p><b>EDIT</b><br>
The maven release plugin takes care of the version handling itself. So when I check the path in the subversion repository the path does not yet exist.</p>
<p><b>EDIT 2</b><br>
@Ben: I don't know the server version, however the client is 1.5.2, too.</p>
| [
{
"answer_id": 92330,
"author": "Roland Schneider",
"author_id": 16515,
"author_profile": "https://Stackoverflow.com/users/16515",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know it is a bug in Subversion 1.5 and not directly related with maven. However a workaround the fixed it for me is to update the local svn repository and run the release:prepare goal again.</p>\n"
},
{
"answer_id": 92337,
"author": "PEELY",
"author_id": 17641,
"author_profile": "https://Stackoverflow.com/users/17641",
"pm_score": 1,
"selected": false,
"text": "<p>It's because you haven't increased the version number - 1.0.2 already exists in your Subversion repo.</p>\n\n<p>Either increment your version or just remove the /repos/june/tags/foo-1.0.2 tag from your repo.</p>\n"
},
{
"answer_id": 250291,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I spent quite a while fighting with this. Something is different in SVN 1.5.1+ that breaks committing to a tag straight from the working copy - which is exactly what Maven does. There's still a lot of finger-pointing as to who's responsible for fixing the problem.</p>\n\n<p>You can do an 'svn update' and rerun the release command but if you're doing a release:branch, this will cause the release plugin not to return your POM files to their previous state.</p>\n\n<p>The best workaround I know of is to drop back to Subversion 1.5.0.</p>\n"
},
{
"answer_id": 509323,
"author": "Tim O'Brien",
"author_id": 1264826,
"author_profile": "https://Stackoverflow.com/users/1264826",
"pm_score": 1,
"selected": false,
"text": "<p>Roland, if you haven't seen this already, take a look at John Smart's blog post about this problem. Although the script he proposes is inelegant, it solves the problem:</p>\n\n<p><a href=\"http://weblogs.java.net/blog/johnsmart/archive/2008/12/subversion_mave.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/johnsmart/archive/2008/12/subversion_mave.html</a></p>\n\n<p>The other solution is to use Git. (Me == currently writing about Maven and Git)</p>\n"
},
{
"answer_id": 748456,
"author": "Jesse Glick",
"author_id": 12916,
"author_profile": "https://Stackoverflow.com/users/12916",
"pm_score": 1,
"selected": false,
"text": "<p>Potentially useful links:</p>\n\n<p><a href=\"http://weblogs.java.net/blog/johnsmart/archive/2008/12/subversion_mave.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/johnsmart/archive/2008/12/subversion_mave.html</a> (previously mentioned)</p>\n\n<p><a href=\"http://jira.codehaus.org/browse/MRELEASE-427\" rel=\"nofollow noreferrer\">http://jira.codehaus.org/browse/MRELEASE-427</a> (the real bug?)</p>\n\n<p><a href=\"http://jira.codehaus.org/browse/SCM-406\" rel=\"nofollow noreferrer\">http://jira.codehaus.org/browse/SCM-406</a> (related bug)</p>\n\n<p><a href=\"http://olafsblog.sysbsb.de/?p=73\" rel=\"nofollow noreferrer\">http://olafsblog.sysbsb.de/?p=73</a> (newer and perhaps more helpful post)</p>\n"
},
{
"answer_id": 751060,
"author": "Dominic Mitchell",
"author_id": 71343,
"author_profile": "https://Stackoverflow.com/users/71343",
"pm_score": 4,
"selected": true,
"text": "<p>This issue is addressed in the latest version of the <a href=\"http://maven.apache.org/plugins/maven-release-plugin/\" rel=\"noreferrer\">maven-release-plugin</a>. Add this to your POM to pull it in.</p>\n\n<pre><code><build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.0-beta-9</version>\n </plugin>\n </plugins>\n </pluginManagement>\n</build>\n</code></pre>\n\n<p>The issue that was fixed is <a href=\"http://jira.codehaus.org/browse/MRELEASE-375\" rel=\"noreferrer\">MRELEASE-375</a>.</p>\n"
},
{
"answer_id": 764673,
"author": "Brian Fox",
"author_id": 77489,
"author_profile": "https://Stackoverflow.com/users/77489",
"pm_score": 0,
"selected": false,
"text": "<p>This is <a href=\"http://jira.codehaus.org/browse/MRELEASE-427\" rel=\"nofollow noreferrer\">fixed</a> in the newest release plugin release, 2.0-beta-9</p>\n"
},
{
"answer_id": 19379911,
"author": "theINtoy",
"author_id": 1279002,
"author_profile": "https://Stackoverflow.com/users/1279002",
"pm_score": 0,
"selected": false,
"text": "<p>I hit this post as I was having a build issue on a server that did not have svn installed.</p>\n\n<p>This helped:\n<a href=\"https://stackoverflow.com/questions/16897288/jenkins-with-subversion\">Jenkins with Subversion</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16515/"
]
| With my multiproject pom I get an error while running release:prepare. There is nothing fancy about the project setup and every release-step before runs fine.
The error I get is:
```
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Unable to tag SCM
Provider message:
The svn tag command failed.
Command output:
svn: Commit failed (details follow):
svn: File '/repos/june/tags/foo-1.0.2/foo.bar.org/pom.xml' already exists
```
Any idea where it comes from and how to get around it?
(sorry for duplicate post - first was closed because I didn't formulate it as a question that can be answered. I hope it's ok now.)
**EDIT**
The maven release plugin takes care of the version handling itself. So when I check the path in the subversion repository the path does not yet exist.
**EDIT 2**
@Ben: I don't know the server version, however the client is 1.5.2, too. | This issue is addressed in the latest version of the [maven-release-plugin](http://maven.apache.org/plugins/maven-release-plugin/). Add this to your POM to pull it in.
```
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-9</version>
</plugin>
</plugins>
</pluginManagement>
</build>
```
The issue that was fixed is [MRELEASE-375](http://jira.codehaus.org/browse/MRELEASE-375). |
92,287 | <p>I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message.</p>
<p>I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length.</p>
| [
{
"answer_id": 92309,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>It's simple, but have you checked endianness? It could easily be a mismatch between the endianness you have sent the data in and the endianness you are recieving in.</p>\n"
},
{
"answer_id": 92375,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 0,
"selected": false,
"text": "<p>I dont know C# but you just need to do the equivalent of this:</p>\n\n<pre><code>out.write((len >>> 24) & 0xFF);\nout.write((len >>> 16) & 0xFF);\nout.write((len >>> 8) & 0xFF);\nout.write((len >>> 0) & 0xFF);\n</code></pre>\n"
},
{
"answer_id": 92399,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 1,
"selected": false,
"text": "<p>If you are going to be exchanging a lot of data, I would recommend implementing (or finding) a Stream-wrapper that can write and read ints in network-order. But if you really only need to write the length do something like this:</p>\n\n<pre><code>using(Socket socket = ...){\n NetworkStream ns = new NetworkStream(socket); \n ns.WriteByte((size>>24) & 0xFF);\n ns.WriteByte((size>>16) & 0xFF);\n ns.WriteByte((size>>8) & 0xFF);\n ns.WriteByte( size & 0xFF);\n // write the actual message\n}\n</code></pre>\n"
},
{
"answer_id": 92983,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 4,
"selected": false,
"text": "<p>It is, as other posters have pointed out, down to endianness.</p>\n\n<p>The Java <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInputStream.html\" rel=\"noreferrer\">DataInputStream</a> expects the data to be <a href=\"http://en.wikipedia.org/wiki/Endianness\" rel=\"noreferrer\">big-endian</a> (network byte order). Judging from the Mono documentation (for equivalents like <a href=\"http://www.go-mono.com/docs/monodoc.ashx?link=T%3aSystem.IO.BinaryWriter\" rel=\"noreferrer\">BinaryWriter</a>), C# tends toward being little-endian (the default for Win32/x86).</p>\n\n<p>So, when you use the standard class library to change the 32bit int '1' to bytes, they produce different results:</p>\n\n<pre><code>//byte hex values\nJava: 00 00 00 01\n C#: 01 00 00 00\n</code></pre>\n\n<p>You can alter the way you write ints in C#:</p>\n\n<pre><code>private static void WriteInt(Stream stream, int n) {\n for(int i=3; i>=0; i--)\n {\n int shift = i * 8; //bits to shift\n byte b = (byte) (n >> shift);\n stream.WriteByte(b);\n }\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>A safer way of doing this would be:</p>\n\n<pre><code>private static void WriteToNetwork(System.IO.BinaryWriter stream, int n) {\n n = System.Net.IPAddress.HostToNetworkOrder(n);\n stream.Write(n);\n}\n</code></pre>\n"
},
{
"answer_id": 93067,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "<p>As everyone here has already pointed out, the issue is most likely caused by the C# application sending ints in little-endian order whereas the Java app expects them in network order (big-endian). However, instead of explicitly rearranging bytes in the C# app, the correct way is to rely on built-in functions for converting from host to network order (htons and the likes) -- this way your code will continue working just fine even when run on a big-endian machine.</p>\n\n<p>In general, when troubleshooting such issues, I find it useful to record the correct traffic (e.g., Java to Java in your case) using tools like netcat or wireshark, and then compare it to the incorrect traffic to see where it's going wrong. As an added benefit, you can also use netcat to inject the captured/prerecorded requests into the server or inject captured/prerecorded responses into the client. Not to mention that you can also modify the requests/responses in a file and test the results before commencing with fixing the code.</p>\n"
},
{
"answer_id": 93238,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 0,
"selected": false,
"text": "<p>The Sysetm.Net.IPAddress class has two static helper methods: HostToNetworkOrder() and NetworkToHostOrder() that do the conversion for you. You can use it with a BinaryWriter over the stream to write the proper value:</p>\n\n<pre><code>using (Socket socket = new Socket())\nusing (NetworkStream stream = new NetworkStream(socket))\nusing (BinaryWriter writer = new BinaryWriter(stream))\n{\n int myValue = 42;\n writer.Write(IPAddress.HostToNetworkOrder(myValue));\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message.
I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length. | It is, as other posters have pointed out, down to endianness.
The Java [DataInputStream](http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInputStream.html) expects the data to be [big-endian](http://en.wikipedia.org/wiki/Endianness) (network byte order). Judging from the Mono documentation (for equivalents like [BinaryWriter](http://www.go-mono.com/docs/monodoc.ashx?link=T%3aSystem.IO.BinaryWriter)), C# tends toward being little-endian (the default for Win32/x86).
So, when you use the standard class library to change the 32bit int '1' to bytes, they produce different results:
```
//byte hex values
Java: 00 00 00 01
C#: 01 00 00 00
```
You can alter the way you write ints in C#:
```
private static void WriteInt(Stream stream, int n) {
for(int i=3; i>=0; i--)
{
int shift = i * 8; //bits to shift
byte b = (byte) (n >> shift);
stream.WriteByte(b);
}
}
```
EDIT:
A safer way of doing this would be:
```
private static void WriteToNetwork(System.IO.BinaryWriter stream, int n) {
n = System.Net.IPAddress.HostToNetworkOrder(n);
stream.Write(n);
}
``` |
92,328 | <p>Within an event, I'd like to put the focus on a specific TextBox within the ListViewItem's template. The XAML looks like this:</p>
<pre><code><ListView x:Name="myList" ItemsSource="{Binding SomeList}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- Focus this! -->
<TextBox x:Name="myBox"/>
</code></pre>
<p>I've tried the following in the code behind:</p>
<pre><code>(myList.FindName("myBox") as TextBox).Focus();
</code></pre>
<p>but I seem to have misunderstood the <code>FindName()</code> docs, because it returns <code>null</code>.</p>
<p>Also the <code>ListView.Items</code> doesn't help, because that (of course) contains my bound business objects and no ListViewItems.</p>
<p>Neither does <code>myList.ItemContainerGenerator.ContainerFromItem(item)</code>, which also returns null.</p>
| [
{
"answer_id": 92765,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 4,
"selected": false,
"text": "<p>As others have noted, The myBox TextBox can not be found by calling FindName on the ListView. However, you can get the ListViewItem that is currently selected, and use the VisualTreeHelper class to get the TextBox from the ListViewItem. To do so looks something like this:</p>\n\n<pre><code>private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n if (myList.SelectedItem != null)\n {\n object o = myList.SelectedItem;\n ListViewItem lvi = (ListViewItem)myList.ItemContainerGenerator.ContainerFromItem(o);\n TextBox tb = FindByName(\"myBox\", lvi) as TextBox;\n\n if (tb != null)\n tb.Dispatcher.BeginInvoke(new Func<bool>(tb.Focus));\n }\n}\n\nprivate FrameworkElement FindByName(string name, FrameworkElement root)\n{\n Stack<FrameworkElement> tree = new Stack<FrameworkElement>();\n tree.Push(root);\n\n while (tree.Count > 0)\n {\n FrameworkElement current = tree.Pop();\n if (current.Name == name)\n return current;\n\n int count = VisualTreeHelper.GetChildrenCount(current);\n for (int i = 0; i < count; ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(current, i);\n if (child is FrameworkElement)\n tree.Push((FrameworkElement)child);\n }\n }\n\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 92917,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": -1,
"selected": false,
"text": "<p>We use a similar technique with WPF's new datagrid:</p>\n\n<pre><code>Private Sub SelectAllText(ByVal cell As DataGridCell)\n If cell IsNot Nothing Then\n Dim txtBox As TextBox= GetVisualChild(Of TextBox)(cell)\n If txtBox IsNot Nothing Then\n txtBox.Focus()\n txtBox.SelectAll()\n End If\n End If\nEnd Sub\n\nPublic Shared Function GetVisualChild(Of T As {Visual, New})(ByVal parent As Visual) As T\n Dim child As T = Nothing\n Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)\n For i As Integer = 0 To numVisuals - 1\n Dim v As Visual = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)\n If v IsNot Nothing Then\n child = TryCast(v, T)\n If child Is Nothing Then\n child = GetVisualChild(Of T)(v)\n Else\n Exit For\n End If\n End If\n Next\n Return child\nEnd Function\n</code></pre>\n\n<p>The technique should be fairly applicable for you, just pass your listviewitem once it's generated.</p>\n"
},
{
"answer_id": 502619,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 5,
"selected": true,
"text": "<p>To understand why <code>ContainerFromItem</code> didn't work for me, here some background. The event handler where I needed this functionality looks like this:</p>\n\n<pre><code>var item = new SomeListItem();\nSomeList.Add(item);\nListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null\n</code></pre>\n\n<p>After the <code>Add()</code> the <code>ItemContainerGenerator</code> doesn't immediately create the container, because the <code>CollectionChanged</code> event could be handled on a non-UI-thread. Instead it starts an asynchronous call and waits for the UI thread to callback and execute the actual ListViewItem control generation.</p>\n\n<p>To be notified when this happens, the <code>ItemContainerGenerator</code> exposes a <code>StatusChanged</code> event which is fired after all Containers are generated.</p>\n\n<p>Now I have to listen to this event and decide whether the control currently want's to set focus or not.</p>\n"
},
{
"answer_id": 3699838,
"author": "miral shah",
"author_id": 446233,
"author_profile": "https://Stackoverflow.com/users/446233",
"pm_score": -1,
"selected": false,
"text": "<p>Or it can be simply done by </p>\n\n<pre><code>private void yourtextboxinWPFGrid_LostFocus(object sender, RoutedEventArgs e)\n {\n //textbox can be catched like this. \n var textBox = ((TextBox)sender);\n EmailValidation(textBox.Text);\n }\n</code></pre>\n"
},
{
"answer_id": 13073720,
"author": "Cillié Malan",
"author_id": 562229,
"author_profile": "https://Stackoverflow.com/users/562229",
"pm_score": 2,
"selected": false,
"text": "<p>I noticed that the question title does not directly relate to the content of the question, and neither does the accepted answer answer it. I have been able to \"access the ListViewItems of a WPF ListView\" by using this:</p>\n\n<pre><code>public static IEnumerable<ListViewItem> GetListViewItemsFromList(ListView lv)\n{\n return FindChildrenOfType<ListViewItem>(lv);\n}\n\npublic static IEnumerable<T> FindChildrenOfType<T>(this DependencyObject ob)\n where T : class\n{\n foreach (var child in GetChildren(ob))\n {\n T castedChild = child as T;\n if (castedChild != null)\n {\n yield return castedChild;\n }\n else\n {\n foreach (var internalChild in FindChildrenOfType<T>(child))\n {\n yield return internalChild;\n }\n }\n }\n}\n\npublic static IEnumerable<DependencyObject> GetChildren(this DependencyObject ob)\n{\n int childCount = VisualTreeHelper.GetChildrenCount(ob);\n\n for (int i = 0; i < childCount; i++)\n {\n yield return VisualTreeHelper.GetChild(ob, i);\n }\n}\n</code></pre>\n\n<p>I'm not sure how hectic the recursion gets, but it seemed to work fine in my case. And no, I have not used <code>yield return</code> in a recursive context before.</p>\n"
},
{
"answer_id": 42567259,
"author": "Latency",
"author_id": 878539,
"author_profile": "https://Stackoverflow.com/users/878539",
"pm_score": 0,
"selected": false,
"text": "<p>You can traverse up the ViewTree to find the item '<em>ListViewItem</em>' record set that corresponds to the cell triggered from hit test.</p>\n\n<p>Similarly, you can get the column headers from the parent view to compare and match the cell's column. You may want to bind the cell name to the column header name as your key for your comparator delegate/filter.</p>\n\n<p>For example: HitResult is on TextBlock shown in green. You wish to obtain the handle to the '<em>ListViewItem</em>'.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8p78C.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8p78C.jpg\" alt=\"enter image description here\"></a></p>\n\n<pre><code>/// <summary>\n/// ListView1_MouseMove\n/// </summary>\n/// <param name=\"sender\"></param>\n/// <param name=\"e\"></param>\nprivate void ListView1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) {\n if (ListView1.Items.Count <= 0)\n return;\n\n // Retrieve the coordinate of the mouse position.\n var pt = e.GetPosition((UIElement) sender);\n\n // Callback to return the result of the hit test.\n HitTestResultCallback myHitTestResult = result => {\n var obj = result.VisualHit;\n\n // Add additional DependancyObject types to ignore triggered by the cell's parent object container contexts here.\n //-----------\n if (obj is Border)\n return HitTestResultBehavior.Stop;\n //-----------\n\n var parent = VisualTreeHelper.GetParent(obj) as GridViewRowPresenter;\n if (parent == null)\n return HitTestResultBehavior.Stop;\n\n var headers = parent.Columns.ToDictionary(column => column.Header.ToString());\n\n // Traverse up the VisualTree and find the record set.\n DependencyObject d = parent;\n do {\n d = VisualTreeHelper.GetParent(d);\n } while (d != null && !(d is ListViewItem));\n\n // Reached the end of element set as root's scope.\n if (d == null)\n return HitTestResultBehavior.Stop;\n\n var item = d as ListViewItem;\n var index = ListView1.ItemContainerGenerator.IndexFromContainer(item);\n Debug.WriteLine(index);\n\n lblCursorPosition.Text = $\"Over {item.Name} at ({index})\";\n\n // Set the behavior to return visuals at all z-order levels.\n return HitTestResultBehavior.Continue;\n };\n\n // Set up a callback to receive the hit test result enumeration.\n VisualTreeHelper.HitTest((Visual)sender, null, myHitTestResult, new PointHitTestParameters(pt));\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
]
| Within an event, I'd like to put the focus on a specific TextBox within the ListViewItem's template. The XAML looks like this:
```
<ListView x:Name="myList" ItemsSource="{Binding SomeList}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- Focus this! -->
<TextBox x:Name="myBox"/>
```
I've tried the following in the code behind:
```
(myList.FindName("myBox") as TextBox).Focus();
```
but I seem to have misunderstood the `FindName()` docs, because it returns `null`.
Also the `ListView.Items` doesn't help, because that (of course) contains my bound business objects and no ListViewItems.
Neither does `myList.ItemContainerGenerator.ContainerFromItem(item)`, which also returns null. | To understand why `ContainerFromItem` didn't work for me, here some background. The event handler where I needed this functionality looks like this:
```
var item = new SomeListItem();
SomeList.Add(item);
ListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null
```
After the `Add()` the `ItemContainerGenerator` doesn't immediately create the container, because the `CollectionChanged` event could be handled on a non-UI-thread. Instead it starts an asynchronous call and waits for the UI thread to callback and execute the actual ListViewItem control generation.
To be notified when this happens, the `ItemContainerGenerator` exposes a `StatusChanged` event which is fired after all Containers are generated.
Now I have to listen to this event and decide whether the control currently want's to set focus or not. |
92,362 | <p><strong>Has anyone found a way to run Selenium RC / Selenium Grid tests, written in C# in parallel?</strong></p>
<p>I've currently got a sizable test suite written using Selenium RC's C# driver. Running the entire test suite takes a little over an hour to complete. I normally don't have to run the entire suite so it hasn't been a concern up to now, but it's something that I'd like to be able to do more regularly (ie, as part of an automated build)</p>
<p>I've been spending some time recently poking around with the Selenium Grid project whose purpose essentially is to allow those tests to run in parallel. Unfortunately, it seems that the TestDriven.net plugin that I'm using runs the tests serially (ie, one after another). I'm assuming that NUnit would execute the tests in a similar fashion, although I haven't actually tested this out. </p>
<p>I've noticed that the NUnit 2.5 betas are starting to talk about running tests in parallel with pNUnit, but I haven't really familiarized myself enough with the project to know for sure whether this would work. </p>
<p>Another option I'm considering is separating my test suite into different libraries which would let me run a test from each library concurrently, but I'd like to avoid that if possible since I'm not convinced this is a valid reason for splitting up the test suite.</p>
| [
{
"answer_id": 96318,
"author": "Jeff Martin",
"author_id": 13100,
"author_profile": "https://Stackoverflow.com/users/13100",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if no answer counts as an answer but I'd say you have researched everything and you really came up with the 2 possible solutions... </p>\n\n<ul>\n<li>Test Suite runs tests in parallel</li>\n<li>Split the test suite up</li>\n</ul>\n\n<p>I am at a loss for any thing else.</p>\n"
},
{
"answer_id": 326555,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote PNUnit as an extension for NUnit almost three years ago and I'm happy to see it was finally integrated into NUnit.</p>\n\n<p>We use it on a daily basis to test our software under different distros and combinations. Just to give an example: we've a test suite of heavy tests (long ones) with about 210 tests. Each of them sets up a server and runs a client in command line running several operations (up to 210 scenarios).</p>\n\n<p>Well, we use the same suite to run the tests on different Linux combinations and windows variations, and also combined ones like a windows server with a linux client, windows xp, vista, then domain controller, out of domain, and so on. We use the same binaries and then just have \"agents\" launched at several boxes.</p>\n\n<p>We use the same platform for: balancing load test load -> I mean, running in chunks faster. Running several combinations at the same time, and what I think is more interesting: defining multi client scenarios: two clients wait for the server to start up, then launch operations, synch with each other and so on. We also use PNUnit for load testing (hundreds of boxes against a single server).</p>\n\n<p>So, if you have any questions about how to set it up (which is not simple yet, I'm afraid), don't hesitate to ask.</p>\n\n<p>Also I wrote an article long ago about it at DDJ: <a href=\"http://www.ddj.com/architect/193104810\" rel=\"nofollow noreferrer\">http://www.ddj.com/architect/193104810</a></p>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 611452,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": 3,
"selected": false,
"text": "<p>I am working on this very thing and have found <a href=\"http://www.gallio.org/\" rel=\"noreferrer\">Gallio</a> latest can drive mbUnit tests in parallel. You can drive them against a single <a href=\"http://selenium-grid.seleniumhq.org/\" rel=\"noreferrer\">Selenium Grid</a> hub, which can have several remote control servers listening. </p>\n\n<p>I'm using the <a href=\"http://ccnet.gallio.org/Distributables/\" rel=\"noreferrer\">latest nightly from Gallio</a> to get the <a href=\"http://www.gallio.org/api/html/T_MbUnit_Framework_ParallelizableAttribute.html\" rel=\"noreferrer\">ParallelizableAttribute</a> and <a href=\"http://www.gallio.org/api/html/T_MbUnit_Framework_DegreeOfParallelismAttribute.html\" rel=\"noreferrer\">DegreeOfParallelismAttribute</a>. </p>\n\n<p>Something things I've noticed is I cannot rely on <code>TestSet</code> and <code>TestTeardown</code> be isolated the parallel tests. You'll need the test to look something like this:</p>\n\n<pre><code>[Test] public void Foo(){\n var s = new DefaultSelenium(\"http://grid\", 4444, \"*firefox\",\n \"http://server-under-test\");\n s.Start();\n s.Open(\"mypage.aspx\");\n // Continue\n s.Stop();\n\n}\n</code></pre>\n\n<p>Using the <code>[SetUp]</code> attribute to start the Selenium session was causing the tests to not get the remote session from <code>s.Start()</code>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6112/"
]
| **Has anyone found a way to run Selenium RC / Selenium Grid tests, written in C# in parallel?**
I've currently got a sizable test suite written using Selenium RC's C# driver. Running the entire test suite takes a little over an hour to complete. I normally don't have to run the entire suite so it hasn't been a concern up to now, but it's something that I'd like to be able to do more regularly (ie, as part of an automated build)
I've been spending some time recently poking around with the Selenium Grid project whose purpose essentially is to allow those tests to run in parallel. Unfortunately, it seems that the TestDriven.net plugin that I'm using runs the tests serially (ie, one after another). I'm assuming that NUnit would execute the tests in a similar fashion, although I haven't actually tested this out.
I've noticed that the NUnit 2.5 betas are starting to talk about running tests in parallel with pNUnit, but I haven't really familiarized myself enough with the project to know for sure whether this would work.
Another option I'm considering is separating my test suite into different libraries which would let me run a test from each library concurrently, but I'd like to avoid that if possible since I'm not convinced this is a valid reason for splitting up the test suite. | I am working on this very thing and have found [Gallio](http://www.gallio.org/) latest can drive mbUnit tests in parallel. You can drive them against a single [Selenium Grid](http://selenium-grid.seleniumhq.org/) hub, which can have several remote control servers listening.
I'm using the [latest nightly from Gallio](http://ccnet.gallio.org/Distributables/) to get the [ParallelizableAttribute](http://www.gallio.org/api/html/T_MbUnit_Framework_ParallelizableAttribute.html) and [DegreeOfParallelismAttribute](http://www.gallio.org/api/html/T_MbUnit_Framework_DegreeOfParallelismAttribute.html).
Something things I've noticed is I cannot rely on `TestSet` and `TestTeardown` be isolated the parallel tests. You'll need the test to look something like this:
```
[Test] public void Foo(){
var s = new DefaultSelenium("http://grid", 4444, "*firefox",
"http://server-under-test");
s.Start();
s.Open("mypage.aspx");
// Continue
s.Stop();
}
```
Using the `[SetUp]` attribute to start the Selenium session was causing the tests to not get the remote session from `s.Start()`. |
92,376 | <p>Is there any way that I can programmatically create (and I guess access) hidden folders on a storage device from within c#?</p>
| [
{
"answer_id": 92397,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 8,
"selected": true,
"text": "<pre><code>using System.IO; \n\nstring path = @\"c:\\folders\\newfolder\"; // or whatever \nif (!Directory.Exists(path)) \n{ \nDirectoryInfo di = Directory.CreateDirectory(path); \ndi.Attributes = FileAttributes.Directory | FileAttributes.Hidden; \n}\n</code></pre>\n"
},
{
"answer_id": 92400,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": false,
"text": "<p>Yes you can. Create the directory as normal then just set the attributes on it. E.g.</p>\n\n<pre><code>DirectoryInfo di = new DirectoryInfo(@\"C:\\SomeDirectory\");\n\n//See if directory has hidden flag, if not, make hidden\nif ((di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)\n{ \n //Add Hidden flag \n di.Attributes |= FileAttributes.Hidden; \n}\n</code></pre>\n"
},
{
"answer_id": 92410,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string path = @\"c:\\folders\\newfolder\"; // or whatever \nif (!System.IO.Directory.Exists(path)) \n{ \n DirectoryInfo di = Directory.CreateDirectory(path); \n di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; \n}\n</code></pre>\n\n<p>From <a href=\"http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=54724#54727\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 92468,
"author": "Phil J Pearson",
"author_id": 17667,
"author_profile": "https://Stackoverflow.com/users/17667",
"pm_score": 3,
"selected": false,
"text": "<pre><code>CreateHiddenFolder(string name) \n{ \n DirectoryInfo di = new DirectoryInfo(name); \n di.Create(); \n di.Attributes |= FileAttributes.Hidden; \n} \n</code></pre>\n"
},
{
"answer_id": 28437059,
"author": "Gul Muhammad",
"author_id": 4551403,
"author_profile": "https://Stackoverflow.com/users/4551403",
"pm_score": -1,
"selected": false,
"text": "<p>Code to get only Root folders path.</p>\n\n<p>Like If we have C:/Test/\nC:/Test/Abc\nC:/Test/xyz\nC:/Test2/\nC:/Test2/mnp</p>\n\n<p>It will return root folders path i.e.\nC:/Test/\nC:/Test2/</p>\n\n<pre><code> int index = 0;\n while (index < lst.Count)\n {\n My obj = lst[index];\n lst.RemoveAll(a => a.Path.StartsWith(obj.Path));\n lst.Insert(index, obj );\n index++; \n }\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
| Is there any way that I can programmatically create (and I guess access) hidden folders on a storage device from within c#? | ```
using System.IO;
string path = @"c:\folders\newfolder"; // or whatever
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
}
``` |
92,396 | <p>I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:</p>
<pre><code>switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
</code></pre>
<p>The above gives me the following error (MSC):</p>
<blockquote>
<p>initialization of 'newVal' is skipped by 'case' label</p>
</blockquote>
<p>This seems to be a limitation in other languages too. Why is this such a problem?</p>
| [
{
"answer_id": 92408,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": false,
"text": "<p>The whole switch statement is in the same scope. To get around it, do this:</p>\n\n<pre><code>switch (val)\n{\n case VAL:\n {\n // This **will** work\n int newVal = 42;\n }\n break;\n\n case ANOTHER_VAL:\n ...\n break;\n}\n</code></pre>\n\n<p><strong>Note</strong> the brackets.</p>\n"
},
{
"answer_id": 92414,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>switch (val)\n{\n case VAL:\n {\n int newVal = 42;\n }\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 92421,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the issue at hand is that is the statement was skipped, and you tried to use the var elsewhere, it wouldn't be declared.</p>\n"
},
{
"answer_id": 92422,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 3,
"selected": false,
"text": "<p>You can declare variables within a switch statement <em>if</em> you start a new block:</p>\n\n<pre><code>switch (thing)\n{ \n case A:\n {\n int i = 0; // Completely legal\n }\n break;\n}\n</code></pre>\n\n<p>The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).</p>\n"
},
{
"answer_id": 92423,
"author": "emk",
"author_id": 12089,
"author_profile": "https://Stackoverflow.com/users/12089",
"pm_score": 4,
"selected": false,
"text": "<p>You can't do this, because <code>case</code> labels are actually just entry points into the containing block.</p>\n\n<p>This is most clearly illustrated by <a href=\"http://en.wikipedia.org/wiki/Duff%27s_device\" rel=\"noreferrer\">Duff's device</a>. Here's some code from Wikipedia:</p>\n\n<pre><code>strcpy(char *to, char *from, size_t count) {\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n</code></pre>\n\n<p>Notice how the <code>case</code> labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a <code>case</code> label is the same as using <code>goto</code>, so you aren't allowed to jump over a local variable with a constructor.</p>\n\n<p>As several other posters have indicated, you need to put in a block of your own:</p>\n\n<pre><code>switch (...) {\n case FOO: {\n MyObject x(...);\n ...\n break; \n }\n ...\n }\n</code></pre>\n"
},
{
"answer_id": 92424,
"author": "marijne",
"author_id": 7038,
"author_profile": "https://Stackoverflow.com/users/7038",
"pm_score": 0,
"selected": false,
"text": "<p>newVal exists in the entire scope of the switch but is only initialised if the VAL limb is hit. If you create a block around the code in VAL it should be OK.</p>\n"
},
{
"answer_id": 92432,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead:</p>\n\n<pre><code>switch (val) \n{ \ncase VAL:\n{\n // This will work\n int newVal = 42;\n break;\n}\ncase ANOTHER_VAL: \n ...\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 92439,
"author": "TJ Seabrooks",
"author_id": 3022,
"author_profile": "https://Stackoverflow.com/users/3022",
"pm_score": 11,
"selected": true,
"text": "<p><code>Case</code> statements are only <strong>labels</strong>. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the <code>switch</code> statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. </p>\n\n<p>The correct way to handle this is to define a scope specific to that <code>case</code> statement and define your variable within it:</p>\n\n<pre><code>switch (val)\n{ \ncase VAL: \n{\n // This will work\n int newVal = 42; \n break;\n}\ncase ANOTHER_VAL: \n...\nbreak;\n}\n</code></pre>\n"
},
{
"answer_id": 92473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If your code says \"int newVal=42\" then you would reasonably expect that newVal is never uninitialised. But if you goto over this statement (which is what you're doing) then that's exactly what happens - newVal is in-scope but has not been assigned.</p>\n\n<p>If that is what you really meant to happen then the language requires to make it explicit by saying \"int newVal; newVal = 42;\". Otherwise you can limit the scope of newVal to the single case, which is more likely what you wanted.</p>\n\n<p>It may clarify things if you consider the same example but with \"const int newVal = 42;\"</p>\n"
},
{
"answer_id": 92477,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 3,
"selected": false,
"text": "<p>Consider:</p>\n\n<pre><code>switch(val)\n{\ncase VAL:\n int newVal = 42;\ndefault:\n int newVal = 23;\n}\n</code></pre>\n\n<p>In the absence of break statements, sometimes newVal gets declared twice, and you don't know whether it does until runtime. My guess is that the limitation is because of this kind of confusion. What would the scope of newVal be? Convention would dictate that it would be the whole of the switch block (between the braces).</p>\n\n<p>I'm no C++ programmer, but in C:</p>\n\n<pre><code>switch(val) {\n int x;\n case VAL:\n x=1;\n}\n</code></pre>\n\n<p>Works fine. Declaring a variable inside a switch block is fine. Declaring after a case guard is not.</p>\n"
},
{
"answer_id": 92497,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>New variables can be decalared only at block scope. You need to write something like this:</p>\n\n<pre><code>case VAL: \n // This will work\n {\n int newVal = 42; \n }\n break;\n</code></pre>\n\n<p>Of course, newVal only has scope within the braces...</p>\n\n<p>Cheers, Ralph</p>\n"
},
{
"answer_id": 92730,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 7,
"selected": false,
"text": "<p>Ok. Just to clarify this strictly has nothing to do with the declaration. It relates only to "jumping over the initialization" (ISO C++ '03 6.7/3)</p>\n<p>A lot of the posts here have mentioned that jumping over the declaration may result in the variable "not being declared". This is not true. An POD object can be declared without an initializer but it will have an indeterminate value. For example:</p>\n<pre><code>switch (i)\n{\n case 0:\n int j; // 'j' has indeterminate value\n j = 0; // 'j' set (not initialized) to 0, but this statement\n // is jumped when 'i == 1'\n break;\n case 1:\n ++j; // 'j' is in scope here - but it has an indeterminate value\n break;\n}\n</code></pre>\n<p>Where the object is a non-POD or aggregate the compiler implicitly adds an initializer, and so it is not possible to jump over such a declaration:</p>\n<pre><code>class A {\npublic:\n A ();\n};\n\nswitch (i) // Error - jumping over initialization of 'A'\n{\n case 0:\n A j; // Compiler implicitly calls default constructor\n break;\n case 1:\n break;\n}\n</code></pre>\n<p>This limitation is not limited to the switch statement. It is also an error to use 'goto' to jump over an initialization:</p>\n<pre><code>goto LABEL; // Error jumping over initialization\nint j = 0; \nLABEL:\n ;\n</code></pre>\n<p>A bit of trivia is that this is a difference between C++ and C. In C, it is not an error to jump over the initialization.</p>\n<p>As others have mentioned, the solution is to add a nested block so that the lifetime of the variable is limited to the individual case label.</p>\n"
},
{
"answer_id": 92788,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 4,
"selected": false,
"text": "<p>Most of the replies so far are wrong in one respect: you <strong>can</strong> declare variables after the case statement, but you <em>can't</em> initialize them:</p>\n\n<pre><code>case 1:\n int x; // Works\n int y = 0; // Error, initialization is skipped by case\n break;\ncase 2:\n ...\n</code></pre>\n\n<p>As previously mentioned, a nice way around this is to use braces to create a scope for your case.</p>\n"
},
{
"answer_id": 94483,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite evil switch trick is to use an if(0) to skip over an unwanted case label.</p>\n\n<pre><code>switch(val)\n{\ncase 0:\n// Do something\nif (0) {\ncase 1:\n// Do something else\n}\ncase 2:\n// Do something in all cases\n}\n</code></pre>\n\n<p>But very evil.</p>\n"
},
{
"answer_id": 212390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I just wanted to emphasize <em>slim</em>'s <a href=\"https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement#answer-92477\">point</a>. A switch construct creates a whole, first-class-citizen scope. So it is posible to declare (and initialize) a variable in a switch statement before the first case label, <strong>without</strong> an additional bracket pair:</p>\n\n<pre><code>switch (val) { \n /* This *will* work, even in C89 */\n int newVal = 42; \ncase VAL:\n newVal = 1984; \n break;\ncase ANOTHER_VAL: \n newVal = 2001;\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 1368293,
"author": "Peter",
"author_id": 160054,
"author_profile": "https://Stackoverflow.com/users/160054",
"pm_score": 2,
"selected": false,
"text": "<p>So far the answers have been for C++.</p>\n\n<p>For C++, you can't jump over an initialization. You can in C. However, in C, a declaration is not a statement, and case labels have to be followed by statements.</p>\n\n<p>So, valid (but ugly) C, invalid C++</p>\n\n<pre><code>switch (something)\n{\n case 1:; // Ugly hack empty statement\n int i = 6;\n do_stuff_with_i(i);\n break;\n case 2:\n do_something();\n break;\n default:\n get_a_life();\n}\n</code></pre>\n\n<p>Conversly, in C++, a declaration is a statement, so the following is valid C++, invalid C</p>\n\n<pre><code>switch (something)\n{\n case 1:\n do_something();\n break;\n case 2:\n int i = 12;\n do_something_else();\n}\n</code></pre>\n"
},
{
"answer_id": 3654361,
"author": "Dan",
"author_id": 438082,
"author_profile": "https://Stackoverflow.com/users/438082",
"pm_score": 2,
"selected": false,
"text": "<p>Interesting that this is fine:</p>\n\n<pre><code>switch (i) \n{ \ncase 0: \n int j; \n j = 7; \n break; \n\ncase 1: \n break;\n}\n</code></pre>\n\n<p>... but this isn't:</p>\n\n<pre><code>switch (i) \n{ \ncase 0: \n int j = 7; \n break; \n\ncase 1: \n break;\n}\n</code></pre>\n\n<p>I get that a fix is simple enough, but I'm not understanding yet why the first example doesn't bother the compiler. As was mentioned earlier (2 years earlier hehe), <strong>declaration</strong> is not what causes the error, even despite the logic. Initialisation is the problem. If the variable is initialised and declared on the different lines, it compiles.</p>\n"
},
{
"answer_id": 8550253,
"author": "Jeegar Patel",
"author_id": 775964,
"author_profile": "https://Stackoverflow.com/users/775964",
"pm_score": 5,
"selected": false,
"text": "<p>After reading all answers and some more research I get a few things.</p>\n\n<pre><code>Case statements are only 'labels'\n</code></pre>\n\n<p><strong>In C, according to the specification,</strong></p>\n\n<p>§6.8.1 Labeled Statements:</p>\n\n<pre><code>labeled-statement:\n identifier : statement\n case constant-expression : statement\n default : statement\n</code></pre>\n\n<p>In C there isn't any clause that allows for a \"labeled declaration\". It's just not part of the language.</p>\n\n<p>So</p>\n\n<pre><code>case 1: int x=10;\n printf(\" x is %d\",x);\nbreak;\n</code></pre>\n\n<p>This <strong>will not compile</strong>, see <a href=\"http://codepad.org/YiyLQTYw\" rel=\"noreferrer\">http://codepad.org/YiyLQTYw</a>. GCC is giving an error:</p>\n\n<pre><code>label can only be a part of statement and declaration is not a statement\n</code></pre>\n\n<p>Even</p>\n\n<pre><code> case 1: int x;\n x=10;\n printf(\" x is %d\",x);\n break;\n</code></pre>\n\n<p>this is <strong>also not compiling</strong>, see <a href=\"http://codepad.org/BXnRD3bu\" rel=\"noreferrer\">http://codepad.org/BXnRD3bu</a>. Here I am also getting the same error.</p>\n\n<hr>\n\n<p><strong>In C++, according to the specification,</strong></p>\n\n<p>labeled-declaration is allowed but labeled -initialization is not allowed.</p>\n\n<p>See <a href=\"http://codepad.org/ZmQ0IyDG\" rel=\"noreferrer\">http://codepad.org/ZmQ0IyDG</a>.</p>\n\n<hr>\n\n<p><strong>Solution to such condition is two</strong></p>\n\n<ol>\n<li><p>Either use new scope using {}</p>\n\n<pre><code>case 1:\n {\n int x=10;\n printf(\" x is %d\", x);\n }\nbreak;\n</code></pre></li>\n<li><p>Or use dummy statement with label</p>\n\n<pre><code>case 1: ;\n int x=10;\n printf(\" x is %d\",x);\nbreak;\n</code></pre></li>\n<li><p>Declare the variable before switch() and initialize it with different values in case statement if it fulfills your requirement</p>\n\n<pre><code>main()\n{\n int x; // Declare before\n switch(a)\n {\n case 1: x=10;\n break;\n\n case 2: x=20;\n break;\n }\n}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p><strong>Some more things with switch statement</strong></p>\n\n<p>Never write any statements in the switch which are not part of any label, because they will never executed:</p>\n\n<pre><code>switch(a)\n{\n printf(\"This will never print\"); // This will never executed\n\n case 1:\n printf(\" 1\");\n break;\n\n default:\n break;\n}\n</code></pre>\n\n<p>See <a href=\"http://codepad.org/PA1quYX3\" rel=\"noreferrer\">http://codepad.org/PA1quYX3</a>.</p>\n"
},
{
"answer_id": 11408021,
"author": "Jingguo Yao",
"author_id": 431698,
"author_profile": "https://Stackoverflow.com/users/431698",
"pm_score": 0,
"selected": false,
"text": "<p>C++ Standard has:\nIt is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).</p>\n\n<p>The code to illustrate this rule:</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nclass X {\n public:\n X() \n {\n cout << \"constructor\" << endl;\n }\n ~X() \n {\n cout << \"destructor\" << endl;\n }\n};\n\ntemplate <class type>\nvoid ill_formed()\n{\n goto lx;\nly:\n type a;\nlx:\n goto ly;\n}\n\ntemplate <class type>\nvoid ok()\n{\nly:\n type a;\nlx:\n goto ly;\n}\n\nvoid test_class()\n{\n ok<X>();\n // compile error\n ill_formed<X>();\n}\n\nvoid test_scalar() \n{\n ok<int>();\n ill_formed<int>();\n}\n\nint main(int argc, const char *argv[]) \n{\n return 0;\n}\n</code></pre>\n\n<p>The code to show the initializer effect:</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nint test1()\n{\n int i = 0;\n // There jumps fo \"case 1\" and \"case 2\"\n switch(i) {\n case 1:\n // Compile error because of the initializer\n int r = 1; \n break;\n case 2:\n break;\n };\n}\n\nvoid test2()\n{\n int i = 2;\n switch(i) {\n case 1:\n int r;\n r= 1; \n break;\n case 2:\n cout << \"r: \" << r << endl;\n break;\n };\n}\n\nint main(int argc, const char *argv[]) \n{\n test1();\n test2();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 14770979,
"author": "Olumide",
"author_id": 181783,
"author_profile": "https://Stackoverflow.com/users/181783",
"pm_score": 0,
"selected": false,
"text": "<p>It appears that anonymous objects <em>can</em> be declared or created in a switch case statement for the reason that they cannot be referenced and as such cannot fall through to the next case. Consider this example compiles on GCC 4.5.3 and Visual Studio 2008 (might be a compliance issue tho' so experts please weigh in)</p>\n\n<pre><code>#include <cstdlib>\n\nstruct Foo{};\n\nint main()\n{\n int i = 42;\n\n switch( i )\n {\n case 42:\n Foo(); // Apparently valid\n break;\n\n default:\n break;\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n"
},
{
"answer_id": 19830820,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 9,
"selected": false,
"text": "<p>This question was originally tagged as <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a> and <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> at the same time. The original code is indeed invalid in both C and C++, but for completely different unrelated reasons.</p>\n<ul>\n<li><p>In C++ this code is invalid because the <code>case ANOTHER_VAL:</code> label jumps into the scope of variable <code>newVal</code> bypassing its initialization. Jumps that bypass initialization of automatic objects are illegal in C++. This side of the issue is correctly addressed by most answers.</p>\n</li>\n<li><p>However, in C language bypassing variable initialization is not an error. Jumping into the scope of a variable over its initialization is legal in C. It simply means that the variable is left uninitialized. The original code does not compile in C for a completely different reason. Label <code>case VAL:</code> in the original code is attached to the declaration of variable <code>newVal</code>. In C language declarations are not statements. They cannot be labeled. And this is what causes the error when this code is interpreted as C code.</p>\n<pre><code> switch (val) \n { \n case VAL: /* <- C error is here */\n int newVal = 42; \n break;\n case ANOTHER_VAL: /* <- C++ error is here */\n ...\n break;\n }\n</code></pre>\n<p>Adding an extra <code>{}</code> block fixes both C++ and C problems, even though these problems happen to be very different. On the C++ side it restricts the scope of <code>newVal</code>, making sure that <code>case ANOTHER_VAL:</code> no longer jumps into that scope, which eliminates the C++ issue. On the C side that extra <code>{}</code> introduces a compound statement, thus making the <code>case VAL:</code> label to apply to a statement, which eliminates the C issue.</p>\n</li>\n<li><p>In C case the problem can be easily solved without the <code>{}</code>. Just add an empty statement after the <code>case VAL:</code> label and the code will become valid</p>\n<pre><code> switch (val) \n { \n case VAL:; /* Now it works in C! */\n int newVal = 42; \n break;\n case ANOTHER_VAL: \n ...\n break;\n }\n</code></pre>\n<p>Note that even though it is now valid from C point of view, it remains invalid from C++ point of view.</p>\n</li>\n<li><p>Symmetrically, in C++ case the the problem can be easily solved without the <code>{}</code>. Just remove the initializer from variable declaration and the code will become valid</p>\n<pre><code> switch (val) \n { \n case VAL: \n int newVal;\n newVal = 42; \n break;\n case ANOTHER_VAL: /* Now it works in C++! */\n ...\n break;\n }\n</code></pre>\n<p>Note that even though it is now valid from C++ point of view, it remains invalid from C point of view.</p>\n</li>\n</ul>\n<p>Starting from C23 all labels in C language will be interpreted as labelling implied null statements (<a href=\"https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2508.pdf\" rel=\"noreferrer\">N2508</a>), i.e. the issue with being unable to place labels in front of declarations in C will no longer exist and the above <code>;</code>-based fix will no longer be necessary.</p>\n"
},
{
"answer_id": 27733339,
"author": "Dalmas",
"author_id": 533552,
"author_profile": "https://Stackoverflow.com/users/533552",
"pm_score": 2,
"selected": false,
"text": "<p>A <code>switch</code> block <strong>isn't the same as a succession of <code>if/else if</code> blocks.</strong> I'm surprised no other answer explains it clearly.</p>\n\n<p>Consider this <code>switch</code> statement :</p>\n\n<pre><code>switch (value) {\n case 1:\n int a = 10;\n break;\n case 2:\n int a = 20;\n break;\n}\n</code></pre>\n\n<p>It may be surprising, but the compiler will not see it as a simple <code>if/else if</code>. It will produce the following code :</p>\n\n<pre><code>if (value == 1)\n goto label_1;\nelse if (value == 2)\n goto label_2;\nelse\n goto label_end;\n\n{\nlabel_1:\n int a = 10;\n goto label_end;\nlabel_2:\n int a = 20; // Already declared !\n goto label_end;\n}\n\nlabel_end:\n // The code after the switch block\n</code></pre>\n\n<p>The <code>case</code> statements are converted into labels and then called with <code>goto</code>. The brackets create a new scope and it is easy to see now why you can't declare two variables with the same name within a <code>switch</code> block.</p>\n\n<p>It may look weird, but it is necessary to support <em>fallthrough</em> (that is, not using <code>break</code> to let execution continue to the next <code>case</code>). </p>\n"
},
{
"answer_id": 37368542,
"author": "PcAF",
"author_id": 4932834,
"author_profile": "https://Stackoverflow.com/users/4932834",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote this answer orginally for <a href=\"https://stackoverflow.com/questions/37368137/c-why-can-we-define-a-variable-in-case-of-switch\">this question</a>. However when I finished it I found that answer has been closed. So I posted it here, maybe someone who likes references to standard will find it helpful.</p>\n\n<p>Original Code in question:</p>\n\n<pre><code>int i;\ni = 2;\nswitch(i)\n{\n case 1: \n int k;\n break;\n case 2:\n k = 1;\n cout<<k<<endl;\n break;\n}\n</code></pre>\n\n<p>There are actually 2 questions:</p>\n\n<p><strong>1. Why can I declare a variable after <code>case</code> label?</strong></p>\n\n<p>It's because in C++ label has to be in form:</p>\n\n<p>N3337 6.1/1</p>\n\n<blockquote>\n <p>labeled-statement:</p>\n \n <p>...</p>\n \n <ul>\n <li><em>attribute-specifier-seqopt</em> <code>case</code> <code>constant-expression</code> : <code>statement</code></li>\n </ul>\n \n <p>...</p>\n</blockquote>\n\n<p>And in <code>C++</code> <em>declaration statement</em> is also considered as <em>statement</em> (as opposed to <code>C</code>):</p>\n\n<p>N3337 6/1:</p>\n\n<blockquote>\n <p><em>statement</em>:</p>\n \n <p>...</p>\n \n <p><em>declaration-statement</em></p>\n \n <p>...</p>\n</blockquote>\n\n<p><strong>2. Why can I jump over variable declaration and then use it?</strong></p>\n\n<p>Because:\nN3337 6.7/3</p>\n\n<blockquote>\n <p>It is possible to transfer into a block, <strong>but not in a way that bypasses declarations with initialization</strong>. A\n program that jumps\n (The <strong>transfer from</strong> the condition of a <strong>switch statement to a case label is considered a jump</strong> in this respect.)</p>\n \n <p><strong>from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed</strong> <strong>unless the variable has scalar type</strong>, class type with a trivial default\n constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the\n preceding types and is declared without an initializer (8.5).</p>\n</blockquote>\n\n<p>Since <code>k</code> is of <em>scalar type</em>, and is not initialized at point of declaration jumping over it's declaration is possible. This is semantically equivalent:</p>\n\n<pre><code>goto label;\n\nint x;\n\nlabel:\ncout << x << endl;\n</code></pre>\n\n<p>However that wouldn't be possible, if <code>x</code> was initialized at point of declaration:</p>\n\n<pre><code> goto label;\n\n int x = 58; //error, jumping over declaration with initialization\n\n label:\n cout << x << endl;\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:
```
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
```
The above gives me the following error (MSC):
>
> initialization of 'newVal' is skipped by 'case' label
>
>
>
This seems to be a limitation in other languages too. Why is this such a problem? | `Case` statements are only **labels**. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the `switch` statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization.
The correct way to handle this is to define a scope specific to that `case` statement and define your variable within it:
```
switch (val)
{
case VAL:
{
// This will work
int newVal = 42;
break;
}
case ANOTHER_VAL:
...
break;
}
``` |
92,413 | <p>I have a SQL Server 2000, C# & ASP.net web app. We want to control access to it by using Active Directory groups. I can get authentication to work if the group I put in is a 'Global' but not if the group is 'Universal'. </p>
<p>How can I make this work with 'Universal' groups an well?
Here's my authorization block:</p>
<pre><code> <authorization>
<allow roles="domain\Group Name Here"/>
<allow roles="domain\Group Name Here2"/>
<allow roles="domain\Group Name Here3"/>
<deny users="*"/>
</authorization>
</code></pre>
| [
{
"answer_id": 92919,
"author": "jliszka",
"author_id": 9767,
"author_profile": "https://Stackoverflow.com/users/9767",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on your Active Directory topology, you might have to wait for the Universal Group membership to replicate around to all the Domain Controllers. Active Directory recommends the following though:</p>\n\n<ol>\n<li>Create a Global group for each domain, e.g., \"Domain A Authorized Users\", \"Domain B Authorized Users\"</li>\n<li>Put the users you want from Domain A in the \"Domain A Authorized Users\" group, etc</li>\n<li>Create a Universal group in the root domain \"All Authorized Users\"</li>\n<li>Put the Global groups in the Universal group</li>\n<li>Secure the resource using the Universal group: <allow roles=\"root domain\\All Authorized Users/></li>\n<li>Wait for replication</li>\n</ol>\n\n<p>One advantage of this scheme is that when you add a new user to one of the Global groups, you won't have to wait for GC replication.</p>\n"
},
{
"answer_id": 103713,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 1,
"selected": true,
"text": "<p>Turns out I needed to use the \"Pre Win2000\" id not the regular one.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
| I have a SQL Server 2000, C# & ASP.net web app. We want to control access to it by using Active Directory groups. I can get authentication to work if the group I put in is a 'Global' but not if the group is 'Universal'.
How can I make this work with 'Universal' groups an well?
Here's my authorization block:
```
<authorization>
<allow roles="domain\Group Name Here"/>
<allow roles="domain\Group Name Here2"/>
<allow roles="domain\Group Name Here3"/>
<deny users="*"/>
</authorization>
``` | Turns out I needed to use the "Pre Win2000" id not the regular one. |
92,427 | <p>Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control. The style did not end up rendering to the output HTML. Even if it was possible, I'm sure it is bad practice to do this.</p>
<p>Is it possible to do this? I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply.</p>
| [
{
"answer_id": 92444,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "<p>I think you will have to add it as an attribute to the server control... for it to render to HTML.</p>\n\n<p>So basically (in C#),</p>\n\n<pre><code>ControlName.Attributes[\"style\"] = \"color:red\";\n</code></pre>\n"
},
{
"answer_id": 92506,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 6,
"selected": false,
"text": "<p>Intellisense won't give you hints but you can do this:</p>\n\n<pre><code><asp:Label ID=\"Label1\" runat=\"server\" Text=\"Label\" style=\"color:Red;\"></asp:Label>\n</code></pre>\n"
},
{
"answer_id": 92585,
"author": "Tom Robinson",
"author_id": 12124,
"author_profile": "https://Stackoverflow.com/users/12124",
"pm_score": 5,
"selected": true,
"text": "<p>According to <a href=\"http://www.w3schools.com/TAGS/tag_style.asp\" rel=\"nofollow noreferrer\">www.w3schools.com</a>:</p>\n\n<blockquote>\n <p>The style element goes in the head section. If you want to include a style sheet in your page, you should define the style sheet externally, and link to it using <code><link></code>.</p>\n</blockquote>\n\n<p>So it's not a good idea to include style elements (e.g. a <code><style type=\"text\\css\"></style></code> block) in a control. If you could, it'd probably have an effect in some browsers but it wouldn't validate and is bad practice.</p>\n\n<p>If you want to apply styles inline to an element then either of these would work:</p>\n\n<p>C#</p>\n\n<pre><code>myControl.Attributes[\"style\"] = \"color:red\";\n\nmyControl.Attributes.Add(\"style\", \"color:red\");\n</code></pre>\n\n<p>VB.NET</p>\n\n<pre><code>myControl.Attributes(\"style\") = \"color:red\";\n\nmyControl.Attributes.Add(\"style\", \"color:red\");\n</code></pre>\n\n<p>But bear in mind that <em>this will replace any existing styles that are set on the style attribute</em>. This may be a problem if you try setting styles in more than one place in the code so is something to watch out for.</p>\n\n<p>Using CSS classes would be preferable as you can group multiple style declarations and avoid redundancy and page bloat. All controls derived from <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.aspx\" rel=\"nofollow noreferrer\">WebControl</a> have a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx\" rel=\"nofollow noreferrer\">CssClass</a> property which you can use, but again be careful not to overwrite existing classes that have been applied elsewhere.</p>\n"
},
{
"answer_id": 24492708,
"author": "Hutch",
"author_id": 2661556,
"author_profile": "https://Stackoverflow.com/users/2661556",
"pm_score": 3,
"selected": false,
"text": "<p>If you use Attributes["style"], you are overwriting the style each time you call it. This can be an issue if you are making the call in two different sections of code. As well, it can be an issue because the framework includes properties for basic settings like border and colour that also will be applied as inline styles. Here is an example:</p>\n<pre><code>// dangerous: first style will be overwritten\nmyControl.Attributes["style"] = "text-align:center";\n// in some other section of code\nmyControl.Attributes["style"] = "width:100%";\n</code></pre>\n<p>To play nicely, set styles like this instead:</p>\n<pre><code>// correct: both style settings are applied\nmyControl.Attributes.CssStyle.Add("text-align", "center");\n// in some other section of code\nmyControl.Attributes.CssStyle.Add("width", "100%");\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
| Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control. The style did not end up rendering to the output HTML. Even if it was possible, I'm sure it is bad practice to do this.
Is it possible to do this? I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply. | According to [www.w3schools.com](http://www.w3schools.com/TAGS/tag_style.asp):
>
> The style element goes in the head section. If you want to include a style sheet in your page, you should define the style sheet externally, and link to it using `<link>`.
>
>
>
So it's not a good idea to include style elements (e.g. a `<style type="text\css"></style>` block) in a control. If you could, it'd probably have an effect in some browsers but it wouldn't validate and is bad practice.
If you want to apply styles inline to an element then either of these would work:
C#
```
myControl.Attributes["style"] = "color:red";
myControl.Attributes.Add("style", "color:red");
```
VB.NET
```
myControl.Attributes("style") = "color:red";
myControl.Attributes.Add("style", "color:red");
```
But bear in mind that *this will replace any existing styles that are set on the style attribute*. This may be a problem if you try setting styles in more than one place in the code so is something to watch out for.
Using CSS classes would be preferable as you can group multiple style declarations and avoid redundancy and page bloat. All controls derived from [WebControl](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.aspx) have a [CssClass](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass.aspx) property which you can use, but again be careful not to overwrite existing classes that have been applied elsewhere. |
92,438 | <p>I use to run</p>
<pre><code>$s =~ s/[^[:print:]]//g;
</code></pre>
<p>on Perl to get rid of non printable characters. </p>
<p>In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. </p>
<p>What would you do? </p>
<p>EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.</p>
| [
{
"answer_id": 92441,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>The best I've come up with now is (thanks to the python-izers above) </p>\n\n<pre><code>def filter_non_printable(str):\n return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])\n</code></pre>\n\n<p>This is the only way I've found out that works with Unicode characters/strings</p>\n\n<p>Any better options?</p>\n"
},
{
"answer_id": 92488,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 6,
"selected": false,
"text": "<p>As far as I know, the most pythonic/efficient method would be:</p>\n\n<pre><code>import string\n\nfiltered_string = filter(lambda x: x in string.printable, myStr)\n</code></pre>\n"
},
{
"answer_id": 92509,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 3,
"selected": false,
"text": "<p>This function uses list comprehensions and str.join, so it runs in linear time instead of O(n^2):</p>\n\n<pre><code>from curses.ascii import isprint\n\ndef printable(input):\n return ''.join(char for char in input if isprint(char))\n</code></pre>\n"
},
{
"answer_id": 93029,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 8,
"selected": true,
"text": "<p>Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The <em>unicodedata</em> module is quite helpful for this, especially the <em>unicodedata.category()</em> function. See <a href=\"http://www.unicode.org/reports/tr44/#General_Category_Values\" rel=\"noreferrer\">Unicode Character Database</a> for descriptions of the categories.</p>\n<pre><code>import unicodedata, re, itertools, sys\n\nall_chars = (chr(i) for i in range(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n</code></pre>\n<p>For Python2</p>\n<pre><code>import unicodedata, re, sys\n\nall_chars = (unichr(i) for i in xrange(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n</code></pre>\n<p>For some use-cases, additional categories (e.g. all from the <em>control</em> group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:</p>\n<ul>\n<li><code>Cc</code> (control): 65</li>\n<li><code>Cf</code> (format): 161</li>\n<li><code>Cs</code> (surrogate): 2048</li>\n<li><code>Co</code> (private-use): 137468</li>\n<li><code>Cn</code> (unassigned): 836601</li>\n</ul>\n<p><em><strong>Edit</strong> Adding suggestions from the comments.</em></p>\n"
},
{
"answer_id": 93557,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "<p>You could try setting up a filter using the <code>unicodedata.category()</code> function:</p>\n\n<pre><code>import unicodedata\nprintable = {'Lu', 'Ll'}\ndef filter_non_printable(str):\n return ''.join(c for c in str if unicodedata.category(c) in printable)\n</code></pre>\n\n<p>See Table 4-9 on page 175 in the <a href=\"http://www.unicode.org/versions/Unicode9.0.0/ch04.pdf\" rel=\"noreferrer\">Unicode database character properties</a> for the available categories</p>\n"
},
{
"answer_id": 25829509,
"author": "shawnrad",
"author_id": 4038859,
"author_profile": "https://Stackoverflow.com/users/4038859",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3,</p>\n<pre><code>def filter_nonprintable(text):\n import itertools\n # Use characters of control category\n nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))\n # Use translate to remove all non-printable characters\n return text.translate({character:None for character in nonprintable})\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python\">this StackOverflow post on removing punctuation</a> for how .translate() compares to regex & .replace()</p>\n<p>The ranges can be generated via <code>nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc')</code> using the <a href=\"http://www.unicode.org/reports/tr44/#General_Category_Values\" rel=\"nofollow noreferrer\">Unicode character database categories</a> as shown by @Ants Aasma.</p>\n"
},
{
"answer_id": 46148658,
"author": "knowingpark",
"author_id": 951739,
"author_profile": "https://Stackoverflow.com/users/951739",
"pm_score": 1,
"selected": false,
"text": "<p>To remove 'whitespace',</p>\n\n<pre><code>import re\nt = \"\"\"\n\\n\\t<p>&nbsp;</p>\\n\\t<p>&nbsp;</p>\\n\\t<p>&nbsp;</p>\\n\\t<p>&nbsp;</p>\\n\\t<p>\n\"\"\"\npat = re.compile(r'[\\t\\n]')\nprint(pat.sub(\"\", t))\n</code></pre>\n"
},
{
"answer_id": 48133754,
"author": "Nilav Baran Ghosh",
"author_id": 1055704,
"author_profile": "https://Stackoverflow.com/users/1055704",
"pm_score": 2,
"selected": false,
"text": "<p>The one below performs faster than the others above. Take a look</p>\n\n<pre><code>''.join([x if x in string.printable else '' for x in Str])\n</code></pre>\n"
},
{
"answer_id": 51185178,
"author": "Risadinha",
"author_id": 621690,
"author_profile": "https://Stackoverflow.com/users/621690",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>In Python there's no POSIX regex classes</p>\n</blockquote>\n\n<p>There are when using the <code>regex</code> library: <a href=\"https://pypi.org/project/regex/\" rel=\"nofollow noreferrer\">https://pypi.org/project/regex/</a></p>\n\n<p>It is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is <strong>very</strong> similar to Python's <code>re</code>.</p>\n\n<p>From the documentation:</p>\n\n<blockquote>\n <p><code>[[:alpha:]]; [[:^alpha:]]</code></p>\n \n <p>POSIX character classes are supported. These\n are normally treated as an alternative form of <code>\\p{...}</code>.</p>\n</blockquote>\n\n<p>(I'm not affiliated, just a user.)</p>\n"
},
{
"answer_id": 52540226,
"author": "c6401",
"author_id": 4824716,
"author_profile": "https://Stackoverflow.com/users/4824716",
"pm_score": 3,
"selected": false,
"text": "<p>Yet another option in python 3:</p>\n\n<pre><code>re.sub(f'[^{re.escape(string.printable)}]', '', my_string)\n</code></pre>\n"
},
{
"answer_id": 54451873,
"author": "ChrisP",
"author_id": 892534,
"author_profile": "https://Stackoverflow.com/users/892534",
"pm_score": 4,
"selected": false,
"text": "<p>The following will work with Unicode input and is rather fast...</p>\n\n<pre><code>import sys\n\n# build a table mapping all non-printable characters to None\nNOPRINT_TRANS_TABLE = {\n i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()\n}\n\ndef make_printable(s):\n \"\"\"Replace non-printable characters in a string.\"\"\"\n\n # the translate method on str removes characters\n # that map to None from the string\n return s.translate(NOPRINT_TRANS_TABLE)\n\n\nassert make_printable('Café') == 'Café'\nassert make_printable('\\x00\\x11Hello') == 'Hello'\nassert make_printable('') == ''\n</code></pre>\n\n<p>My own testing suggests this approach is faster than functions that iterate over the string and return a result using <code>str.join</code>.</p>\n"
},
{
"answer_id": 62437138,
"author": "Joe",
"author_id": 5306011,
"author_profile": "https://Stackoverflow.com/users/5306011",
"pm_score": 2,
"selected": false,
"text": "<p>Adapted from answers by <a href=\"https://stackoverflow.com/a/93029/5306011\">Ants Aasma</a> and <a href=\"https://stackoverflow.com/a/25829509/5306011\">shawnrad</a>:</p>\n\n<pre><code>nonprintable = set(map(chr, list(range(0,32)) + list(range(127,160))))\nord_dict = {ord(character):None for character in nonprintable}\ndef filter_nonprintable(text):\n return text.translate(ord_dict)\n\n#use\nstr = \"this is my string\"\nstr = filter_nonprintable(str)\nprint(str)\n</code></pre>\n\n<p>tested on Python 3.7.7</p>\n"
},
{
"answer_id": 62530464,
"author": "darkdragon",
"author_id": 3779655,
"author_profile": "https://Stackoverflow.com/users/3779655",
"pm_score": 3,
"selected": false,
"text": "<p>Based on @Ber's answer, I suggest removing only control characters as defined in the <a href=\"http://www.unicode.org/reports/tr44/#General_Category_Values\" rel=\"noreferrer\">Unicode character database categories</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import unicodedata\ndef filter_non_printable(s):\n return ''.join(c for c in s if not unicodedata.category(c).startswith('C'))\n</code></pre>\n"
},
{
"answer_id": 71105750,
"author": "Thomas Juul Dyhr",
"author_id": 6905974,
"author_profile": "https://Stackoverflow.com/users/6905974",
"pm_score": 2,
"selected": false,
"text": "<p>An elegant pythonic solution to stripping 'non printable' characters from a string in python is to use the isprintable() string method together with a generator expression or list comprehension depending on the use case ie. size of the string:</p>\n<pre><code> ''.join(c for c in my_string if c.isprintable())\n</code></pre>\n<p>str.isprintable()\nReturn True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)</p>\n"
},
{
"answer_id": 72879204,
"author": "thrinadhn",
"author_id": 5836700,
"author_profile": "https://Stackoverflow.com/users/5836700",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Error description\nRun the copied and pasted python code report:</li>\n</ol>\n<p>Python invalid non-printable character U+00A0</p>\n<ol start=\"2\">\n<li><p>The cause of the error\nThe space in the copied code is not the same as the format in Python;</p>\n</li>\n<li><p>Solution\nDelete the space and re-enter the space. For example, the red part in the above picture is an abnormal space. Delete and re-enter the space to run;</p>\n</li>\n</ol>\n<p>Source : <a href=\"https://blog.karatos.in/a?ID=01800-42a1f28f-71b6-497e-9a94-072b6234b28d\" rel=\"nofollow noreferrer\">Python invalid non-printable character U+00A0\n</a></p>\n"
},
{
"answer_id": 74555580,
"author": "Tim Richardson",
"author_id": 401226,
"author_profile": "https://Stackoverflow.com/users/401226",
"pm_score": 0,
"selected": false,
"text": "<p>I used this:</p>\n<pre><code>import sys\nimport unicodedata\n\n# the test string has embedded characters, \\u2069 \\u2068\ntest_string = """"ABC. 6", "}"""\nnonprintable = list((ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if\n unicodedata.category(c) in ['Cc','Cf']))\n\ntranslate_dict = {character: None for character in nonprintable}\nprint("Before translate, using repr()", repr(test_string))\nprint("After translate, using repr()", repr(test_string.translate(translate_dict)))\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
]
| I use to run
```
$s =~ s/[^[:print:]]//g;
```
on Perl to get rid of non printable characters.
In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not.
What would you do?
EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character. | Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The *unicodedata* module is quite helpful for this, especially the *unicodedata.category()* function. See [Unicode Character Database](http://www.unicode.org/reports/tr44/#General_Category_Values) for descriptions of the categories.
```
import unicodedata, re, itertools, sys
all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
```
For Python2
```
import unicodedata, re, sys
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
```
For some use-cases, additional categories (e.g. all from the *control* group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:
* `Cc` (control): 65
* `Cf` (format): 161
* `Cs` (surrogate): 2048
* `Co` (private-use): 137468
* `Cn` (unassigned): 836601
***Edit** Adding suggestions from the comments.* |
92,452 | <p>I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines? </p>
<p>Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable.</p>
<p>Solutions I've toyed with conceptually are:</p>
<ol>
<li><p>Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer</p></li>
<li><p>Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record.</p></li>
<li><p>Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model.</p></li>
<li><p>Using EHCache for synchronous replication of my in-memory "locks."</p></li>
</ol>
<p>I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product?</p>
| [
{
"answer_id": 92521,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": -1,
"selected": false,
"text": "<p>Back in the day, we'd use a specific \"lock server\" on the network to handle this. Bleh.</p>\n\n<p>Your database server might have resources specifically for doing this kind of thing. MS-SQL Server has application locks usable through the <em>sp_getapplock</em>/<em>sp_releaseapplock</em> procedures.</p>\n"
},
{
"answer_id": 92559,
"author": "entzik",
"author_id": 12297,
"author_profile": "https://Stackoverflow.com/users/12297",
"pm_score": 0,
"selected": false,
"text": "<p>I made a simple RMI service with two methods: lock and release. both methods take a key (my data model used UUIDs as pk so that was also the locking key). </p>\n\n<p>RMI is a good solution for this because it's centralized. you can't do this with EJBs (specialially in a cluster as you don't know on which machine your call will land). plus, it's easy.</p>\n\n<p>it worked for me.</p>\n"
},
{
"answer_id": 92637,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 1,
"selected": false,
"text": "<p>I have done a lot of work with Coherence, which allowed several approaches to implementing a distributed lock. The naive approach was to request to lock the same logical object on all participating nodes. In Coherence terms this was locking a key on a Replicated Cache. This approach doesn't scale that well because the network traffic increases linearly as you add nodes. A smarter way was to use a Distributed Cache, where each node in the cluster is naturally responsible for a portion of the key space, so locking a key in such a cache always involved communication with at most one node. You could roll your own approach based on this idea, or better still, get Coherence. It really is the scalability toolkit of your dreams. </p>\n\n<p>I would add that any half decent multi-node network based locking mechanism would have to be reasonably sophisticated to act correctly in the event of any network failure.</p>\n"
},
{
"answer_id": 92694,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if I understand the entire context but it sounds like you have 1 single database backing this? Why not make use of the database's locking: if creating the customer is a single INSERT then this statement alone can serve as a lock since the database will reject a second INSERT that would violate one of your constraints (e.g. the fact that the customer name is unique for example).</p>\n\n<p>If the \"inserting of a customer\" operation is not atomic and is a batch of statements then I would introduce (or use) an initial INSERT that creates some simple basic record identifying your customer (with the necessary UNIQUEness constraints) and then do all the other inserts/updates in the same transaction. Again the database will take care of consistency and any concurrent modifications will result in one of them failing.</p>\n"
},
{
"answer_id": 97897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>you might want to consider using <a href=\"http://www.hazelcast.com\" rel=\"noreferrer\">Hazelcast</a> distributed locks. Super lite and easy.</p>\n\n<pre><code>java.util.concurrent.locks.Lock lock = Hazelcast.getLock (\"mymonitor\");\nlock.lock ();\ntry {\n// do your stuff\n}finally {\n lock.unlock();\n}\n</code></pre>\n\n<p>Hazelcast - Distributed Queue, Map, Set, List, Lock</p>\n"
},
{
"answer_id": 103384,
"author": "Taylor Gautier",
"author_id": 19013,
"author_profile": "https://Stackoverflow.com/users/19013",
"pm_score": 2,
"selected": false,
"text": "<p>Terracotta is closer to a \"tiered\" model - all client applications talk to a Terracotta Server Array (and more importantly for scale they don't talk to one another). The Terracotta Server Array is capable of being clustered for both scale and availability (mirrored, for availability, and striped, for scale).</p>\n\n<p>In any case as you probably know Terracotta gives you the ability to express concurrency across the cluster the same way you do in a single JVM by using POJO synchronized/wait/notify or by using any of the java.util.concurrent primitives such as ReentrantReadWriteLock, CyclicBarrier, AtomicLong, FutureTask and so on.</p>\n\n<p>There are a lot of simple recipes demonstrating the use of these primitives in the <a href=\"http://www.terracotta.org/web/display/orgsite/Tutorials\" rel=\"nofollow noreferrer\">Terracotta Cookbook</a>.</p>\n\n<p>As an example, I will post the ReentrantReadWriteLock example (note there is no \"Terracotta\" version of the lock - you just use normal Java ReentrantReadWriteLock)</p>\n\n<pre><code>import java.util.concurrent.locks.*;\n\npublic class Main\n{\n public static final Main instance = new Main();\n private int counter = 0;\n private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);\n\n public void read()\n {\n while (true) {\n rwl.readLock().lock();\n try {\n System.out.println(\"Counter is \" + counter);\n } finally {\n rwl.readLock().unlock();\n }\n try { Thread.currentThread().sleep(1000); } catch (InterruptedException ie) { }\n }\n }\n\n public void write()\n {\n while (true) {\n rwl.writeLock().lock();\n try {\n counter++;\n System.out.println(\"Incrementing counter. Counter is \" + counter);\n } finally {\n rwl.writeLock().unlock();\n }\n try { Thread.currentThread().sleep(3000); } catch (InterruptedException ie) { }\n }\n }\n\n public static void main(String[] args)\n {\n if (args.length > 0) {\n // args --> Writer\n instance.write();\n } else {\n // no args --> Reader\n instance.read();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 210995,
"author": "fern",
"author_id": 28805,
"author_profile": "https://Stackoverflow.com/users/28805",
"pm_score": 4,
"selected": false,
"text": "<p>We use Terracotta, so I would like to vote for that.</p>\n\n<p>I've been following Hazelcast and it looks like another promising technology, but can't vote for it since I've not used it, and knowing that it uses a P2P based system at its heard, I really would not trust it for large scaling needs.</p>\n\n<p>But I have also heard of Zookeeper, which came out of Yahoo, and is moving under the Hadoop umbrella. If you're adventurous trying out some new technology this really has lots of promise since it's very lean and mean, focusing on just coordination. I like the vision and promise, though it might be too green still.</p>\n\n<ul>\n<li><a href=\"http://www.terracotta.org\" rel=\"noreferrer\">http://www.terracotta.org</a></li>\n<li><a href=\"http://wiki.apache.org/hadoop/ZooKeeper\" rel=\"noreferrer\">http://wiki.apache.org/hadoop/ZooKeeper</a></li>\n<li><a href=\"http://www.hazelcast.com\" rel=\"noreferrer\">http://www.hazelcast.com</a></li>\n</ul>\n"
},
{
"answer_id": 211014,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 2,
"selected": false,
"text": "<p>I was going to advice on using memcached as a very fast, distributed RAM storage for keeping logs; but it seems that EHCache is a similar project but more java-centric.</p>\n\n<p>Either one is the way to go, as long as you're sure to use atomic updates (memcached supports them, don't know about EHCache). It's by far the most scalable solution.</p>\n\n<p>As a related datapoint, Google uses 'Chubby', a fast, RAM-based distributed lock storage as the root of several systems, among them BigTable.</p>\n"
},
{
"answer_id": 293629,
"author": "Jonathan",
"author_id": 14850,
"author_profile": "https://Stackoverflow.com/users/14850",
"pm_score": 0,
"selected": false,
"text": "<p>If you can set up your load balancing so that requests for a single customer always get mapped to the same server then you can handle this via local synchronization. For example, take your customer ID mod 10 to find which of the 10 nodes to use.</p>\n\n<p>Even if you don't want to do this in the general case your nodes could proxy to each other for this specific type of request.</p>\n\n<p>Assuming your users are uniform enough (i.e. if you have a ton of them) that you don't expect hot spots to pop up where one node gets overloaded, this should still scale pretty well.</p>\n"
},
{
"answer_id": 2220383,
"author": "Kamran",
"author_id": 268512,
"author_profile": "https://Stackoverflow.com/users/268512",
"pm_score": -1,
"selected": false,
"text": "<p>We have been developing an open source, distributed synchronization framework, currently DistributedReentrantLock and DistributedReentrantReadWrite lock has been implemented, but still are in testing and refactoring phase. In our architecture lock keys are devided in buckets and each node is resonsible for certain number of buckets. So effectively for a successfull lock requests, there is only one network request. We are also using AbstractQueuedSynchronizer class as local lock state, so all the failed lock requests are handled locally, this drastically reduces network trafic.\nWe are using JGroups (<a href=\"http://jgroups.org\" rel=\"nofollow noreferrer\">http://jgroups.org</a>) for group communication and Hessian for serialization.</p>\n\n<p>for details, please check out <a href=\"http://code.google.com/p/vitrit/\" rel=\"nofollow noreferrer\">http://code.google.com/p/vitrit/</a>.</p>\n\n<p>Please send me your valuable feedback.</p>\n\n<p>Kamran</p>\n"
},
{
"answer_id": 7208058,
"author": "Slava Imeshev",
"author_id": 213480,
"author_profile": "https://Stackoverflow.com/users/213480",
"pm_score": 0,
"selected": false,
"text": "<p>You might also consider <a href=\"http://www.cacheonix.com/products/cacheonix/index.htm\" rel=\"nofollow\">Cacheonix</a> for distributed locks. Unlike anything else mentioned here Cacheonix support ReadWrite locks with lock escalation from read to write when needed:</p>\n\n<pre><code>ReadWriteLock rwLock = Cacheonix.getInstance().getCluster().getReadWriteLock();\nLock lock = rwLock.getWriteLock();\ntry {\n ...\n} finally {\n lock.unlock();\n}\n</code></pre>\n\n<p>Full disclosure: I am a Cacheonix developer.</p>\n"
},
{
"answer_id": 21073494,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend to use <a href=\"https://redisson.org\" rel=\"nofollow noreferrer\">Redisson</a>. It implements over 30 distributed data structures and services including <code>java.util.Lock</code>. Usage example:</p>\n\n<pre><code>Config config = new Config();\nconfig.addAddress(\"some.server.com:8291\");\nRedisson redisson = Redisson.create(config);\n\nLock lock = redisson.getLock(\"anyLock\");\nlock.lock();\ntry {\n ...\n} finally {\n lock.unlock();\n}\n\nredisson.shutdown();\n</code></pre>\n"
},
{
"answer_id": 39090822,
"author": "user2179737",
"author_id": 2179737,
"author_profile": "https://Stackoverflow.com/users/2179737",
"pm_score": 0,
"selected": false,
"text": "<p>Since you are already connecting to a database, before adding another infra piece, take a look at <a href=\"https://github.com/zolyfarkas/spf4j/blob/master/spf4j-core/src/main/java/org/spf4j/concurrent/jdbc/JdbcSemaphore.java\" rel=\"nofollow\">JdbcSemaphore</a>, it is simple to use:</p>\n\n<pre><code>JdbcSemaphore semaphore = new JdbcSemaphore(ds, semName, maxReservations);\nboolean acq = semaphore.acquire(acquire, 1, TimeUnit.MINUTES);\nif (acq) {\n // do stuff\n semaphore.release();\n} else {\n throw new TimeoutException();\n}\n</code></pre>\n\n<p>It is part of <a href=\"http://www.spf4j.org\" rel=\"nofollow\">spf4j</a> library.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7567/"
]
| I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines?
Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable.
Solutions I've toyed with conceptually are:
1. Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer
2. Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record.
3. Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model.
4. Using EHCache for synchronous replication of my in-memory "locks."
I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product? | you might want to consider using [Hazelcast](http://www.hazelcast.com) distributed locks. Super lite and easy.
```
java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor");
lock.lock ();
try {
// do your stuff
}finally {
lock.unlock();
}
```
Hazelcast - Distributed Queue, Map, Set, List, Lock |
92,456 | <p>I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc...
C++ code looks like:</p>
<pre><code>des_string_to_key(reinterpret_cast<const char *>(key1), &initkey);
des_string_to_key(reinterpret_cast<const char *>(key2), &key);
key_sched(&key, ks);
// ...
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
return base64(reinterpret_cast<const unsigned char *>(encrypted_buffer), strlen(encrypted_buffer));
</code></pre>
<p>Java code looks like:</p>
<pre><code>Cipher ecipher;
try {
ecipher = Cipher.getInstance("DES");
SecretKeySpec keySpec = new SecretKeySpec(key, "DES");
ecipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] utf8 = password.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch {
// ...
}
</code></pre>
<p>So I can do DES encryption in Java pretty easily, but how can I get the same result as with the above code with methods that are completely different? What bothers me in particular is the fact that the C++ version uses 2 keys while the Java version uses only 1 key.
The answer about DES in CBC mode is quite satisfying but I can't get it to work yet.
Here are more details about the original code:
unsigned char key1[10]= {0};
unsigned char key2[50]= {0};</p>
<pre><code>int i;
for (i=0;i<8;i++)
key1[i] = 31+int((i*sqrt((double)i*5)))%100;
key1[9]=0;
for (i=0;i<48;i++)
key2[i] = 31+int((i*i*sqrt((double)i*2)))%100;
key2[49]=0;
...
// Initialize encrypted buffer
memset(encrypted_buffer, 0, sizeof(encrypted_buffer));
// Add begin Text and End Text to the encrypted message
std::string input;
const char beginText = 2;
const char endText = 3;
input.append(1,beginText);
input.append(bufferToEncrypt);
input.append(1,endText);
// Add padding
tmp.assign(desPad(input));
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
...
</code></pre>
<p>From what I've read, the key should be 56 (or 64, it's not clear to me) bits long, but here it's 48 bytes long.</p>
| [
{
"answer_id": 92547,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 0,
"selected": false,
"text": "<p>The algorithms should match; if you're getting different results it may have to do with the way you're handling the keys and the text. Also keep in mind that Java characters are 2 bytes long, which C++ chars are 1 byte, so that may have something to do with it.</p>\n"
},
{
"answer_id": 92926,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV.</p>\n"
},
{
"answer_id": 93140,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 1,
"selected": false,
"text": "<p>Also, keep in mind that you really shouldn't use sun.misc.* classes in your code. This could break in other VMs as these are not public APIs. Apache Commons Codecs (among others) have implementations of Base64 that don't bear this problem.</p>\n\n<p>I'm not really sure why single DES would ever use multiple keys. Even if you were using Triple-DES, I believe you would use a single key (with more bytes of data) rather than using separate keys with the Java Cryptography API.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17647/"
]
| I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc...
C++ code looks like:
```
des_string_to_key(reinterpret_cast<const char *>(key1), &initkey);
des_string_to_key(reinterpret_cast<const char *>(key2), &key);
key_sched(&key, ks);
// ...
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
return base64(reinterpret_cast<const unsigned char *>(encrypted_buffer), strlen(encrypted_buffer));
```
Java code looks like:
```
Cipher ecipher;
try {
ecipher = Cipher.getInstance("DES");
SecretKeySpec keySpec = new SecretKeySpec(key, "DES");
ecipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] utf8 = password.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch {
// ...
}
```
So I can do DES encryption in Java pretty easily, but how can I get the same result as with the above code with methods that are completely different? What bothers me in particular is the fact that the C++ version uses 2 keys while the Java version uses only 1 key.
The answer about DES in CBC mode is quite satisfying but I can't get it to work yet.
Here are more details about the original code:
unsigned char key1[10]= {0};
unsigned char key2[50]= {0};
```
int i;
for (i=0;i<8;i++)
key1[i] = 31+int((i*sqrt((double)i*5)))%100;
key1[9]=0;
for (i=0;i<48;i++)
key2[i] = 31+int((i*i*sqrt((double)i*2)))%100;
key2[49]=0;
...
// Initialize encrypted buffer
memset(encrypted_buffer, 0, sizeof(encrypted_buffer));
// Add begin Text and End Text to the encrypted message
std::string input;
const char beginText = 2;
const char endText = 3;
input.append(1,beginText);
input.append(bufferToEncrypt);
input.append(1,endText);
// Add padding
tmp.assign(desPad(input));
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
...
```
From what I've read, the key should be 56 (or 64, it's not clear to me) bits long, but here it's 48 bytes long. | I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV. |
92,504 | <p>I'm trying to create a self signed certificate for use with Apache Tomcat 6. Every certificate I can make always results in the browser connecting with AES-128. The customer would like me to demonstrate that I can create a connection at AES-256.</p>
<p>I've tried java's keytool and openssl. I've tried with a variety of parameters, but can't seem to specify anything about the keysize, just the signature size.</p>
<p>How can I get the browser-tomcat connection to use AES-256 with a self signed certificate?</p>
| [
{
"answer_id": 93095,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 1,
"selected": false,
"text": "<p>danivo, so long as the server's cert is capable of AES encryption, the level of encryption between the browser and the server is independent of the cert itself -- that level of encryption is negotiated between the browser and server. In other words, my understanding is that the cert doesn't specify the level of encryption, just the <em>type</em> of encryption (e.g., AES). See <a href=\"http://www.trustico.com/material/techpaper_encryption.pdf\" rel=\"nofollow noreferrer\">this link</a> (PDF) for verification of this, and how the cert resellers upsell \"256-bit-capable\" certs despite the cert not being what determines 256-bit capability.</p>\n\n<p>So you're just fine with the cert you have that supports AES-128 -- and they key is to figure out how to get Tomcat to support AES-256 (since most, if not all, major browsers certainly support it).</p>\n"
},
{
"answer_id": 93252,
"author": "alif",
"author_id": 12650,
"author_profile": "https://Stackoverflow.com/users/12650",
"pm_score": 1,
"selected": false,
"text": "<p>The strength of the SSL connection is negotiated between the browser and the server (or whatever is providing SSL). It might be their browser asking for a weaker cypher. Have they ever seen a 256-AES SSL connection on this browser? AES-128 is still a very secure algorithm, so unless they have something that they want to protect from off line (think: supercomputer brute force generating 2^128 keys <a href=\"http://en.wikipedia.org/wiki/Brute_force_attack\" rel=\"nofollow noreferrer\">wikipedia</a>) attack, 128-bit should be fine. If they really need that much protection, they probably should be using a more stable solution for data access than a website, a secure ssh tunnel to their server is bulletproof (you can tell them they can have their 256-bit AES and 4096-bit RSA too), or a vpn depending upon implementation.</p>\n"
},
{
"answer_id": 93696,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 5,
"selected": true,
"text": "<p>Okie doke, I think I just figured this out.</p>\n\n<p>As I said above, the key bit of knowledge is that the cert doesn't matter, so long as it's generated with an algorithm that supports AES 256-bit encryption (e.g., RSA). Just to make sure that we're on the same page, for my testing, I generated my self-signed cert using the following:</p>\n\n<pre><code>keytool -genkey -alias tomcat -keyalg RSA\n</code></pre>\n\n<p>Now, you have to make sure that your Java implementation on your server supports AES-256, and this is the tricky bit. I did my testing on an OS X (OS 10.5) box, and when I checked to see the list of ciphers that it supported by default, AES-256 was NOT on the list, which is why using that cert I generated above only was creating an AES-128 connection between my browser and Tomcat. (Well, technically, TLS_RSA_WITH_AES_256_CBC_SHA was not on the list -- that's the cipher that you want, according to <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#AppA\" rel=\"noreferrer\">this JDK 5 list</a>.)</p>\n\n<p>For completeness, here's the short Java app I created to check my box's supported ciphers:</p>\n\n<pre><code>import java.util.Arrays;\nimport javax.net.ssl.SSLSocketFactory;\n\npublic class CipherSuites {\n public static void main(String[] args) {\n SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();\n String[] ciphers = sslsf.getDefaultCipherSuites();\n Arrays.sort(ciphers);\n for (String cipher : ciphers) {\n System.out.println(cipher);\n }\n }\n}\n</code></pre>\n\n<p>It turns out that JDK 5, which is what this OS X box has installed by default, needs the \"Unlimited Strength Jurisdiction Policy Files\" installed in order to tell Java that it's OK to use the higher-bit encryption levels; you can <a href=\"http://java.sun.com/javase/downloads/index_jdk5.jsp\" rel=\"noreferrer\">find those files here</a> (scroll down and look at the top of the \"Other Downloads\" section). I'm not sure offhand if JDK 6 needs the same thing done, but the same policy files for JDK 6 <a href=\"http://java.sun.com/javase/downloads/index.jsp\" rel=\"noreferrer\">are available here</a>, so I assume it does. Unzip that file, read the README to see how to install the files where they belong, and then check your supported ciphers again... I bet AES-256 is now on the list.</p>\n\n<p>If it is, you should be golden; just restart Tomcat, connect to your SSL instance, and I bet you'll now see an AES-256 connection.</p>\n"
},
{
"answer_id": 10076386,
"author": "kkron",
"author_id": 889140,
"author_profile": "https://Stackoverflow.com/users/889140",
"pm_score": 1,
"selected": false,
"text": "<p>I think what you are looking for is \n<a href=\"http://www.sslshopper.com/article-how-to-disable-weak-ciphers-and-ssl-2-in-tomcat.html\" rel=\"nofollow\">http://www.sslshopper.com/article-how-to-disable-weak-ciphers-and-ssl-2-in-tomcat.html</a> \nand \n<a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#AppA\" rel=\"nofollow\">http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#AppA</a></p>\n\n<p>Depending on whether you want good security and compatibility or PCI certification.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17583/"
]
| I'm trying to create a self signed certificate for use with Apache Tomcat 6. Every certificate I can make always results in the browser connecting with AES-128. The customer would like me to demonstrate that I can create a connection at AES-256.
I've tried java's keytool and openssl. I've tried with a variety of parameters, but can't seem to specify anything about the keysize, just the signature size.
How can I get the browser-tomcat connection to use AES-256 with a self signed certificate? | Okie doke, I think I just figured this out.
As I said above, the key bit of knowledge is that the cert doesn't matter, so long as it's generated with an algorithm that supports AES 256-bit encryption (e.g., RSA). Just to make sure that we're on the same page, for my testing, I generated my self-signed cert using the following:
```
keytool -genkey -alias tomcat -keyalg RSA
```
Now, you have to make sure that your Java implementation on your server supports AES-256, and this is the tricky bit. I did my testing on an OS X (OS 10.5) box, and when I checked to see the list of ciphers that it supported by default, AES-256 was NOT on the list, which is why using that cert I generated above only was creating an AES-128 connection between my browser and Tomcat. (Well, technically, TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA was not on the list -- that's the cipher that you want, according to [this JDK 5 list](http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#AppA).)
For completeness, here's the short Java app I created to check my box's supported ciphers:
```
import java.util.Arrays;
import javax.net.ssl.SSLSocketFactory;
public class CipherSuites {
public static void main(String[] args) {
SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
String[] ciphers = sslsf.getDefaultCipherSuites();
Arrays.sort(ciphers);
for (String cipher : ciphers) {
System.out.println(cipher);
}
}
}
```
It turns out that JDK 5, which is what this OS X box has installed by default, needs the "Unlimited Strength Jurisdiction Policy Files" installed in order to tell Java that it's OK to use the higher-bit encryption levels; you can [find those files here](http://java.sun.com/javase/downloads/index_jdk5.jsp) (scroll down and look at the top of the "Other Downloads" section). I'm not sure offhand if JDK 6 needs the same thing done, but the same policy files for JDK 6 [are available here](http://java.sun.com/javase/downloads/index.jsp), so I assume it does. Unzip that file, read the README to see how to install the files where they belong, and then check your supported ciphers again... I bet AES-256 is now on the list.
If it is, you should be golden; just restart Tomcat, connect to your SSL instance, and I bet you'll now see an AES-256 connection. |
92,514 | <p>Is there any way to create a ODBC DSN with C#?</p>
<p>Maybe a P/invoke?</p>
| [
{
"answer_id": 92538,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>Following resources might be helpful:</p>\n\n<p>MSDN:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/310988\" rel=\"nofollow noreferrer\">How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings</a></p>\n\n<p>CodeProject.com</p>\n\n<p><a href=\"http://www.codeproject.com/KB/database/sdbODBCMngr.aspx\" rel=\"nofollow noreferrer\">An ODBC (DSN/Driver) Manager DLL written in C#</a></p>\n\n<p>You can try to invoke functions: </p>\n\n<p>SQLWriteDSNToIni and ConfigDSN (MSDN links are dead for some reason, try to google by functions names)</p>\n"
},
{
"answer_id": 92645,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 2,
"selected": false,
"text": "<p>You can use Registry classes to write the dsn info in the registry, under</p>\n\n<pre><code>HKLM\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\n</code></pre>\n\n<p>You'll need to check what values are needed for you ODBC driver.</p>\n"
},
{
"answer_id": 170603,
"author": "Matthew Murdoch",
"author_id": 4023,
"author_profile": "https://Stackoverflow.com/users/4023",
"pm_score": 1,
"selected": false,
"text": "<p>An example of the Registry Keys and Values required to create an ODBC Data Source for SQL Server can be found <a href=\"https://stackoverflow.com/questions/170466/what-is-the-simplest-most-maintainable-way-to-create-a-sql-server-odbc-data-sou#170490\">here</a>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098074/"
]
| Is there any way to create a ODBC DSN with C#?
Maybe a P/invoke? | You can use Registry classes to write the dsn info in the registry, under
```
HKLM\Software\ODBC\ODBC.INI\ODBC Data Sources
```
You'll need to check what values are needed for you ODBC driver. |
92,522 | <p>What is the best way to issue a http get in VB.net? I want to get the result of a request like <a href="http://api.hostip.info/?ip=68.180.206.184" rel="noreferrer">http://api.hostip.info/?ip=68.180.206.184</a> </p>
| [
{
"answer_id": 92529,
"author": "Dario Solera",
"author_id": 16026,
"author_profile": "https://Stackoverflow.com/users/16026",
"pm_score": 1,
"selected": false,
"text": "<p>You should try the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"nofollow noreferrer\">HttpWebRequest</a> class.</p>\n"
},
{
"answer_id": 92544,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 7,
"selected": true,
"text": "<p>In VB.NET:</p>\n\n<pre><code>Dim webClient As New System.Net.WebClient\nDim result As String = webClient.DownloadString(\"http://api.hostip.info/?ip=68.180.206.184\")\n</code></pre>\n\n<p>In C#:</p>\n\n<pre><code>System.Net.WebClient webClient = new System.Net.WebClient();\nstring result = webClient.DownloadString(\"http://api.hostip.info/?ip=68.180.206.184\");\n</code></pre>\n"
},
{
"answer_id": 92549,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.webrequest\" rel=\"nofollow noreferrer\">WebRequest</a> class</p>\n\n<p>This is to get an image:</p>\n\n<pre><code>Try\n Dim _WebRequest As System.Net.WebRequest = Nothing\n _WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)\nCatch ex As Exception\n Windows.Forms.MessageBox.Show(ex.Message)\n Exit Sub\nEnd Try\n\nTry\n _NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())\nCatch ex As Exception\n Windows.Forms.MessageBox.Show(ex.Message)\n Exit Sub\nEnd Try\n</code></pre>\n"
},
{
"answer_id": 92553,
"author": "Oliver Mellet",
"author_id": 12001,
"author_profile": "https://Stackoverflow.com/users/12001",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is <code>System.Net.WebClient.DownloadFile</code> or <code>DownloadString</code>.</p>\n"
},
{
"answer_id": 92576,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>WebRequest request = WebRequest.CreateDefault(RequestUrl);\nrequest.Method = \"GET\";\n\nWebResponse response;\ntry { response = request.GetResponse(); }\ncatch (WebException exc) { response = exc.Response; }\n\nif (response == null)\n throw new HttpException((int)HttpStatusCode.NotFound, \"The requested url could not be found.\");\n\nusing(StreamReader reader = new StreamReader(response.GetResponseStream())) {\n string requestedText = reader.ReadToEnd();\n\n // do what you want with requestedText\n}\n</code></pre>\n\n<p>Sorry about the C#, I know you asked for VB, but I didn't have time to convert.</p>\n"
},
{
"answer_id": 92588,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 5,
"selected": false,
"text": "<p>You can use the HttpWebRequest class to perform a request and retrieve a response from a given URL. You'll use it like:</p>\n\n<pre><code>Try\n Dim fr As System.Net.HttpWebRequest\n Dim targetURI As New Uri(\"http://whatever.you.want.to.get/file.html\") \n\n fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)\n If (fr.GetResponse().ContentLength > 0) Then\n Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())\n Response.Write(str.ReadToEnd())\n str.Close(); \n End If \nCatch ex As System.Net.WebException\n 'Error in accessing the resource, handle it\nEnd Try\n</code></pre>\n\n<p>HttpWebRequest is detailed at: <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx</a></p>\n\n<p>A second option is to use the WebClient class, this provides an easier to use interface for downloading web resources but is not as flexible as HttpWebRequest:</p>\n\n<pre><code>Sub Main()\n 'Address of URL\n Dim URL As String = http://whatever.com\n ' Get HTML data\n Dim client As WebClient = New WebClient()\n Dim data As Stream = client.OpenRead(URL)\n Dim reader As StreamReader = New StreamReader(data)\n Dim str As String = \"\"\n str = reader.ReadLine()\n Do While str.Length > 0\n Console.WriteLine(str)\n str = reader.ReadLine()\n Loop\nEnd Sub\n</code></pre>\n\n<p>More info on the webclient can be found at: <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx</a></p>\n"
},
{
"answer_id": 43911430,
"author": "sanket parikh",
"author_id": 5414397,
"author_profile": "https://Stackoverflow.com/users/5414397",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String\n Dim requestUrl As String = \"your api\"\n Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)\n Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)\n Dim dataStream As Stream = response.GetResponseStream()\n Dim reader As New StreamReader(dataStream)\n Dim responseFromServer As String = reader.ReadToEnd()\n Dim result = responseFromServer\n reader.Close()\n response.Close()\n Return result\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4221/"
]
| What is the best way to issue a http get in VB.net? I want to get the result of a request like <http://api.hostip.info/?ip=68.180.206.184> | In VB.NET:
```
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")
```
In C#:
```
System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
``` |
92,533 | <p>Based on <a href="https://stackoverflow.com/questions/6209/split-a-string-ignoring-quoted-sections#6243">"Split a string by spaces in Python"</a>, which uses <em>shlex.split</em> to split a string with quotes smartly, I would be interested in hearing about other common tasks solved by non-obvious standard library functions. </p>
<p>If this turns into <a href="http://www.doughellmann.com/projects/PyMOTW/" rel="nofollow noreferrer">Module of The Week</a>, that's fine too. </p>
| [
{
"answer_id": 92548,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "<p>I found struct.unpack to be a godsend for unpacking binary data formats after I learned of it!</p>\n"
},
{
"answer_id": 93498,
"author": "Marcin",
"author_id": 16917,
"author_profile": "https://Stackoverflow.com/users/16917",
"pm_score": 1,
"selected": false,
"text": "<p>I've found <a href=\"http://docs.python.org/lib/module-sched.html\" rel=\"nofollow noreferrer\">sched module</a> to be helpful in cron-like activities. It simplifies things a lot. Unfortunately I found it too late. </p>\n"
},
{
"answer_id": 93865,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>Oft overlooked modules, uses and tricks:</p>\n\n<p>collections.defaultdict(): for when you want missing keys in a dict to have a default value.</p>\n\n<p>functools.wraps(): for writing decorators that play nicely with introspection.</p>\n\n<p>posixpath: the os.path module for POSIX systems. You can use it for manipulating POSIX paths (including URI elements) even on Windows and other non-POSIX systems.</p>\n\n<p>ntpath: the os.path module for Windows; usable for manipulation of Windows paths on non-Windows systems.</p>\n\n<p>(also: macpath, for MacOS 9 and earlier, os2emxpath for OS/2 EMX, but I'm not sure if anyone still cares.)</p>\n\n<p>pprint: more structured printing of the repr() of containers makes debugging much easier.</p>\n\n<p>imp: all the tools you need to write your own plugin system or make Python import modules from arbitrary archives.</p>\n\n<p>rlcompleter: getting tab-completion in the normal interactive interpreter. Just do \"import readline, rlcompleter; readline.parse_and_bind('tab: complete')\"</p>\n\n<p>the PYTHONSTARTUP environment variable: can be set to the path to a file that will be executed (in the main namespace) when entering the interactive interpreter; useful for putting things in like the rlcompleter recipe above.</p>\n"
},
{
"answer_id": 94551,
"author": "J Miller",
"author_id": 16976,
"author_profile": "https://Stackoverflow.com/users/16976",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://docs.python.org/lib/module-getpass.html\" rel=\"nofollow noreferrer\">getpass</a> is useful for determining the login name of the current user.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-grp.html\" rel=\"nofollow noreferrer\">grp</a> allows you to lookup Unix group IDs by name, and vice versa.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-dircache.html\" rel=\"nofollow noreferrer\">dircache</a> might be useful in situations where you're repeatedly polling the contents of a directory.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-glob.html\" rel=\"nofollow noreferrer\">glob</a> can find filenames matching wildcards like a Unix shell does.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-shutil.html\" rel=\"nofollow noreferrer\">shutil</a> is useful when you need to copy, delete or rename a file.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-csv.html\" rel=\"nofollow noreferrer\">csv</a> can simplify parsing of delimited text files.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-optparse.html\" rel=\"nofollow noreferrer\">optparse</a> provides a reliable way to parse command line options.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-bz2.html\" rel=\"nofollow noreferrer\">bz2</a> comes in handy when you need to manipulate a bzip2-compressed file.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-urlparse.html\" rel=\"nofollow noreferrer\">urlparse</a> will save you the hassle of breaking up a URL into component parts.</p>\n"
},
{
"answer_id": 94991,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the other examples are merely overlooked, not unexpected uses for module.</p>\n\n<p>fnmatch, like shlex, can be applied in unexpected ways. fnmatch is a kind of poor-person's RE, and can be used for more than matching files, it can compare strings with the simplified wild-card patterns.</p>\n"
},
{
"answer_id": 95159,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 2,
"selected": false,
"text": "<p>I use itertools (especially cycle, repeat, chain) to make python behave more like R and in other functional / vector applications. Often this lets me avoid the overhead and complication of Numpy. </p>\n\n<pre><code># in R, shorter iterables are automatically cycled\n# and all functions \"apply\" in a \"map\"-like way over lists\n> 0:10 + 0:2\n [1] 0 2 4 3 5 7 6 8 10 9 11\n</code></pre>\n\n<p>Python\n #Normal python\n In [1]: range(10) + range(3)\n Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]</p>\n\n<pre><code>## this code is terrible, but it demos the idea.\nfrom itertools import cycle\ndef addR(L1,L2):\n n = max( len(L1), len(L2))\n out = [None,]*n\n gen1,gen2 = cycle(L1), cycle(L2)\n ii = 0\n while ii < n:\n out[ii] = gen1.next() + gen2.next()\n ii += 1\n return out\n\nIn [21]: addR(range(10), range(3))\nOut[21]: [0, 2, 4, 3, 5, 7, 6, 8, 10, 9]\n</code></pre>\n"
},
{
"answer_id": 95825,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 3,
"selected": false,
"text": "<p>I was quite surprised to learn that you could use the bisect module to do a very fast binary search in a sequence. It's documentation doesn't say anything about it:</p>\n\n<blockquote>\n <p>This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.</p>\n</blockquote>\n\n<p>The usage is very simple:</p>\n\n<pre><code>>>> import bisect\n>>> lst = [4, 7, 10, 23, 25, 100, 103, 201, 333]\n>>> bisect.bisect_left(lst, 23)\n3\n</code></pre>\n\n<p>You have to remember though, that it's quicker to linearly look for something in a list goes item by item, than sorting the list and then doing a binary search on it. The first option is O(n), the second is O(nlogn).</p>\n"
},
{
"answer_id": 97103,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 1,
"selected": false,
"text": "<p>One function I've come to appreciate is string.translate. Its very fast at what it does, and useful anywhere you want to alter or remove characters in a string. I've just used it in a seemingly inapplicable <a href=\"https://stackoverflow.com/questions/89909/in-python-how-to-i-verify-that-a-string-only-contains-letters-numbers-underscor#92000\">problem</a> and found it beat all the other solutions handily.</p>\n\n<p>The downside is that its API is a bit clunky, but this is improving in Py2.6 / Py3.0.</p>\n"
},
{
"answer_id": 99969,
"author": "Ingrid",
"author_id": 18432,
"author_profile": "https://Stackoverflow.com/users/18432",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://docs.python.org/lib/module-pickle.html\" rel=\"nofollow noreferrer\">pickle</a> module is pretty awesome</p>\n"
},
{
"answer_id": 101353,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "<p>complex numbers. (The complexobject.c defines a class, so technically it's not a module). Great for 2d coordinates, with easy translation/rotations etc</p>\n\n<p>eg.</p>\n\n<pre><code>TURN_LEFT_90= 1j\nTURN_RIGHT_90= -1j\n\ncoord= 5+4j # x=5 y=4\nprint coord*TURN_LEFT_90\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
]
| Based on ["Split a string by spaces in Python"](https://stackoverflow.com/questions/6209/split-a-string-ignoring-quoted-sections#6243), which uses *shlex.split* to split a string with quotes smartly, I would be interested in hearing about other common tasks solved by non-obvious standard library functions.
If this turns into [Module of The Week](http://www.doughellmann.com/projects/PyMOTW/), that's fine too. | I was quite surprised to learn that you could use the bisect module to do a very fast binary search in a sequence. It's documentation doesn't say anything about it:
>
> This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.
>
>
>
The usage is very simple:
```
>>> import bisect
>>> lst = [4, 7, 10, 23, 25, 100, 103, 201, 333]
>>> bisect.bisect_left(lst, 23)
3
```
You have to remember though, that it's quicker to linearly look for something in a list goes item by item, than sorting the list and then doing a binary search on it. The first option is O(n), the second is O(nlogn). |
92,540 | <p>In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?</p>
<p>Related, is it possible to add new User scoped application settings AT RUNTIME? I totally see how to add settings at design time, that's not a problem. But what if I want to create one at runtime?</p>
<p>More details:</p>
<p>My application is a conversion of an existing Visual FoxPro application. I've been trying to read as much as I can about application settings, user settings, etc. and get myself clear on the .Net way of doing things, but there are still several things I am confused on.</p>
<p>In the Fox app, saved settings are stored in the registry. My forms are subclassed, and I have base class code that automatically saves the form position and size in the registry keyed on the form name. Whenever I create a new form, I don't have to do anything special to get this behavior; it's built in to the base class. My .Net forms are also subclassed, that part is working well.</p>
<p>In .Net, I get the impression I'm supposed to use User scoped settings for things like user preferences. Size and location of a form definitely seem like a user preference. But, I can't see any way to automatically add these settings to the project. In other words, every time I add a new form to my project (and their are 100's of forms), I have to remember to ADD a User scoped application setting and be sure to give it the same name as the form, i.e., "FormMySpecialSizePosition" to hold the size and position. I'd rather not have to remember to do that. Is this just tough luck? Or am I totally barking up the wrong tree by trying to use User scoped settings? Do I need to create my own XML file to hold settings, so that I can do whatever I want (i.e, add a new setting at runtime)? Or something else?</p>
<p>Surely this is very common and somebody can tell the "right" way to do it.</p>
| [
{
"answer_id": 93211,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a base form class with common functionality such as remembering the position and size and inherit from that base class.</p>\n\n<pre><code>public class myForm : Form {\nprotected override void OnLoad(){\n //load the settings and apply them\n base.OnLoad();\n}\n\nprotected override void OnClose(){\n //save the settings\n base.OnClose();\n}\n}\nthen for the other forms:\n\npublic class frmMainScreen : myForm {\n// you get the settings for free ;)\n}</code></pre>\n\n<p>Well, something like that ;)</p>\n"
},
{
"answer_id": 102485,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm in the same boat as you, in that I have a number of forms (MDI children, in my case) that I want to preserve the position and size of for each user. From my research, creating application settings at runtime is not supported. (see <a href=\"http://bytes.com/forum/thread479401.html\" rel=\"nofollow noreferrer\">this blog entry</a>)\nHowever, you don't have to stick everything in the main settings file. You can add a Settings file to your project (<a href=\"http://msdn.microsoft.com/en-us/library/bb397748.aspx\" rel=\"nofollow noreferrer\">explained here in the MSDN</a>) and use it via the Properties.Settings object. This won't ease the pain of having to remember to create new settigns for each form, but at least it will keep them together, and not clutter up your main application settings.</p>\n\n<p>As far as using the base class to retrieve the settings... I don't know if you can do it there. What I would (and probably will) do is name each attribute , then use Me.GetType().ToString() (I'm working in VB) to composite the names of the attributes I want to retrieve in the Load() event of each form.</p>\n"
},
{
"answer_id": 236274,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>private void Form1_Load( object sender, EventArgs e )\n{\n // restore location and size of the form on the desktop\n this.DesktopBounds =\n new Rectangle(Properties.Settings.Default.Location,\n Properties.Settings.Default.Size);\n // restore form's window state\n this.WindowState = ( FormWindowState )Enum.Parse(\n typeof(FormWindowState),\n Properties.Settings.Default.WindowState);\n}\n\nprivate void Form1_FormClosing( object sender, FormClosingEventArgs e )\n{\n System.Drawing.Rectangle bounds = this.WindowState != FormWindowState.Normal ? this.RestoreBounds : this.DesktopBounds;\n Properties.Settings.Default.Location = bounds.Location;\n Properties.Settings.Default.Size = bounds.Size;\n Properties.Settings.Default.WindowState =\n Enum.GetName(typeof(FormWindowState), this.WindowState);\n // persist location ,size and window state of the form on the desktop\n Properties.Settings.Default.Save();\n}\n</code></pre>\n"
},
{
"answer_id": 1808291,
"author": "fusi",
"author_id": 159132,
"author_profile": "https://Stackoverflow.com/users/159132",
"pm_score": 0,
"selected": false,
"text": "<p>I just stream it out to a separate <code>XML</code> file - quick and dirty and probably not what youre after:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim winRect As String() = util.ConfigFile.GetUserConfigInstance().GetValue(\"appWindow.rect\").Split(\",\")\nDim winState As String = util.ConfigFile.GetUserConfigInstance().GetValue(\"appWindow.state\")\n\nMe.WindowState = FormWindowState.Normal\n\nMe.Left = CType(winRect(0), Integer)\nMe.Top = CType(winRect(1), Integer)\nMe.Width = CType(winRect(2), Integer)\nMe.Height = CType(winRect(3), Integer)\n\nIf winState = \"maximised\" Then\n Me.WindowState = FormWindowState.Maximized\nEnd If\n</code></pre>\n\n<p>and</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim winState As String = \"normal\"\nIf Me.WindowState = FormWindowState.Maximized Then\n winState = \"maximised\"\nElseIf Me.WindowState = FormWindowState.Minimized Then\n winState = \"minimised\"\nEnd If\n\nIf Me.WindowState = FormWindowState.Normal Then\n\n Dim winRect As String = CType(Me.Left, String) & \",\" & CType(Me.Top, String) & \",\" & CType(Me.Width, String) & \",\" & CType(Me.Height, String)\n ' only save window rectangle if its not maximised/minimised\n util.ConfigFile.GetUserConfigInstance().SetValue(\"appWindow.rect\", winRect)\nEnd If\n\nutil.ConfigFile.GetUserConfigInstance().SetValue(\"appWindow.state\", winState)\n</code></pre>\n"
},
{
"answer_id": 4474945,
"author": "Pat",
"author_id": 116891,
"author_profile": "https://Stackoverflow.com/users/116891",
"pm_score": 0,
"selected": false,
"text": "<p>Here are some relevant links to check out:</p>\n\n<p><a href=\"http://blogs.msdn.com/b/rprabhu/archive/2005/11/28/497792.aspx\" rel=\"nofollow\">Saving out a Form's Size and Location using the Application Settings feature</a></p>\n\n<p><a href=\"http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/5e509b2a-76da-4d91-89b5-9fa8cb50fc8f/\" rel=\"nofollow\">Any good examples of how to use Applications settings</a></p>\n\n<p><a href=\"http://www.devx.com/dotnet/Article/33944/1954\" rel=\"nofollow\">Exploring Secrets of Persistent Application Settings</a></p>\n"
},
{
"answer_id": 9351887,
"author": "slolife",
"author_id": 698,
"author_profile": "https://Stackoverflow.com/users/698",
"pm_score": 2,
"selected": false,
"text": "<p>I got this code from somewhere, but unfortunately at the time (long ago) didn't make a comment about where I got it from.</p>\n\n<p>This saves the form info to the user's HKCU registry:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing Microsoft.Win32;\n\n/// <summary>Summary description for FormPlacement.</summary>\npublic class PersistentForm : System.Windows.Forms.Form\n{\n private const string DIALOGKEY = \"Dialogs\";\n\n /// <summary></summary>\n protected override void OnCreateControl()\n {\n LoadSettings();\n base.OnCreateControl ();\n }\n\n /// <summary></summary>\n protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n {\n SaveSettings();\n base.OnClosing(e);\n }\n\n /// <summary>Saves the form's settings.</summary>\n public void SaveSettings()\n {\n RegistryKey dialogKey = Application.UserAppDataRegistry.CreateSubKey(DIALOGKEY);\n if (dialogKey != null)\n {\n RegistryKey formKey = dialogKey.CreateSubKey(this.GetType().ToString());\n if (formKey != null)\n {\n formKey.SetValue(\"Left\", this.Left);\n formKey.SetValue(\"Top\", this.Top);\n formKey.Close();\n }\n dialogKey.Close();\n }\n }\n\n /// <summary></summary>\n public void LoadSettings()\n {\n RegistryKey dialogKey = Application.UserAppDataRegistry.OpenSubKey(DIALOGKEY);\n if (dialogKey != null)\n {\n RegistryKey formKey = dialogKey.OpenSubKey(this.GetType().ToString());\n if (formKey != null)\n {\n this.Left = (int)formKey.GetValue(\"Left\");\n this.Top = (int)formKey.GetValue(\"Top\");\n formKey.Close();\n }\n dialogKey.Close();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9436526,
"author": "Niall Douglas",
"author_id": 805579,
"author_profile": "https://Stackoverflow.com/users/805579",
"pm_score": 2,
"selected": false,
"text": "<p>There is actually a real lack of a single, \"just works\" solution to this anywhere on the internet, so here's my own creation:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing Microsoft.Win32;\nusing System.ComponentModel;\nusing System.Security.Cryptography;\n\nnamespace nedprod\n{\n abstract public class WindowSettings\n {\n private Form form;\n\n public FormWindowState state;\n public Point location;\n public Size size;\n\n public WindowSettings(Form _form)\n {\n this.form = _form;\n }\n internal class MD5Sum\n {\n static MD5CryptoServiceProvider engine = new MD5CryptoServiceProvider();\n private byte[] sum = engine.ComputeHash(BitConverter.GetBytes(0));\n public MD5Sum() { }\n public MD5Sum(string s)\n {\n for (var i = 0; i < sum.Length; i++)\n sum[i] = byte.Parse(s.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);\n }\n public void Add(byte[] data)\n {\n byte[] temp = new byte[sum.Length + data.Length];\n var i=0;\n for (; i < sum.Length; i++)\n temp[i] = sum[i];\n for (; i < temp.Length; i++)\n temp[i] = data[i - sum.Length];\n sum=engine.ComputeHash(temp);\n }\n public void Add(int data)\n {\n Add(BitConverter.GetBytes(data));\n }\n public void Add(string data)\n {\n Add(Encoding.UTF8.GetBytes(data));\n }\n public static bool operator ==(MD5Sum a, MD5Sum b)\n {\n if (a.sum == b.sum) return true;\n if (a.sum.Length != b.sum.Length) return false;\n for (var i = 0; i < a.sum.Length; i++)\n if (a.sum[i] != b.sum[i]) return false;\n return true;\n }\n public static bool operator !=(MD5Sum a, MD5Sum b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n try\n {\n return (bool)(this == (MD5Sum)obj);\n }\n catch\n {\n return false;\n }\n }\n public override int GetHashCode()\n {\n return ToString().GetHashCode();\n }\n public override string ToString()\n {\n StringBuilder sb = new StringBuilder();\n for (var i = 0; i < sum.Length; i++)\n sb.Append(sum[i].ToString(\"x2\"));\n return sb.ToString();\n }\n }\n private MD5Sum screenconfig()\n {\n MD5Sum md5=new MD5Sum();\n md5.Add(Screen.AllScreens.Length); // Hash the number of screens\n for(var i=0; i<Screen.AllScreens.Length; i++)\n {\n md5.Add(Screen.AllScreens[i].Bounds.ToString()); // Hash the dimensions of this screen\n }\n return md5;\n }\n public void load()\n {\n using (RegistryKey r = Registry.CurrentUser.OpenSubKey(@\"Software\\\" + CompanyId() + @\"\\\" + AppId() + @\"\\Window State\\\" + form.Name))\n {\n if (r != null)\n {\n try\n {\n string _location = (string)r.GetValue(\"location\"), _size = (string)r.GetValue(\"size\");\n state = (FormWindowState)r.GetValue(\"state\");\n location = (Point)TypeDescriptor.GetConverter(typeof(Point)).ConvertFromInvariantString(_location);\n size = (Size)TypeDescriptor.GetConverter(typeof(Size)).ConvertFromInvariantString(_size);\n\n // Don't do anything if the screen config has since changed (otherwise windows vanish off the side)\n if (screenconfig() == new MD5Sum((string) r.GetValue(\"screenconfig\")))\n {\n form.Location = location;\n form.Size = size;\n // Don't restore if miminised (it's unhelpful as the user misses the fact it's opened)\n if (state != FormWindowState.Minimized)\n form.WindowState = state;\n }\n }\n catch (Exception)\n {\n }\n }\n }\n }\n public void save()\n {\n state = form.WindowState;\n if (form.WindowState == FormWindowState.Normal)\n {\n size = form.Size;\n location = form.Location;\n }\n else\n {\n size = form.RestoreBounds.Size;\n location = form.RestoreBounds.Location;\n }\n using (RegistryKey r = Registry.CurrentUser.CreateSubKey(@\"Software\\\" + CompanyId()+@\"\\\"+AppId() + @\"\\Window State\\\" + form.Name, RegistryKeyPermissionCheck.ReadWriteSubTree))\n {\n r.SetValue(\"state\", (int) state, RegistryValueKind.DWord);\n r.SetValue(\"location\", location.X.ToString() + \",\" + location.Y.ToString(), RegistryValueKind.String);\n r.SetValue(\"size\", size.Width.ToString()+\",\"+size.Height.ToString(), RegistryValueKind.String);\n r.SetValue(\"screenconfig\", screenconfig().ToString(), RegistryValueKind.String);\n }\n }\n abstract protected string CompanyId();\n abstract protected string AppId();\n }\n}\n</code></pre>\n\n<p>This implementation stores the position and size of a form in HKCU/Software/<CompanyId()>/<AppId()>/Window State/<form name>. It won't restore settings if the monitor configuration changes as so to prevent windows being restored off screen.</p>\n\n<p>Obviously this can't handle multiple instances of the same form. I also specifically disabled restoring minimised but that's an easy fix of the source.</p>\n\n<p>The above is designed to be dropped into its own .cs file and never touched again. You have to instantiate a local namespace copy like this (in Program.cs or your plugin main .cs file or wherever):</p>\n\n<pre><code>namespace <your app/plugin namespace name>\n{\n public class WindowSettings : nedprod.WindowSettings\n {\n public WindowSettings(Form form) : base(form) { }\n protected override string CompanyId() { return \"<your company name>\"; }\n protected override string AppId() { return \"<your app name>\"; }\n }\n ....\n</code></pre>\n\n<p>Now you have a non-abstract instantiation in the main namespace. So, to use, add this to the forms you want saved and restored:</p>\n\n<pre><code> private void IssuesForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n new WindowSettings(this).save();\n }\n\n private void IssuesForm_Load(object sender, EventArgs e)\n {\n new WindowSettings(this).load();\n }\n</code></pre>\n\n<p>Obviously feel free to customise to your own purposes. No warranty is expressed or implied. Use at your own risk - I disclaim any copyright.</p>\n\n<p>Niall</p>\n"
},
{
"answer_id": 25963789,
"author": "Jonathan Wood",
"author_id": 522663,
"author_profile": "https://Stackoverflow.com/users/522663",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the code I used.</p>\n\n<pre><code>private void SaveWindowPosition()\n{\n Rectangle rect = (WindowState == FormWindowState.Normal) ?\n new Rectangle(DesktopBounds.Left, DesktopBounds.Top, DesktopBounds.Width, DesktopBounds.Height) :\n new Rectangle(RestoreBounds.Left, RestoreBounds.Top, RestoreBounds.Width, RestoreBounds.Height);\n RegistrySettings.SetSetting(\"WindowPosition\", String.Format(\"{0},{1},{2},{3},{4}\",\n (int)this.WindowState,\n rect.Left, rect.Top, rect.Width, rect.Height));\n}\n\nprivate void RestoreWindowPosition()\n{\n try\n {\n string s = RegistrySettings.GetSetting(\"WindowPosition\", String.Empty) as string;\n if (s != null)\n {\n List<int> settings = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(v => int.Parse(v)).ToList();\n if (settings.Count == 5)\n {\n this.SetBounds(\n settings[1],\n settings[2],\n settings[3],\n settings[4]);\n this.WindowState = (FormWindowState)settings[0];\n }\n }\n }\n catch { /* Just leave current position if error */ }\n}\n</code></pre>\n\n<p>I also presented this code in my article <a href=\"http://www.blackbeltcoder.com/Articles/winforms/saving-and-restoring-a-forms-window-position\" rel=\"nofollow\">Saving and Restoring a Form's Window Position</a>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?
Related, is it possible to add new User scoped application settings AT RUNTIME? I totally see how to add settings at design time, that's not a problem. But what if I want to create one at runtime?
More details:
My application is a conversion of an existing Visual FoxPro application. I've been trying to read as much as I can about application settings, user settings, etc. and get myself clear on the .Net way of doing things, but there are still several things I am confused on.
In the Fox app, saved settings are stored in the registry. My forms are subclassed, and I have base class code that automatically saves the form position and size in the registry keyed on the form name. Whenever I create a new form, I don't have to do anything special to get this behavior; it's built in to the base class. My .Net forms are also subclassed, that part is working well.
In .Net, I get the impression I'm supposed to use User scoped settings for things like user preferences. Size and location of a form definitely seem like a user preference. But, I can't see any way to automatically add these settings to the project. In other words, every time I add a new form to my project (and their are 100's of forms), I have to remember to ADD a User scoped application setting and be sure to give it the same name as the form, i.e., "FormMySpecialSizePosition" to hold the size and position. I'd rather not have to remember to do that. Is this just tough luck? Or am I totally barking up the wrong tree by trying to use User scoped settings? Do I need to create my own XML file to hold settings, so that I can do whatever I want (i.e, add a new setting at runtime)? Or something else?
Surely this is very common and somebody can tell the "right" way to do it. | ```
private void Form1_Load( object sender, EventArgs e )
{
// restore location and size of the form on the desktop
this.DesktopBounds =
new Rectangle(Properties.Settings.Default.Location,
Properties.Settings.Default.Size);
// restore form's window state
this.WindowState = ( FormWindowState )Enum.Parse(
typeof(FormWindowState),
Properties.Settings.Default.WindowState);
}
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
System.Drawing.Rectangle bounds = this.WindowState != FormWindowState.Normal ? this.RestoreBounds : this.DesktopBounds;
Properties.Settings.Default.Location = bounds.Location;
Properties.Settings.Default.Size = bounds.Size;
Properties.Settings.Default.WindowState =
Enum.GetName(typeof(FormWindowState), this.WindowState);
// persist location ,size and window state of the form on the desktop
Properties.Settings.Default.Save();
}
``` |
92,546 | <p>When refactoring away some <code>#defines</code> I came across declarations similar to the following in a C++ header file:</p>
<pre><code>static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
</code></pre>
<p>The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic <code>#ifndef HEADER</code> <code>#define HEADER</code> <code>#endif</code> trick (if that matters).</p>
<p>Does the static mean only one copy of <code>VAL</code> is created, in case the header is included by more than one source file?</p>
| [
{
"answer_id": 92568,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 0,
"selected": false,
"text": "<p>Static prevents another compilation unit from externing that variable so that the compiler can just \"inline\" the variable's value where it is used and not create memory storage for it.</p>\n\n<p>In your second example, the compiler cannot assume that some other source file won't extern it, so it must actually store that value in memory somewhere.</p>\n"
},
{
"answer_id": 92611,
"author": "Superpolock",
"author_id": 16496,
"author_profile": "https://Stackoverflow.com/users/16496",
"pm_score": -1,
"selected": false,
"text": "<p>Static prevents the compiler from adding multiple instances. This becomes less important with #ifndef protection, but assuming the header is included in two seperate libraries, and the application is linked, two instances would be included.</p>\n"
},
{
"answer_id": 92641,
"author": "Justsalt",
"author_id": 13693,
"author_profile": "https://Stackoverflow.com/users/13693",
"pm_score": 8,
"selected": true,
"text": "<p>The <code>static</code> means that there will be one copy of <code>VAL</code> created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of <code>VAL</code> that will collide at link time. In C, without the <code>static</code> you would need to ensure that only one source file defined <code>VAL</code> while the other source files declared it <code>extern</code>. Usually one would do this by defining it (possibly with an initializer) in a source file and put the <code>extern</code> declaration in a header file.</p>\n\n<p><code>static</code> variables at global level are only visible in their own source file whether they got there via an include or were in the main file.</p>\n\n<hr>\n\n<p><em>Editor's note:</em> In C++, <code>const</code> objects with neither the <code>static</code> nor <code>extern</code> keywords in their declaration are implicitly <code>static</code>.</p>\n"
},
{
"answer_id": 92664,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 3,
"selected": false,
"text": "<p>The static declaration at this level of code means that the variabel is only visible in the current compilation unit. This means that only code within that module will see that variable. </p>\n\n<p>if you have a header file that declares a variable static and that header is included in multiple C/CPP files, then that variable will be \"local\" to those modules. There will be N copies of that variable for the N places that header is included. They are not related to each other at all. Any code within any of those source files will only reference the variable that is declared within that module.</p>\n\n<p>In this particular case, the 'static' keyword doesn't seem to be providing any benefit. I might be missing something, but it seems to not matter -- I've never seen anything done like this before.</p>\n\n<p>As for inlining, in this case the variable is likely inlined, but that's only because it's declared const. The compiler <em>might</em> be more likely to inline module static variables, but that's dependent on the situation and the code being compiled. There is no guarantee that the compiler will inline 'statics'.</p>\n"
},
{
"answer_id": 92690,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that these declarations are at global scope (i.e. aren't member variables), then:</p>\n\n<p><strong>static</strong> means 'internal linkage'. In this case, since it is declared <strong>const</strong> this can be optimised/inlined by the compiler. If you omit the <strong>const</strong> then the compiler must allocate storage in each compilation unit.</p>\n\n<p>By omitting <strong>static</strong> the linkage is <strong>extern</strong> by default. Again, you've been saved by the <strong>const</strong>ness - the compiler can optimise/inline usage. If you drop the <strong>const</strong> then you will get a <em>multiply defined symbols</em> error at link time.</p>\n"
},
{
"answer_id": 92693,
"author": "slicedlime",
"author_id": 11230,
"author_profile": "https://Stackoverflow.com/users/11230",
"pm_score": 6,
"selected": false,
"text": "<p>The static will mean you get one copy per file, but unlike others have said it's perfectly legal to do so. You can easily test this with a small code sample:</p>\n\n<p>test.h:</p>\n\n<pre><code>static int TEST = 0;\nvoid test();\n</code></pre>\n\n<p>test1.cpp:</p>\n\n<pre><code>#include <iostream>\n#include \"test.h\"\n\nint main(void) {\n std::cout << &TEST << std::endl;\n test();\n}\n</code></pre>\n\n<p>test2.cpp:</p>\n\n<pre><code>#include <iostream>\n#include \"test.h\"\n\nvoid test() {\n std::cout << &TEST << std::endl;\n}\n</code></pre>\n\n<p>Running this gives you this output:</p>\n\n<blockquote>\n <p>0x446020<br>\n 0x446040</p>\n</blockquote>\n"
},
{
"answer_id": 92749,
"author": "Jan de Vos",
"author_id": 11215,
"author_profile": "https://Stackoverflow.com/users/11215",
"pm_score": 2,
"selected": false,
"text": "<p>The C book (free online) has a chapter about linkage, which explains the meaning of 'static' in more detail (although the correct answer is already given in other comments):\n<a href=\"http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html\" rel=\"nofollow noreferrer\">http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html</a></p>\n"
},
{
"answer_id": 93663,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>static</code> and <code>extern</code> tags on file-scoped variables determine whether they are accessible in other translation units (i.e. other <code>.c</code> or <code>.cpp</code> files). </p>\n\n<ul>\n<li><p><code>static</code> gives the variable internal linkage, hiding it from other translation units. However, variables with internal linkage can be defined in multiple translation units.</p></li>\n<li><p><code>extern</code> gives the variable external linkage, making it visible to other translation units. Typically this means that the variable must only be defined in one translation unit.</p></li>\n</ul>\n\n<p>The default (when you don't specify <code>static</code> or <code>extern</code>) is one of those areas in which C and C++ differ. </p>\n\n<ul>\n<li><p>In C, file-scoped variables are <code>extern</code> (external linkage) by default. If you're using C, <code>VAL</code> is <code>static</code> and <code>ANOTHER_VAL</code> is <code>extern</code>.</p></li>\n<li><p>In C++, file-scoped variables are <code>static</code> (internal linkage) by default if they are <code>const</code>, and <code>extern</code> by default if they are not. If you're using C++, both <code>VAL</code> and <code>ANOTHER_VAL</code> are <code>static</code>.</p></li>\n</ul>\n\n<p>From a draft of the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf\" rel=\"noreferrer\">C specification</a>:</p>\n\n<blockquote>\n <p>6.2.2 Linkages of identifiers\n ... \n -5- If the declaration of an identifier for a function has no storage-class specifier, its linkage\n is determined exactly as if it were declared with the storage-class specifier extern. If\n the declaration of an identifier for an object has file scope and no storage-class specifier,\n its linkage is external.</p>\n</blockquote>\n\n<p>From a draft of the <a href=\"http://www.kuzbass.ru:8086/docs/isocpp/dcl.html\" rel=\"noreferrer\">C++ specification</a>:</p>\n\n<blockquote>\n <p>7.1.1 - Storage class specifiers [dcl.stc]\n ...\n -6- A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. Objects declared const and not explicitly declared extern have internal linkage. </p>\n</blockquote>\n"
},
{
"answer_id": 96783,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 2,
"selected": false,
"text": "<p>To answer the question, \"does the static mean only one copy of VAL is created, in case the header is included by more than one source file?\"...</p>\n\n<p><strong>NO</strong>. VAL will always be defined separately in every file that includes the header.</p>\n\n<p>The standards for C and C++ do cause a difference in this case.</p>\n\n<blockquote>\n <p>In C, file-scoped variables are extern by default. If you're using C, VAL is static and ANOTHER_VAL is extern. </p>\n</blockquote>\n\n<p>Note that Modern linkers may complain about ANOTHER_VAL if the header is included in different files (same global name defined twice), and would definitely complain if ANOTHER_VAL was initialised to a different value in another file</p>\n\n<blockquote>\n <p>In C++, file-scoped variables are static by default if they are const, and extern by default if they are not. If you're using C++, both VAL and ANOTHER_VAL are static.</p>\n</blockquote>\n\n<p>You also need to take account of the fact that both variables are designated const. Ideally the compiler would always choose to inline these variables and not include any storage for them. There is a whole host of reasons why storage can be allocated. Ones I can think of...</p>\n\n<ul>\n<li>debug options</li>\n<li>address taken in the file</li>\n<li>compiler always allocates storage (complex const types can't easily be inlined, so becomes a special case for basic types)</li>\n</ul>\n"
},
{
"answer_id": 2718315,
"author": "Nitin",
"author_id": 326492,
"author_profile": "https://Stackoverflow.com/users/326492",
"pm_score": 3,
"selected": false,
"text": "<p><code>const</code> variables in C++ have internal linkage. So, using <code>static</code> has no effect. </p>\n\n<p><strong>a.h</strong></p>\n\n<pre><code>const int i = 10;\n</code></pre>\n\n<p><strong>one.cpp</strong></p>\n\n<pre><code>#include \"a.h\"\n\nfunc()\n{\n cout << i;\n}\n</code></pre>\n\n<p><strong>two.cpp</strong></p>\n\n<pre><code>#include \"a.h\"\n\nfunc1()\n{\n cout << i;\n}\n</code></pre>\n\n<p>If this were a C program, you would get 'multiple definition' error for <code>i</code> (due to external linkage).</p>\n"
},
{
"answer_id": 19077035,
"author": "Gajendra Kumar",
"author_id": 2828177,
"author_profile": "https://Stackoverflow.com/users/2828177",
"pm_score": 1,
"selected": false,
"text": "<p>You can’t declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended.</p>\n"
},
{
"answer_id": 28106844,
"author": "Konstantin Burlachenko",
"author_id": 1154447,
"author_profile": "https://Stackoverflow.com/users/1154447",
"pm_score": 1,
"selected": false,
"text": "<p><strong>const</strong> variables are by default static in C++, but extern C. So if you use C++ this no sense what construction to use.</p>\n\n<p>(7.11.6 C++ 2003, and Apexndix C has samples)</p>\n\n<p>Example in compare compile/link sources as C and C++ program:</p>\n\n<pre><code>bruziuz:~/test$ cat a.c\nconst int b = 22;\nint main(){return 0;}\nbruziuz:~/test$ cat b.c\nconst int b=2;\nbruziuz:~/test$ gcc -x c -std=c89 a.c b.c\n/tmp/ccSKKIRZ.o:(.rodata+0x0): multiple definition of `b'\n/tmp/ccDSd0V3.o:(.rodata+0x0): first defined here\ncollect2: error: ld returned 1 exit status\nbruziuz:~/test$ gcc -x c++ -std=c++03 a.c b.c \nbruziuz:~/test$ \nbruziuz:~/test$ gcc --version | head -n1\ngcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| When refactoring away some `#defines` I came across declarations similar to the following in a C++ header file:
```
static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
```
The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic `#ifndef HEADER` `#define HEADER` `#endif` trick (if that matters).
Does the static mean only one copy of `VAL` is created, in case the header is included by more than one source file? | The `static` means that there will be one copy of `VAL` created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of `VAL` that will collide at link time. In C, without the `static` you would need to ensure that only one source file defined `VAL` while the other source files declared it `extern`. Usually one would do this by defining it (possibly with an initializer) in a source file and put the `extern` declaration in a header file.
`static` variables at global level are only visible in their own source file whether they got there via an include or were in the main file.
---
*Editor's note:* In C++, `const` objects with neither the `static` nor `extern` keywords in their declaration are implicitly `static`. |
92,613 | <p>I have some code which is supposed to display a short message. Here's the pertinent code:</p>
<pre><code>DATA SEGMENT 'DATA'
MSG DB 0AH, 0DH, 'Hello, Adam', '$'
CHAR DB 00H
DATA ENDS
CODE SEGMENT 'CODE'
PRINT_MSG:
MOV AH, 09H ;Command to print string of characters
MOV DX, OFFSET MSG ;Mov address of message into DX
INT 21H ;DOS Interrupt
JMP WAITING ;Loop back to waiting state
CODE ENDS
</code></pre>
<p>And the output is:</p>
<pre><code>E:\ece323\software\lab2>MAIN.EXE
?F ^?¶ ? N? ? -!-
Hello, Adam-
</code></pre>
<p>What is going on here?</p>
| [
{
"answer_id": 92708,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": "<p>My guess is that your DS does not point to your data-segment.</p>\n\n<p>Int21 Function 0x09 takes the string from DS:DX.</p>\n\n<p>Remember that DX is only a 16 bit register. To access data outside the 16 bit range you have to use segment registers. These are called DS and ES for data, CS for code and SS for the stack (there are FS and GS on i386 as well).</p>\n\n<p>The exact address you load from is given by 16 * segment_register + offset_register. Int21 cannot guess where your DS is, so you have to load it prior to call the interrupt.</p>\n\n<p>I guess you have never initialized your DS register, so it most likely points to the code, not the data-segment.</p>\n\n<p>Try to replace your </p>\n\n<pre><code> MOV DX, offset MSG\n</code></pre>\n\n<p>by:</p>\n\n<pre><code> LDS DX, MSG ; Check that, it's been ages since I've written 16 bit code.\n</code></pre>\n\n<p>Unfortunatley it's been years since I've last played with 16 bit assembler, so I can't check it, but LDS should do the trick.</p>\n\n<p>You may also load DS indirectly at your program startup by something like this:</p>\n\n<pre><code> MOV AX, SEG DATA ; check that - can be SEGMENT or so as well.\n MOV DS, AX\n</code></pre>\n"
},
{
"answer_id": 92724,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "<p>My guess is that you are probably not running in \"Real\" mode, which is needed for MSDOS programs in general (and Int 21h interrupts in specific) to work. </p>\n\n<p>Windows has been running exclusively in \"Protected\" mode since Windows 95; The Command Prompt has been in Protected mode since, I think, Windows 2000. </p>\n\n<p>You may want to try create a shortcut do you EXE, and then setting the Compatibility options in the shortcut.</p>\n"
},
{
"answer_id": 92767,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following change:</p>\n\n<pre><code>DATA SEGMENT 'DATA'\nERROR_MSG DB 'DS:DX is wrong'\nMSG DB 0AH, 0DH, 'Hello, Adam', '$'\nCHAR DB 00H\nDATA ENDS\n</code></pre>\n\n<p>If the error-message displays then DS:DX is wrong, so either DS doesn't point to the DATA segment, or 'OFFSET MSG' is wrong for some reason...my asm is rusty but try ADDR instead of OFFSET (?)</p>\n\n<p>If the error-message doesn't display, the problem happened before execution reached PRINT_MSG.</p>\n"
},
{
"answer_id": 174275,
"author": "akalenuk",
"author_id": 25459,
"author_profile": "https://Stackoverflow.com/users/25459",
"pm_score": 0,
"selected": false,
"text": "<p>Nils is right, DS register need to be set in order to use this function of int 21. Try the second part with EAX transition first, it should work for sure. </p>\n\n<p>And there's no need in 0 char after the string. 9-th function doesn't work with null terminated strings, this '$' char works instead of 0.</p>\n"
},
{
"answer_id": 4325893,
"author": "Brian Knoblauch",
"author_id": 15689,
"author_profile": "https://Stackoverflow.com/users/15689",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you're display part of the PSP. Is this a .COM by any chance? If you forget the ORG 100h assembler directive, OFFSETs will not point where you think they should... As an interesting side note is that just switching from MOV OFFSET to LEA will also \"work\". MASM is smart enough to figure out what you're doing when you use LEA, whereas it may not with OFFSET (yeah, I learned all this the hard way a long time ago... :-) ).</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13790/"
]
| I have some code which is supposed to display a short message. Here's the pertinent code:
```
DATA SEGMENT 'DATA'
MSG DB 0AH, 0DH, 'Hello, Adam', '$'
CHAR DB 00H
DATA ENDS
CODE SEGMENT 'CODE'
PRINT_MSG:
MOV AH, 09H ;Command to print string of characters
MOV DX, OFFSET MSG ;Mov address of message into DX
INT 21H ;DOS Interrupt
JMP WAITING ;Loop back to waiting state
CODE ENDS
```
And the output is:
```
E:\ece323\software\lab2>MAIN.EXE
?F ^?¶ ? N? ? -!-
Hello, Adam-
```
What is going on here? | My guess is that your DS does not point to your data-segment.
Int21 Function 0x09 takes the string from DS:DX.
Remember that DX is only a 16 bit register. To access data outside the 16 bit range you have to use segment registers. These are called DS and ES for data, CS for code and SS for the stack (there are FS and GS on i386 as well).
The exact address you load from is given by 16 \* segment\_register + offset\_register. Int21 cannot guess where your DS is, so you have to load it prior to call the interrupt.
I guess you have never initialized your DS register, so it most likely points to the code, not the data-segment.
Try to replace your
```
MOV DX, offset MSG
```
by:
```
LDS DX, MSG ; Check that, it's been ages since I've written 16 bit code.
```
Unfortunatley it's been years since I've last played with 16 bit assembler, so I can't check it, but LDS should do the trick.
You may also load DS indirectly at your program startup by something like this:
```
MOV AX, SEG DATA ; check that - can be SEGMENT or so as well.
MOV DS, AX
``` |
92,620 | <p>I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with:</p>
<pre><code><urlopen error The read operation timed out>
</code></pre>
<p>If I set the timeout (no matter how long), it dies even more immediately with:</p>
<pre><code><urlopen error The connect operation timed out>
</code></pre>
<p>The latter is reproducible with:</p>
<pre><code>import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
</code></pre>
<p>returning:</p>
<pre><code>socket.sslerror: The connect operation timed out
</code></pre>
<p>but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this.</p>
| [
{
"answer_id": 93401,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>www.google.com is not accessible by HTTPS. It redirects to insecure HTTP. To get to mail, you should be going go <a href=\"https://mail.google.com\" rel=\"nofollow noreferrer\">https://mail.google.com</a></p>\n"
},
{
"answer_id": 93404,
"author": "defnull",
"author_id": 407880,
"author_profile": "https://Stackoverflow.com/users/407880",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import socket\nsocket.setdefaulttimeout(30000)\nsock = socket.socket()\nsock.connect(('www.google.com', 443))\nssl = socket.ssl(sock)\nssl.server()\n--> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com'\n</code></pre>\n\n<p>It works just fine. I can't reproduce your error.</p>\n"
},
{
"answer_id": 96565,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 0,
"selected": false,
"text": "<p>The first thing I would check is whether you need to connect via an HTTP proxy (in which case direct connections bypassing the proxy will likely time out). Run Wireshark and see what happens.</p>\n"
},
{
"answer_id": 67149643,
"author": "Martin Gergov",
"author_id": 1857005,
"author_profile": "https://Stackoverflow.com/users/1857005",
"pm_score": 0,
"selected": false,
"text": "<p>There is no timeout connecting to <code>www.google.com</code>, but Python 3.x now offers the <code>ssl</code> module so OP's sample code won't work.</p>\n<p>Here's something similar that will work with current versions of Python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import ssl\nimport socket\nfrom pprint import pprint\n\n\nhostname = 'www.google.org'\ncontext = ssl.create_default_context()\n\nwith socket.create_connection((hostname, 443)) as sock:\n with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n pprint(ssock.getpeercert()['subject'])\n</code></pre>\n<p>Which produces:</p>\n<pre class=\"lang-py prettyprint-override\"><code>((('countryName', 'US'),),\n (('stateOrProvinceName', 'California'),),\n (('localityName', 'Mountain View'),),\n (('organizationName', 'Google LLC'),),\n (('commonName', 'misc.google.com'),))\n</code></pre>\n<p>Read more about the ssl module here: <a href=\"https://docs.python.org/3/library/ssl.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/ssl.html</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4300/"
]
| I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with:
```
<urlopen error The read operation timed out>
```
If I set the timeout (no matter how long), it dies even more immediately with:
```
<urlopen error The connect operation timed out>
```
The latter is reproducible with:
```
import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
```
returning:
```
socket.sslerror: The connect operation timed out
```
but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this. | ```
import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
ssl.server()
--> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com'
```
It works just fine. I can't reproduce your error. |
92,689 | <p>I am writing a Composite control, which contains a listview to display a table of items. Normally when using a ListView in Asp.NET I would define the templates in the code-forward.</p>
<pre><code><asp:ListView runat="server" ID="ArticleList">
<LayoutTemplate>
<div class="ContentContainer">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<div><%# Eval("Content") %></div>
</div>
</ItemTemplate>
</asp:ListView>
</code></pre>
<p>I assume it's something like:</p>
<pre><code>ListView view = new ListView();
view.LayoutTemplate = .....
view.ItemTemplate = .....
// when do I call these?
view.DataSource = myDataSource;
view.DataBind();
</code></pre>
<p><strong>Update:</strong>
I created 2 templates by implementing the ITemplate interface:</p>
<pre><code>private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var outer = new HtmlGenericControl("div");
var inner = new HtmlGenericControl("div") { ID = "itemPlaceholder" };
table.Rows.Add(row);
container.Controls.Add(table);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var inner = new HtmlGenericControl("div");
container.Controls.Add(inner);
}
}
</code></pre>
<p>and I can add them using:</p>
<pre><code>dataList.LayoutTemplate = new LayoutTemplate();
dataList.ItemTemplate = new ItemTemplate();
</code></pre>
<p>But then I get stuck, since container.DataItem is null.</p>
| [
{
"answer_id": 93348,
"author": "paudirac",
"author_id": 15554,
"author_profile": "https://Stackoverflow.com/users/15554",
"pm_score": 2,
"selected": false,
"text": "<p>Could this link be of some help? <a href=\"http://web.archive.org/web/20120414044008/http://iridescence.no/post/Using-Templated-Controls-Programmatically.aspx\" rel=\"nofollow noreferrer\">Using Templated Controls Programmatically</a></p>\n\n<p>Generating the Templates at Design-Time (in order to persist them in the aspx file) is a little bit trickier, but the DataBinding will work automatically.</p>\n"
},
{
"answer_id": 94536,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "<p>Setup a class like:</p>\n\n<pre><code>public delegate void InstantiateTemplateDelegate(Control container);\n\npublic class GenericTemplateImplementation : ITemplate\n{\n private InstantiateTemplateDelegate instantiateTemplate;\n\n public void InstantiateIn(Control container)\n {\n this.instantiateTemplate(container);\n }\n\n public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate)\n {\n this.instantiateTemplate = instantiateTemplate;\n }\n}\n</code></pre>\n\n<p>And then do the following:</p>\n\n<pre><code> view.LayoutTemplate = new GenericTemplateImplementation(p =>\n {\n p.Controls.Add(new Label { Text = \"Foo\" });\n });\n</code></pre>\n"
},
{
"answer_id": 149025,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 4,
"selected": true,
"text": "<p>The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate. </p>\n\n<p>The complete solution:</p>\n\n<pre><code>public class FibonacciControl : CompositeControl\n{\n public FibonacciControl()\n {\n // ....\n }\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n ListView view = new ListView();\n\n view.LayoutTemplate = new LayoutTemplate();\n view.ItemTemplate = new ItemTemplate();\n\n view.DataSource = FibonacciSequence();\n view.DataBind();\n\n this.Controls.Add(view);\n }\n\n private IEnumerable<int> FibonacciSequence()\n {\n\n int i1 = 0;\n int i2 = 1;\n\n for (int i = 0; i < Iterations; i++)\n {\n yield return i1 + i2;\n int temp = i1 + i2;\n i1 = i2;\n i2 = temp;\n }\n yield break;\n }\n\n public int Iterations { get; set; }\n\n private class LayoutTemplate : ITemplate\n {\n\n public void InstantiateIn(Control container)\n {\n var ol = new HtmlGenericControl(\"ol\");\n var li = new HtmlGenericControl(\"li\") { ID = \"itemPlaceholder\" };\n ol.Controls.Add(li);\n\n container.Controls.Add(ol);\n }\n }\n\n private class ItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var li = new HtmlGenericControl(\"li\");\n\n li.DataBinding += DataBinding;\n container.Controls.Add(li);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n\n container.Controls.Add( new Literal(){Text = dataItem.ToString() });\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 348158,
"author": "Michael Washington",
"author_id": 384585,
"author_profile": "https://Stackoverflow.com/users/384585",
"pm_score": 0,
"selected": false,
"text": "<p>Building on Sonteks example here is an example that creates a template that contains elements that are then bound using databinding.</p>\n\n<pre><code>public partial class View : PortalModuleBase\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n #region MasterListView_ItemDataBound\n public void MasterListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n {\n ListViewItem objListViewItem = (ListViewItem)e.Item;\n ListViewDataItem objListViewDataItem = objListViewItem as ListViewDataItem;\n\n if (objListViewDataItem != null)\n {\n Tab objTab = (Tab)objListViewDataItem.DataItem;\n IEnumerable<Tab> Tabs = CustomData(objTab.TabID);\n\n Label TabIDLabel = (Label)objListViewItem.FindControl(\"TabIDLabel\");\n Label TabNameLabel = (Label)objListViewItem.FindControl(\"TabNameLabel\");\n\n TabIDLabel.Text = objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n AddListView(objTab.TabName, objListViewItem, Tabs);\n }\n }\n #endregion\n\n #region CustomData\n static IEnumerable<Tab> CustomData(int? ParentID)\n {\n TabAdminDataContext objTabAdminDataContext = new TabAdminDataContext();\n\n var myCustomData = from Tabs in objTabAdminDataContext.Tabs\n where Tabs.ParentId == ParentID\n select Tabs;\n\n return myCustomData.AsEnumerable();\n }\n #endregion\n\n #region AddListView\n private void AddListView(string CurrentTabName, Control container, IEnumerable<Tab> ChildTabs)\n {\n // The Tab has Children so add a ListView\n if (ChildTabs.Count() > 0)\n {\n ListView ChildListView = new ListView();\n ChildListView.ID = \"ChildListView\";\n ChildListView.ItemCommand += ListView_ItemCommand;\n ChildListView.EnableViewState = true;\n ChildListView.LayoutTemplate = new MyLayoutTemplate();\n ChildListView.ItemTemplate = new MyItemTemplate();\n ChildListView.DataSource = ChildTabs;\n ChildListView.DataBind();\n\n // Put the ListView in a Panel\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"ChildListViewTR\" };\n var oTD = new HtmlGenericControl(\"td\") { ID = \"ChildListViewTD\" };\n\n Panel objPanel = new Panel();\n objPanel.ID = \"ListViewPanel\";\n objPanel.ToolTip = CurrentTabName;\n objPanel.Controls.Add(ChildListView);\n\n oTD.Controls.Add(objPanel);\n oTR.Controls.Add(oTD);\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ListView_ItemCommand\n protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)\n {\n LinkButton objButton = (LinkButton)sender;\n Label1.Text = objButton.Text;\n MasterListView.DataBind();\n }\n #endregion\n\n #region MyLayoutTemplate\n public class MyLayoutTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"itemPlaceholder\" };\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ItemTemplate\n public class MyItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\");\n\n var oTD1 = new HtmlGenericControl(\"td\");\n LinkButton TabIDLinkButton = new LinkButton();\n TabIDLinkButton.ID = \"TabIDLinkButton\";\n oTD1.Controls.Add(TabIDLinkButton);\n oTR.Controls.Add(oTD1);\n\n var oTD2 = new HtmlGenericControl(\"td\");\n Label TabNameLabel = new Label();\n TabNameLabel.ID = \"TabNameLabel\";\n oTD2.Controls.Add(TabNameLabel);\n oTR.Controls.Add(oTD2);\n\n oTR.DataBinding += DataBinding;\n container.Controls.Add(oTR);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n Tab objTab = (Tab)dataItem;\n\n LinkButton TabIDLinkButton = (LinkButton)container.FindControl(\"TabIDLinkButton\");\n Label TabNameLabel = (Label)container.FindControl(\"TabNameLabel\");\n\n TabIDLinkButton.Text = \"+\" + objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n IEnumerable<Tab> ChildTabs = View.CustomData(objTab.TabID);\n\n View objView = new View();\n objView.AddListView(objTab.TabName, container, ChildTabs);\n }\n\n }\n #endregion\n\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1837197/"
]
| I am writing a Composite control, which contains a listview to display a table of items. Normally when using a ListView in Asp.NET I would define the templates in the code-forward.
```
<asp:ListView runat="server" ID="ArticleList">
<LayoutTemplate>
<div class="ContentContainer">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<div><%# Eval("Content") %></div>
</div>
</ItemTemplate>
</asp:ListView>
```
I assume it's something like:
```
ListView view = new ListView();
view.LayoutTemplate = .....
view.ItemTemplate = .....
// when do I call these?
view.DataSource = myDataSource;
view.DataBind();
```
**Update:**
I created 2 templates by implementing the ITemplate interface:
```
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var outer = new HtmlGenericControl("div");
var inner = new HtmlGenericControl("div") { ID = "itemPlaceholder" };
table.Rows.Add(row);
container.Controls.Add(table);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var inner = new HtmlGenericControl("div");
container.Controls.Add(inner);
}
}
```
and I can add them using:
```
dataList.LayoutTemplate = new LayoutTemplate();
dataList.ItemTemplate = new ItemTemplate();
```
But then I get stuck, since container.DataItem is null. | The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate.
The complete solution:
```
public class FibonacciControl : CompositeControl
{
public FibonacciControl()
{
// ....
}
protected override void CreateChildControls()
{
base.CreateChildControls();
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
view.DataSource = FibonacciSequence();
view.DataBind();
this.Controls.Add(view);
}
private IEnumerable<int> FibonacciSequence()
{
int i1 = 0;
int i2 = 1;
for (int i = 0; i < Iterations; i++)
{
yield return i1 + i2;
int temp = i1 + i2;
i1 = i2;
i2 = temp;
}
yield break;
}
public int Iterations { get; set; }
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add( new Literal(){Text = dataItem.ToString() });
}
}
}
``` |
92,696 | <p>I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame.</p>
<p>I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit.</p>
| [
{
"answer_id": 93348,
"author": "paudirac",
"author_id": 15554,
"author_profile": "https://Stackoverflow.com/users/15554",
"pm_score": 2,
"selected": false,
"text": "<p>Could this link be of some help? <a href=\"http://web.archive.org/web/20120414044008/http://iridescence.no/post/Using-Templated-Controls-Programmatically.aspx\" rel=\"nofollow noreferrer\">Using Templated Controls Programmatically</a></p>\n\n<p>Generating the Templates at Design-Time (in order to persist them in the aspx file) is a little bit trickier, but the DataBinding will work automatically.</p>\n"
},
{
"answer_id": 94536,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "<p>Setup a class like:</p>\n\n<pre><code>public delegate void InstantiateTemplateDelegate(Control container);\n\npublic class GenericTemplateImplementation : ITemplate\n{\n private InstantiateTemplateDelegate instantiateTemplate;\n\n public void InstantiateIn(Control container)\n {\n this.instantiateTemplate(container);\n }\n\n public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate)\n {\n this.instantiateTemplate = instantiateTemplate;\n }\n}\n</code></pre>\n\n<p>And then do the following:</p>\n\n<pre><code> view.LayoutTemplate = new GenericTemplateImplementation(p =>\n {\n p.Controls.Add(new Label { Text = \"Foo\" });\n });\n</code></pre>\n"
},
{
"answer_id": 149025,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 4,
"selected": true,
"text": "<p>The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate. </p>\n\n<p>The complete solution:</p>\n\n<pre><code>public class FibonacciControl : CompositeControl\n{\n public FibonacciControl()\n {\n // ....\n }\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n ListView view = new ListView();\n\n view.LayoutTemplate = new LayoutTemplate();\n view.ItemTemplate = new ItemTemplate();\n\n view.DataSource = FibonacciSequence();\n view.DataBind();\n\n this.Controls.Add(view);\n }\n\n private IEnumerable<int> FibonacciSequence()\n {\n\n int i1 = 0;\n int i2 = 1;\n\n for (int i = 0; i < Iterations; i++)\n {\n yield return i1 + i2;\n int temp = i1 + i2;\n i1 = i2;\n i2 = temp;\n }\n yield break;\n }\n\n public int Iterations { get; set; }\n\n private class LayoutTemplate : ITemplate\n {\n\n public void InstantiateIn(Control container)\n {\n var ol = new HtmlGenericControl(\"ol\");\n var li = new HtmlGenericControl(\"li\") { ID = \"itemPlaceholder\" };\n ol.Controls.Add(li);\n\n container.Controls.Add(ol);\n }\n }\n\n private class ItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var li = new HtmlGenericControl(\"li\");\n\n li.DataBinding += DataBinding;\n container.Controls.Add(li);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n\n container.Controls.Add( new Literal(){Text = dataItem.ToString() });\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 348158,
"author": "Michael Washington",
"author_id": 384585,
"author_profile": "https://Stackoverflow.com/users/384585",
"pm_score": 0,
"selected": false,
"text": "<p>Building on Sonteks example here is an example that creates a template that contains elements that are then bound using databinding.</p>\n\n<pre><code>public partial class View : PortalModuleBase\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n #region MasterListView_ItemDataBound\n public void MasterListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n {\n ListViewItem objListViewItem = (ListViewItem)e.Item;\n ListViewDataItem objListViewDataItem = objListViewItem as ListViewDataItem;\n\n if (objListViewDataItem != null)\n {\n Tab objTab = (Tab)objListViewDataItem.DataItem;\n IEnumerable<Tab> Tabs = CustomData(objTab.TabID);\n\n Label TabIDLabel = (Label)objListViewItem.FindControl(\"TabIDLabel\");\n Label TabNameLabel = (Label)objListViewItem.FindControl(\"TabNameLabel\");\n\n TabIDLabel.Text = objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n AddListView(objTab.TabName, objListViewItem, Tabs);\n }\n }\n #endregion\n\n #region CustomData\n static IEnumerable<Tab> CustomData(int? ParentID)\n {\n TabAdminDataContext objTabAdminDataContext = new TabAdminDataContext();\n\n var myCustomData = from Tabs in objTabAdminDataContext.Tabs\n where Tabs.ParentId == ParentID\n select Tabs;\n\n return myCustomData.AsEnumerable();\n }\n #endregion\n\n #region AddListView\n private void AddListView(string CurrentTabName, Control container, IEnumerable<Tab> ChildTabs)\n {\n // The Tab has Children so add a ListView\n if (ChildTabs.Count() > 0)\n {\n ListView ChildListView = new ListView();\n ChildListView.ID = \"ChildListView\";\n ChildListView.ItemCommand += ListView_ItemCommand;\n ChildListView.EnableViewState = true;\n ChildListView.LayoutTemplate = new MyLayoutTemplate();\n ChildListView.ItemTemplate = new MyItemTemplate();\n ChildListView.DataSource = ChildTabs;\n ChildListView.DataBind();\n\n // Put the ListView in a Panel\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"ChildListViewTR\" };\n var oTD = new HtmlGenericControl(\"td\") { ID = \"ChildListViewTD\" };\n\n Panel objPanel = new Panel();\n objPanel.ID = \"ListViewPanel\";\n objPanel.ToolTip = CurrentTabName;\n objPanel.Controls.Add(ChildListView);\n\n oTD.Controls.Add(objPanel);\n oTR.Controls.Add(oTD);\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ListView_ItemCommand\n protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)\n {\n LinkButton objButton = (LinkButton)sender;\n Label1.Text = objButton.Text;\n MasterListView.DataBind();\n }\n #endregion\n\n #region MyLayoutTemplate\n public class MyLayoutTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"itemPlaceholder\" };\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ItemTemplate\n public class MyItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\");\n\n var oTD1 = new HtmlGenericControl(\"td\");\n LinkButton TabIDLinkButton = new LinkButton();\n TabIDLinkButton.ID = \"TabIDLinkButton\";\n oTD1.Controls.Add(TabIDLinkButton);\n oTR.Controls.Add(oTD1);\n\n var oTD2 = new HtmlGenericControl(\"td\");\n Label TabNameLabel = new Label();\n TabNameLabel.ID = \"TabNameLabel\";\n oTD2.Controls.Add(TabNameLabel);\n oTR.Controls.Add(oTD2);\n\n oTR.DataBinding += DataBinding;\n container.Controls.Add(oTR);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n Tab objTab = (Tab)dataItem;\n\n LinkButton TabIDLinkButton = (LinkButton)container.FindControl(\"TabIDLinkButton\");\n Label TabNameLabel = (Label)container.FindControl(\"TabNameLabel\");\n\n TabIDLinkButton.Text = \"+\" + objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n IEnumerable<Tab> ChildTabs = View.CustomData(objTab.TabID);\n\n View objView = new View();\n objView.AddListView(objTab.TabName, container, ChildTabs);\n }\n\n }\n #endregion\n\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885/"
]
| I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame.
I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit. | The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate.
The complete solution:
```
public class FibonacciControl : CompositeControl
{
public FibonacciControl()
{
// ....
}
protected override void CreateChildControls()
{
base.CreateChildControls();
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
view.DataSource = FibonacciSequence();
view.DataBind();
this.Controls.Add(view);
}
private IEnumerable<int> FibonacciSequence()
{
int i1 = 0;
int i2 = 1;
for (int i = 0; i < Iterations; i++)
{
yield return i1 + i2;
int temp = i1 + i2;
i1 = i2;
i2 = temp;
}
yield break;
}
public int Iterations { get; set; }
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add( new Literal(){Text = dataItem.ToString() });
}
}
}
``` |
92,698 | <p>I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function.</p>
<p>In SQL Server you could do something like:</p>
<p><strong>Person</strong></p>
<pre><code>John
Steve
Richard
</code></pre>
<p><strong>SQL</strong></p>
<pre><code>DECLARE @PersonList nvarchar(1024)
SELECT @PersonList = COALESCE(@PersonList + ',','') + Person
FROM PersonTable
PRINT @PersonList
</code></pre>
<p>Which produces: John, Steve, Richard</p>
<p>I want to do the same but in Access 2007.</p>
<p>Does anyone know how to combine rows like this in Access 2007?</p>
| [
{
"answer_id": 92878,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 0,
"selected": false,
"text": "<p>I think Nz is what you're after, syntax is <code>Nz(variant, [if null value])</code>. Here's the documentation link: <a href=\"http://office.microsoft.com/en-us/access/HA012288901033.aspx\" rel=\"nofollow noreferrer\">Nz Function</a></p>\n\n<pre><code>---Person--- \nJohn\nSteve\nRichard\n\nDECLARE @PersonList nvarchar(1024)\nSELECT @PersonList = Nz(@PersonList + ',','') + Person\nFROM PersonTable\n\nPRINT @PersonList\n</code></pre>\n"
},
{
"answer_id": 93133,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 0,
"selected": false,
"text": "<p>Although Nz does a comparable thing to COALESCE, you can't use it in Access to do the operation you are performing. It's not the COALESCE that is building the list of row values, it's the concatenatiion into a variable. </p>\n\n<p>Unfortunately, this isn't possible inside an Access query which has to be a single SQL statement and where there is no facility to declare a variable. </p>\n\n<p>I think you would need to create a function that would open a resultset, iterate over it and concatenate the row values into a string. </p>\n"
},
{
"answer_id": 93332,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>To combine rows in Access, you'll probably need code that looks something like this:</p>\n\n<pre><code>Public Function Coalesce(pstrTableName As String, pstrFieldName As String)\n\nDim rst As DAO.Recordset\nDim str As String\n\n Set rst = CurrentDb.OpenRecordset(pstrTableName)\n Do While rst.EOF = False\n If Len(str) = 0 Then\n str = rst(pstrFieldName)\n Else\n str = str & \",\" & rst(pstrFieldName)\n End If\n rst.MoveNext\n Loop\n\n Coalesce = str\n\nEnd Function\n</code></pre>\n\n<p>You'll want to add error-handling code and clean up your recordset, and this will change slightly if you use ADO instead of DAO, but the general idea is the same. </p>\n"
},
{
"answer_id": 93370,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "<p>I understand here that you have a table \"person\" with 3 records. There is nothing comparable to what you describe in Access. </p>\n\n<p>In \"standard\" Access (DAO recordset), you will have to open a recordset and use the getrows method to have your data</p>\n\n<pre><code>Dim rs as DAO.recordset, _\n personList as String, _\n personArray() as variant\n\nset rs = currentDb.open(\"Person\")\nset personArray = rs.getRows(rs.recordcount)\n\nrs.close\n</code></pre>\n\n<p>once you have this array (it will be bidimensional), you can manipulate it to extract the \"column\" you'll need. There might be a smart way to extract a one-dimension array from this, so you can then use the \"Join\" instruction to concatenate each array value in one string.</p>\n"
},
{
"answer_id": 93863,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 5,
"selected": true,
"text": "<p>Here is a sample User Defined Function (UDF) and possible usage.</p>\n\n<p>Function:</p>\n\n<pre><code>Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant)\nDim db As Database\nDim rs As DAO.Recordset\nDim strList As String\n\n Set db = CurrentDb\n\n If strSQL <> \"\" Then\n Set rs = db.OpenRecordset(strSQL)\n\n Do While Not rs.EOF\n strList = strList & strDelim & rs.Fields(0)\n rs.MoveNext\n Loop\n\n strList = Mid(strList, Len(strDelim))\n Else\n\n strList = Join(NameList, strDelim)\n End If\n\n Coalsce = strList\n\nEnd Function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>SELECT documents.MembersOnly, \n Coalsce(\"SELECT FName From Persons WHERE Member=True\",\":\") AS Who, \n Coalsce(\"\",\":\",\"Mary\",\"Joe\",\"Pat?\") AS Others\nFROM documents;\n</code></pre>\n\n<p>An ADO version, inspired by a comment by onedaywhen</p>\n\n<pre><code>Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant)\n Dim rs As New ADODB.Recordset\n Dim strList As String\n\n On Error GoTo Proc_Err\n\n If strSQL <> \"\" Then\n rs.Open strSQL, CurrentProject.Connection\n strList = rs.GetString(, , strColDelim, strRowDelim)\n strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))\n Else\n strList = Join(NameList, strColDelim)\n End If\n\n ConcatADO = strList\n\n Exit Function\n\n Proc_Err:\n ConcatADO = \"***\" & UCase(Err.Description)\n End Function\n</code></pre>\n\n<p>From: <a href=\"http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29\" rel=\"noreferrer\">http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
]
| I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function.
In SQL Server you could do something like:
**Person**
```
John
Steve
Richard
```
**SQL**
```
DECLARE @PersonList nvarchar(1024)
SELECT @PersonList = COALESCE(@PersonList + ',','') + Person
FROM PersonTable
PRINT @PersonList
```
Which produces: John, Steve, Richard
I want to do the same but in Access 2007.
Does anyone know how to combine rows like this in Access 2007? | Here is a sample User Defined Function (UDF) and possible usage.
Function:
```
Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant)
Dim db As Database
Dim rs As DAO.Recordset
Dim strList As String
Set db = CurrentDb
If strSQL <> "" Then
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
strList = strList & strDelim & rs.Fields(0)
rs.MoveNext
Loop
strList = Mid(strList, Len(strDelim))
Else
strList = Join(NameList, strDelim)
End If
Coalsce = strList
End Function
```
Usage:
```
SELECT documents.MembersOnly,
Coalsce("SELECT FName From Persons WHERE Member=True",":") AS Who,
Coalsce("",":","Mary","Joe","Pat?") AS Others
FROM documents;
```
An ADO version, inspired by a comment by onedaywhen
```
Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant)
Dim rs As New ADODB.Recordset
Dim strList As String
On Error GoTo Proc_Err
If strSQL <> "" Then
rs.Open strSQL, CurrentProject.Connection
strList = rs.GetString(, , strColDelim, strRowDelim)
strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))
Else
strList = Join(NameList, strColDelim)
End If
ConcatADO = strList
Exit Function
Proc_Err:
ConcatADO = "***" & UCase(Err.Description)
End Function
```
From: <http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29> |
92,699 | <p>I have a table called OffDays, where weekends and holiday dates are kept. I have a table called LeadTime where amount of time (in days) for a product to be manufactured is stored. Finally I have a table called Order where a product and the order date is kept.</p>
<p>Is it possible to query when a product will be finished manufacturing without using stored procedures or loops?</p>
<p>For example:</p>
<ul>
<li>OffDays has 2008-01-10, 2008-01-11, 2008-01-14.</li>
<li>LeadTime has 5 for product 9.</li>
<li>Order has 2008-01-09 for product 9.</li>
</ul>
<p>The calculation I'm looking for is this:</p>
<ul>
<li>2008-01-09 1</li>
<li>2008-01-10 x</li>
<li>2008-01-11 x</li>
<li>2008-01-12 2</li>
<li>2008-01-13 3</li>
<li>2008-01-14 x</li>
<li>2008-01-15 4</li>
<li>2008-01-16 5</li>
</ul>
<p>I'm wondering if it's possible to have a query return 2008-01-16 without having to use a stored procedure, or calculate it in my application code.</p>
<p><strong>Edit (why no stored procs / loops):</strong>
The reason I can't use stored procedures is that they are not supported by the database. I can only add extra tables / data. The application is a third party reporting tool where I can only control the SQL query.</p>
<p><strong>Edit (how i'm doing it now):</strong>
My current method is that I have an extra column in the order table to hold the calculated date, then a scheduled task / cron job runs the calculation on all the orders every hour. This is less than ideal for several reasons.</p>
| [
{
"answer_id": 92722,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": 1,
"selected": false,
"text": "<p>Just calculate it in application code ... much easier and you won't have to write a really ugly query in your sql</p>\n"
},
{
"answer_id": 92736,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 2,
"selected": false,
"text": "<p>The best approach is to use a Calendar table. </p>\n\n<p>See <a href=\"http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html</a>.</p>\n\n<p>Then your query could look something like:</p>\n\n<pre><code>SELECT c.dt, l.*, o.*, c.*\n FROM [statistics].dbo.[calendar] c, \n [order] o JOIN\n lead l ON l.leadId = o.leadId\n WHERE c.isWeekday = 1 \n AND c.isHoliday =0 \n AND o.orderId = 1\n AND l.leadDays = ( \n SELECT COUNT(*) \n FROM [statistics].dbo.Calendar c2 \n WHERE c2.dt >= o.startDate\n AND c2.dt <= c.dt \n AND c2.isWeekday=1 \n AND c2.isHoliday=0 \n )\n</code></pre>\n\n<p>Hope that helps,</p>\n\n<p>RB.</p>\n"
},
{
"answer_id": 92783,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 0,
"selected": false,
"text": "<p>Why are you against using loops?</p>\n\n<p>//some pseudocode</p>\n\n<pre><code>int leadtime = 5;\ndate order = 2008-01-09;\ndate finishdate = order;\nwhile (leadtime > 0) {\nfinishdate.addDay();\nif (!IsOffday(finishdate)) leadtime--;\n}\nreturn finishdate;</code></pre>\n\n<p>this seems like a too simple function to try to find a non-looping way.</p>\n"
},
{
"answer_id": 92815,
"author": "Russell Leggett",
"author_id": 2828,
"author_profile": "https://Stackoverflow.com/users/2828",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm.. one solution could be to store a table of dates with an offset based on a count of non-off days from the beginning of the year. Lets say jan. 2 is an off day. 1/1/08 would have an offset of 1 (or 0 if you like to start from 0). 1/3/08 would have an offset of 2, because the count skips 1/2/08. From there its a simple calculation. Get the offset of the order date, add the lead time, then do a lookup on the calculated offset to get the end date.</p>\n"
},
{
"answer_id": 92822,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": true,
"text": "<p>You can generate a table of working days in advance.</p>\n\n<pre><code>WDId | WDDate\n-----+-----------\n4200 | 2008-01-08\n4201 | 2008-01-09\n4202 | 2008-01-12\n4203 | 2008-01-13\n4204 | 2008-01-16\n4205 | 2008-01-17\n</code></pre>\n\n<p>Then do a query such as</p>\n\n<pre><code>SELECT DeliveryDay.WDDate FROM WorkingDay OrderDay, WorkingDay DeliveryDay, LeadTime, Order where DeliveryDay.WDId = OrderDay.WDId + LeadTime.LTDays AND OrderDay.WDDate = '' AND LeadTime.ProductId = Order.ProductId AND Order.OrderId = 1234\n</code></pre>\n\n<p>You would need a stored procedure with a loop to generate the WorkingDays table, but not for regular queries. It's also fewer round trips to the server than if you use application code to count the days.</p>\n"
},
{
"answer_id": 93175,
"author": "kamajo",
"author_id": 5415,
"author_profile": "https://Stackoverflow.com/users/5415",
"pm_score": 1,
"selected": false,
"text": "<p>here's one way - using the dateadd function. </p>\n\n<p>I need to take this answer off the table. This isn't going to work properly for long lead times. It was simply adding the # of off days found in the lead time and pushing the date out. This will cause a problem when more off days show up in the new range. </p>\n\n<pre><code>-- Setup test\ncreate table #odays (offd datetime)\ncreate table #leadtime (pid int , ltime int)\ncreate table [#order] (pid int, odate datetime)\n\n\ninsert into #odays \nselect '1/10/8'\ninsert into #odays \nselect '1/11/8'\ninsert into #odays \nselect '1/14/8'\n\n\ninsert into #Leadtime\nvalues (3,5)\ninsert into #leadtime\nvalues (9, 5)\n\ninsert into #order \nvalues( 9, '1/9/8')\n\nselect dateadd(dd, \n(select count(*)-1 \n from #odays \n where offd between odate and \n (select odate+ltime \n from #order o \n left join #leadtime l \n on o.pid = l.pid \n where l.pid = 9\n )\n ),\n odate+ltime) \n from #order o \n left join #leadtime l \n on o.pid = l.pid \n where o.pid = 9\n</code></pre>\n"
},
{
"answer_id": 93249,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 0,
"selected": false,
"text": "<p>One way (without creating another table) is using a sort of ceiling function: for each offdate, find out how many \"on dates\" come before it, relative to the order date, in a subquery. Then take the highest number that's less than the lead time. Use the date corresponding to that, plus the remainder.</p>\n\n<p>This code may be specific to PostgreSQL, sorry if that's not what you're using.</p>\n\n<pre><code>CREATE DATABASE test;\nCREATE TABLE offdays\n(\n offdate date NOT NULL,\n CONSTRAINT offdays_pkey PRIMARY KEY (offdate)\n);\ninsert into offdays (offdate) values ('2008-01-10');\ninsert into offdays (offdate) values ('2008-01-11');\ninsert into offdays (offdate) values ('2008-01-14');\ninsert into offdays (offdate) values ('2008-01-18'); -- just for testing\nCREATE TABLE product\n(\n id integer NOT NULL,\n CONSTRAINT product_pkey PRIMARY KEY (id)\n);\ninsert into product (id) values (9);\nCREATE TABLE leadtime\n(\n product integer NOT NULL,\n leaddays integer NOT NULL,\n CONSTRAINT leadtime_pkey PRIMARY KEY (product),\n CONSTRAINT leadtime_product_fkey FOREIGN KEY (product)\n REFERENCES product (id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into leadtime (product, leaddays) values (9, 5);\nCREATE TABLE \"order\"\n(\n product integer NOT NULL,\n \"start\" date NOT NULL,\n CONSTRAINT order_pkey PRIMARY KEY (product),\n CONSTRAINT order_product_fkey FOREIGN KEY (product)\n REFERENCES product (id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into \"order\" (product, \"start\") values (9, '2008-01-09');\n\n-- finally, the query:\n\nselect e.product, offdate + (leaddays - ondays)::integer as \"end\"\nfrom\n(\n select c.product, offdate, (select (a.offdate - c.\"start\") - count(b.offdate) from offdays b where b.offdate < a.offdate) as ondays, d.leaddays\n from offdays a, \"order\" c\n inner join leadtime d on d.product = c.product\n) e\nwhere leaddays >= ondays\norder by \"end\" desc\nlimit 1;\n</code></pre>\n"
},
{
"answer_id": 95268,
"author": "user17957",
"author_id": 17957,
"author_profile": "https://Stackoverflow.com/users/17957",
"pm_score": 0,
"selected": false,
"text": "<p>This is PostgreSQL syntax but it should be easy to translate to other SQL dialect</p>\n\n<pre><code>--Sample data\ncreate table offdays(datum date);\n\ninsert into offdays(datum)\nselect to_date('2008-01-10','yyyy-MM-dd') UNION \nselect to_date('2008-01-11','yyyy-MM-dd') UNION \nselect to_date('2008-01-14','yyyy-MM-dd') UNION \nselect to_date('2008-01-20','yyyy-MM-dd') UNION\nselect to_date('2008-01-21','yyyy-MM-dd') UNION\nselect to_date('2008-01-26','yyyy-MM-dd');\n\ncreate table leadtime (product_id integer , lead_time integer);\ninsert into leadtime(product_id,lead_time) values (9,5);\n\ncreate table myorder (order_id integer,product_id integer, datum date);\ninsert into myorder(order_id,product_id,datum) \nvalues (1,9,to_date('2008-01-09','yyyy-MM-dd'));\ninsert into myorder(order_id,product_id,datum) \nvalues (2,9,to_date('2008-01-16','yyyy-MM-dd'));\ninsert into myorder(order_id,product_id,datum) \nvalues (3,9,to_date('2008-01-23','yyyy-MM-dd'));\n\n--Query\nselect order_id,min(finished_date)\nFROM \n (select mo.order_id,(mo.datum+lead_time+count(od2.*)::integer-1) as finished_date\n from \n myorder mo\n join leadtime lt on (mo.product_id=lt.product_id)\n join offdays od1 on (mo.datum<od1.datum)\n left outer join offdays od2 on (mo.datum<od2.datum and od2.datum<od1.datum)\n group by mo.order_id,mo.datum,lt.lead_time,od1.datum\n having (mo.datum+lead_time+count(od2.*)::integer-1) < od1.datum) tmp\ngroup by 1; \n\n--Results :\n1 2008.01.16\n2 2008.01.22\n</code></pre>\n\n<p>This will <strong>not return</strong> result for orders that would be finished after last date in offdays table (order number 3), so you must take care to insert offdays on time.It is assumed that orders do not start on offdays.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
]
| I have a table called OffDays, where weekends and holiday dates are kept. I have a table called LeadTime where amount of time (in days) for a product to be manufactured is stored. Finally I have a table called Order where a product and the order date is kept.
Is it possible to query when a product will be finished manufacturing without using stored procedures or loops?
For example:
* OffDays has 2008-01-10, 2008-01-11, 2008-01-14.
* LeadTime has 5 for product 9.
* Order has 2008-01-09 for product 9.
The calculation I'm looking for is this:
* 2008-01-09 1
* 2008-01-10 x
* 2008-01-11 x
* 2008-01-12 2
* 2008-01-13 3
* 2008-01-14 x
* 2008-01-15 4
* 2008-01-16 5
I'm wondering if it's possible to have a query return 2008-01-16 without having to use a stored procedure, or calculate it in my application code.
**Edit (why no stored procs / loops):**
The reason I can't use stored procedures is that they are not supported by the database. I can only add extra tables / data. The application is a third party reporting tool where I can only control the SQL query.
**Edit (how i'm doing it now):**
My current method is that I have an extra column in the order table to hold the calculated date, then a scheduled task / cron job runs the calculation on all the orders every hour. This is less than ideal for several reasons. | You can generate a table of working days in advance.
```
WDId | WDDate
-----+-----------
4200 | 2008-01-08
4201 | 2008-01-09
4202 | 2008-01-12
4203 | 2008-01-13
4204 | 2008-01-16
4205 | 2008-01-17
```
Then do a query such as
```
SELECT DeliveryDay.WDDate FROM WorkingDay OrderDay, WorkingDay DeliveryDay, LeadTime, Order where DeliveryDay.WDId = OrderDay.WDId + LeadTime.LTDays AND OrderDay.WDDate = '' AND LeadTime.ProductId = Order.ProductId AND Order.OrderId = 1234
```
You would need a stored procedure with a loop to generate the WorkingDays table, but not for regular queries. It's also fewer round trips to the server than if you use application code to count the days. |
92,720 | <p>I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.</p>
<p>How do I use jQuery to get the set of images, filter it to broken images then replace the src?</p>
<hr/>
<p>--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.</p>
| [
{
"answer_id": 92819,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 11,
"selected": true,
"text": "<p>Handle the <code>onError</code> event for the image to reassign its source using JavaScript:</p>\n\n<pre><code>function imgError(image) {\n image.onerror = \"\";\n image.src = \"/images/noimage.gif\";\n return true;\n}\n</code></pre>\n\n\n\n<pre><code><img src=\"image.png\" onerror=\"imgError(this);\"/>\n</code></pre>\n\n<p>Or without a JavaScript function:</p>\n\n<pre><code><img src=\"image.png\" onError=\"this.onerror=null;this.src='/images/noimage.gif';\" />\n</code></pre>\n\n<p>The following compatibility table lists the browsers that support the error facility:</p>\n\n<p><a href=\"http://www.quirksmode.org/dom/events/error.html\" rel=\"noreferrer\">http://www.quirksmode.org/dom/events/error.html</a></p>\n"
},
{
"answer_id": 92829,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 5,
"selected": false,
"text": "<p>I believe this is what you're after: <a href=\"http://flesler.blogspot.com/2008/01/jquerypreload.html\" rel=\"nofollow noreferrer\">jQuery.Preload</a></p>\n<p>Here's the example code from the demo, you specify the loading and not found images and you're all set:</p>\n<pre><code>jQuery('#images img').preload({\n placeholder:'placeholder.jpg',\n notFound:'notfound.jpg'\n});\n</code></pre>\n"
},
{
"answer_id": 92830,
"author": "Chii",
"author_id": 17335,
"author_profile": "https://Stackoverflow.com/users/17335",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure if there is a better way, but I can think of a hack to get it - you could Ajax post to the img URL, and parse the response to see if the image actually came back. If it came back as a 404 or something, then swap out the img. Though I expect this to be quite slow.</p>\n"
},
{
"answer_id": 93017,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a standalone solution:</p>\n<pre><code>$(window).load(function() {\n $('img').each(function() {\n if ( !this.complete\n || typeof this.naturalWidth == "undefined"\n || this.naturalWidth == 0 ) {\n // image was broken, replace with your new image\n this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 168448,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 8,
"selected": false,
"text": "<p>I use the built in <code>error</code> handler:</p>\n\n<pre><code>$(\"img\").error(function () {\n $(this).unbind(\"error\").attr(\"src\", \"broken.gif\");\n});\n</code></pre>\n\n<p><strong>Edit:</strong> The <code>error()</code> method is deprecated in <a href=\"https://api.jquery.com/error/\" rel=\"noreferrer\">jquery 1.8</a> and higher. Instead, you should use <code>.on(\"error\")</code> instead:</p>\n\n<pre><code>$(\"img\").on(\"error\", function () {\n $(this).attr(\"src\", \"broken.gif\");\n});\n</code></pre>\n"
},
{
"answer_id": 2520294,
"author": "Mohamad",
"author_id": 302184,
"author_profile": "https://Stackoverflow.com/users/302184",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$(window).bind('load', function() {\n $('img').each(function() {\n if( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) \n || this.readyState == 'uninitialized' ) {\n $(this).attr('src', 'missing.jpg');\n }\n });\n});\n</code></pre>\n<p>Source: <a href=\"http://www.developria.com/2009/03/jquery-quickie---broken-images.html\" rel=\"nofollow noreferrer\">http://www.developria.com/2009/03/jquery-quickie---broken-images.html</a></p>\n"
},
{
"answer_id": 8575302,
"author": "Shade",
"author_id": 1107804,
"author_profile": "https://Stackoverflow.com/users/1107804",
"pm_score": 3,
"selected": false,
"text": "<p>I couldn't find a script to suit my needs, so I made a recursive function to check for broken images and attempt to reload them every four seconds until they are fixed.</p>\n\n<p>I limited it to 10 attempts as if it's not loaded by then the image might not be present on server and the function would enter an infinite loop. I am still testing though. Feel free to tweak it :)</p>\n\n<pre><code>var retries = 0;\n$.imgReload = function() {\n var loaded = 1;\n\n $(\"img\").each(function() {\n if (!this.complete || typeof this.naturalWidth == \"undefined\" || this.naturalWidth == 0) {\n\n var src = $(this).attr(\"src\");\n var date = new Date();\n $(this).attr(\"src\", src + \"?v=\" + date.getTime()); //slightly change url to prevent loading from cache\n loaded =0;\n }\n });\n\n retries +=1;\n if (retries < 10) { // If after 10 retries error images are not fixed maybe because they\n // are not present on server, the recursion will break the loop\n if (loaded == 0) {\n setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server\n }\n // All images have been loaded\n else {\n // alert(\"images loaded\");\n }\n }\n // If error images cannot be loaded after 10 retries\n else {\n // alert(\"recursion exceeded\");\n }\n}\n\njQuery(document).ready(function() {\n setTimeout('$.imgReload()',5000);\n});\n</code></pre>\n"
},
{
"answer_id": 8621397,
"author": "Shade",
"author_id": 1114091,
"author_profile": "https://Stackoverflow.com/users/1114091",
"pm_score": 2,
"selected": false,
"text": "<p>Better call using</p>\n\n<pre><code>jQuery(window).load(function(){\n $.imgReload();\n});\n</code></pre>\n\n<p>Because using <code>document.ready</code> doesn't necessary imply that images are loaded, only the HTML. Thus, there is no need for a delayed call.</p>\n"
},
{
"answer_id": 11052002,
"author": "mouad",
"author_id": 479633,
"author_profile": "https://Stackoverflow.com/users/479633",
"pm_score": 7,
"selected": false,
"text": "<p>In case someone like me, tries to attach the <code>error</code> event to a dynamic HTML <code>img</code> tag, I'd like to point out that, there is a catch: </p>\n\n<p>Apparently <code>img</code> error events <strong><a href=\"http://forum.jquery.com/topic/error-event-with-live\" rel=\"noreferrer\">don't bubble</a></strong> in most browsers, contrary to what the <a href=\"http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents\" rel=\"noreferrer\">standard</a> says.</p>\n\n<p>So, something like the following will <strong>not work</strong>:</p>\n\n<pre><code>$(document).on('error', 'img', function () { ... })\n</code></pre>\n\n<p>Hope this will be helpful to someone else. I wish I had seen this here in this thread. But, I didn't. So, I am adding it </p>\n"
},
{
"answer_id": 17352656,
"author": "yckart",
"author_id": 1250044,
"author_profile": "https://Stackoverflow.com/users/1250044",
"pm_score": 2,
"selected": false,
"text": "<pre><code>(window.jQuery || window.Zepto).fn.fallback = function (fallback) {\n return this.one('error', function () {\n var self = this;\n this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(\n /\\$(\\w+)/g, function (m, t) { return self[t] || ''; }\n );\n });\n};\n \n</code></pre>\n<p>You can pass a placeholder path and acces in it all properties from the failed image object via <code>$*</code>:</p>\n<pre><code>$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');\n</code></pre>\n<p><a href=\"http://jsfiddle.net/ARTsinn/Cu4Zn/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/ARTsinn/Cu4Zn/</a></p>\n"
},
{
"answer_id": 17730147,
"author": "Kevin",
"author_id": 375960,
"author_profile": "https://Stackoverflow.com/users/375960",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/CoffeeScript\" rel=\"nofollow\">CoffeeScript</a> variant:</p>\n\n<p>I made it to fix an issue with Turbolinks that causes the .error() method to get raised in Firefox sometimes even though the image is really there.</p>\n\n<pre><code>$(\"img\").error ->\n e = $(@).get 0\n $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == \"undefined\" || this.naturalWidth == 0)\n</code></pre>\n"
},
{
"answer_id": 19492959,
"author": "Luis Gustavo Beligante",
"author_id": 2902842,
"author_profile": "https://Stackoverflow.com/users/2902842",
"pm_score": 2,
"selected": false,
"text": "<p>I solved my problem with these two simple functions:</p>\n\n<pre><code>function imgExists(imgPath) {\n var http = jQuery.ajax({\n type:\"HEAD\",\n url: imgPath,\n async: false\n });\n return http.status != 404;\n}\n\nfunction handleImageError() {\n var imgPath;\n\n $('img').each(function() {\n imgPath = $(this).attr('src');\n if (!imgExists(imgPath)) {\n $(this).attr('src', 'images/noimage.jpg');\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 21858938,
"author": "Ashfaque Ali Solangi",
"author_id": 820059,
"author_profile": "https://Stackoverflow.com/users/820059",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a quick-and-dirty way to replace all the broken images, and there is no need to change the HTML code ;)</p>\n\n<p><a href=\"https://codepen.io/ASHFAQAHMED/pen/RYxyjm\" rel=\"nofollow noreferrer\">codepen example</a></p>\n\n<pre><code> $(\"img\").each(function(){\n var img = $(this);\n var image = new Image();\n image.src = $(img).attr(\"src\");\n var no_image = \"https://dummyimage.com/100x100/7080b5/000000&text=No+image\";\n if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){\n $(img).unbind(\"error\").attr(\"src\", no_image).css({\n height: $(img).css(\"height\"),\n width: $(img).css(\"width\"),\n });\n }\n });\n</code></pre>\n"
},
{
"answer_id": 23014637,
"author": "Phil LaNasa",
"author_id": 2374900,
"author_profile": "https://Stackoverflow.com/users/2374900",
"pm_score": 4,
"selected": false,
"text": "<p>This is a crappy technique, but it's pretty much guaranteed:</p>\n<pre><code><img onerror="this.parentNode.removeChild(this);">\n</code></pre>\n"
},
{
"answer_id": 23297041,
"author": "Dylan Valade",
"author_id": 638452,
"author_profile": "https://Stackoverflow.com/users/638452",
"pm_score": 3,
"selected": false,
"text": "<p>This has been frustrating me for years. My CSS fix sets a background image on the <code>img</code>. When a dynamic image <code>src</code> doesn't load to the foreground, a placeholder is visible on the <code>img</code>'s bg. This works if your images have a default size (e.g. <code>height</code>, <code>min-height</code>, <code>width</code> and/or <code>min-width</code>).</p>\n<p>You'll see the broken image icon but it's an improvement. Tested down to IE9 successfully. iOS Safari and Chrome don't even show a broken icon.</p>\n<pre><code>.dynamicContainer img {\n background: url('/images/placeholder.png');\n background-size: contain;\n}\n</code></pre>\n<p>Add a little animation to give <code>src</code> time to load without a background flicker. Chrome fades in the background smoothly but desktop Safari doesn't.</p>\n<pre><code>.dynamicContainer img {\n background: url('/images/placeholder.png');\n background-size: contain;\n animation: fadein 1s; \n}\n\n@keyframes fadein {\n 0% { opacity: 0.0; }\n 50% { opacity: 0.5; }\n 100% { opacity: 1.0; }\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.dynamicContainer img {\n background: url('https://picsum.photos/id/237/200');\n background-size: contain;\n animation: fadein 1s;\n}\n\n@keyframes fadein {\n 0% {\n opacity: 0.0;\n }\n 50% {\n opacity: 0.5;\n }\n 100% {\n opacity: 1.0;\n }\n}\n\nimg {\n /* must define dimensions */\n width: 200px;\n height: 200px;\n min-width: 200px;\n min-height: 200px;\n /* hides broken text */\n color: transparent;\n /* optional css below here */\n display: block;\n border: .2em solid black;\n border-radius: 1em;\n margin: 1em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"dynamicContainer\">\n <img src=\"https://picsum.photos/200\" alt=\"Found image\" />\n <img src=\"https://picsumx.photos/200\" alt=\"Not found image\" />\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 24475191,
"author": "trante",
"author_id": 429938,
"author_profile": "https://Stackoverflow.com/users/429938",
"pm_score": 2,
"selected": false,
"text": "<p>By using <a href=\"https://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images/92819#92819\">Prestaul's answer</a>, I added some checks and I prefer to use the jQuery way.</p>\n\n<pre><code><img src=\"image1.png\" onerror=\"imgError(this,1);\"/>\n<img src=\"image2.png\" onerror=\"imgError(this,2);\"/>\n\nfunction imgError(image, type) {\n if (typeof jQuery !== 'undefined') {\n var imgWidth=$(image).attr(\"width\");\n var imgHeight=$(image).attr(\"height\");\n\n // Type 1 puts a placeholder image\n // Type 2 hides img tag\n if (type == 1) {\n if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {\n $(image).attr(\"src\", \"http://lorempixel.com/\" + imgWidth + \"/\" + imgHeight + \"/\");\n } else {\n $(image).attr(\"src\", \"http://lorempixel.com/200/200/\");\n }\n } else if (type == 2) {\n $(image).hide();\n }\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 25377280,
"author": "Axel",
"author_id": 3931192,
"author_profile": "https://Stackoverflow.com/users/3931192",
"pm_score": 3,
"selected": false,
"text": "<p>This is JavaScript, should be cross browser compatible, and delivers without the ugly markup <code>onerror=\"\"</code>:</p>\n\n<pre><code>var sPathToDefaultImg = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',\n validateImage = function( domImg ) {\n oImg = new Image();\n oImg.onerror = function() {\n domImg.src = sPathToDefaultImg;\n };\n oImg.src = domImg.src;\n },\n aImg = document.getElementsByTagName( 'IMG' ),\n i = aImg.length;\n\nwhile ( i-- ) {\n validateImage( aImg[i] );\n}\n</code></pre>\n\n<p><a href=\"http://codepen.io/elstermann/pen/giEvC?editors=001\" rel=\"nofollow noreferrer\">CODEPEN: </a></p>\n"
},
{
"answer_id": 26886941,
"author": "horro",
"author_id": 2856041,
"author_profile": "https://Stackoverflow.com/users/2856041",
"pm_score": 3,
"selected": false,
"text": "<p>If you have inserted your <code>img</code> with <code>innerHTML</code>, like: <code>$(\"div\").innerHTML = <img src=\"wrong-uri\"></code>, you can load another image if it fails doing, e.g, this:</p>\n\n<pre><code><script>\n function imgError(img) {\n img.error=\"\";\n img.src=\"valid-uri\";\n }\n</script>\n\n<img src=\"wrong-uri\" onerror=\"javascript:imgError(this)\">\n</code></pre>\n\n<p>Why is <code>javascript: _</code>needed? Because scripts injected into the DOM via script tags in <code>innerHTML</code> are not run at the time they are injected, so you have to be explicit.</p>\n"
},
{
"answer_id": 36990598,
"author": "Barry",
"author_id": 4513271,
"author_profile": "https://Stackoverflow.com/users/4513271",
"pm_score": 3,
"selected": false,
"text": "<p>You can use GitHub's own fetch for this:</p>\n\n<p>Frontend: <a href=\"https://github.com/github/fetch\" rel=\"noreferrer\">https://github.com/github/fetch</a><br>\nor for Backend, a Node.js version: <a href=\"https://github.com/bitinn/node-fetch\" rel=\"noreferrer\">https://github.com/bitinn/node-fetch</a></p>\n\n<pre><code>fetch(url)\n .then(function(res) {\n if (res.status == '200') {\n return image;\n } else {\n return placeholder;\n }\n }\n</code></pre>\n\n<p>Edit: This method is going to replace XHR and supposedly already has been in Chrome. To anyone reading this in the future, you may not need the aforementioned library included.</p>\n"
},
{
"answer_id": 38359229,
"author": "Jordan Bonitatis",
"author_id": 2860951,
"author_profile": "https://Stackoverflow.com/users/2860951",
"pm_score": 2,
"selected": false,
"text": "<p>I found this post while looking at <a href=\"https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript\">this other SO post</a>. Below is a copy of the answer I gave there.</p>\n\n<p>I know this is an old thread, but React has become popular and, perhaps, someone using React will come here looking for an answer to the same problem.</p>\n\n<p>So, if you are using React, you can do something like the below, which was an answer original provided by Ben Alpert of the React team <a href=\"https://discuss.reactjs.org/t/onerror-for-img-to-hide-images-with-error/2094\" rel=\"nofollow noreferrer\">here</a></p>\n\n<pre><code>getInitialState: function(event) {\n return {image: \"http://example.com/primary_image.jpg\"};\n},\nhandleError: function(event) {\n this.setState({image: \"http://example.com/failover_image.jpg\"});\n},\nrender: function() {\n return (\n <img onError={this.handleError} src={src} />;\n );\n}\n</code></pre>\n"
},
{
"answer_id": 39272741,
"author": "Rohith K P",
"author_id": 3919057,
"author_profile": "https://Stackoverflow.com/users/3919057",
"pm_score": 2,
"selected": false,
"text": "<p>I created a <a href=\"https://jsfiddle.net/Rohith_KP/3mqecx69/6/\" rel=\"nofollow\">fiddle</a> to replace the broken image using \"onerror\" event.\nThis may help you. </p>\n\n<pre><code> //the placeholder image url\n var defaultUrl = \"url('https://sadasd/image02.png')\";\n\n $('div').each(function(index, item) {\n var currentUrl = $(item).css(\"background-image\").replace(/^url\\(['\"](.+)['\"]\\)/, '$1');\n $('<img>', {\n src: currentUrl\n }).on(\"error\", function(e) {\n $this = $(this);\n $this.css({\n \"background-image\": defaultUrl\n })\n e.target.remove()\n }.bind(this))\n })\n</code></pre>\n"
},
{
"answer_id": 40263918,
"author": "Nathan Arthur",
"author_id": 937377,
"author_profile": "https://Stackoverflow.com/users/937377",
"pm_score": 5,
"selected": false,
"text": "<p>While the OP was looking to replace the SRC, I'm sure many people hitting this question may only wish to hide the broken image, in which case <a href=\"https://stackoverflow.com/a/3675104/937377\">this simple solution</a> worked great for me.</p>\n<h1>Using Inline JavaScript:</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img src=\"img.jpg\" onerror=\"this.style.display='none';\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h1>Using External JavaScript:</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var images = document.querySelectorAll('img');\n\nfor (var i = 0; i < images.length; i++) {\n images[i].onerror = function() {\n this.style.display='none';\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img src='img.jpg' /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h1>Using Modern External JavaScript:</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelectorAll('img').forEach((img) => {\n img.onerror = function() {\n this.style.display = 'none';\n }\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img src='img.jpg' /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See browser support for <a href=\"https://caniuse.com/#feat=mdn-api_nodelist_foreach\" rel=\"noreferrer\">NodeList.forEach</a> and <a href=\"https://caniuse.com/#feat=arrow-functions\" rel=\"noreferrer\">arrow functions</a>.</p>\n"
},
{
"answer_id": 40427037,
"author": "Kurt Hartmann",
"author_id": 4805485,
"author_profile": "https://Stackoverflow.com/users/4805485",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example using the HTML5 Image object wrapped by JQuery. Call the load function for the primary image URL and if that load causes an error, replace the src attribute of the image with a backup URL.</p>\n\n<pre><code>function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {\n var $img = $('#' + imgId);\n $(new Image()).load().error(function() {\n $img.attr('src', backupUrl);\n }).attr('src', primaryUrl)\n}\n\n<img id=\"myImage\" src=\"primary-image-url\"/>\n<script>\n loadImageUseBackupUrlOnError('myImage','primary-image-url','backup-image-url');\n</script>\n</code></pre>\n"
},
{
"answer_id": 43281517,
"author": "Dima Dorogonov",
"author_id": 6082084,
"author_profile": "https://Stackoverflow.com/users/6082084",
"pm_score": 2,
"selected": false,
"text": "<p>Pure JS.\nMy task was: if image 'bl-once.png' is empty -> insert the first one (that hasn't 404 status) image from array list (in current dir):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img src=\"http://localhost:63342/GetImage/bl-once.png\" width=\"200\" onerror=\"replaceEmptyImage.insertImg(this)\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Maybe it needs to be improved, but:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array\r\n var path;\r\n var imgNotFounded = true; // to mark when success\r\n\r\n var replaceEmptyImage = {\r\n insertImg: function (elem) {\r\n\r\n if (srcToInsertArr.length == 0) { // if there are no more src to try return\r\n return \"no-image.png\";\r\n }\r\n if(!/undefined/.test(elem.src)) { // remember path\r\n path = elem.src.split(\"/\").slice(0, -1).join(\"/\"); // \"http://localhost:63342/GetImage\"\r\n }\r\n var url = path + \"/\" + srcToInsertArr[0];\r\n\r\n srcToInsertArr.splice(0, 1); // tried 1 src\r\n\r\n \r\n if(imgNotFounded){ // while not success\r\n replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE\r\n }\r\n \r\n\r\n },\r\n getImg: function (src, path, elem) { // GET IMAGE\r\n\r\n if (src && path && elem) { // src = \"http://localhost:63342/GetImage/needed.png\"\r\n \r\n var pathArr = src.split(\"/\"); // [\"http:\", \"\", \"localhost:63342\", \"GetImage\", \"needed.png\"]\r\n var name = pathArr[pathArr.length - 1]; // \"needed.png\"\r\n\r\n xhr = new XMLHttpRequest();\r\n xhr.open('GET', src, true);\r\n xhr.send();\r\n\r\n xhr.onreadystatechange = function () {\r\n\r\n if (xhr.status == 200) {\r\n elem.src = src; // insert correct src\r\n imgNotFounded = false; // mark success\r\n }\r\n else {\r\n console.log(name + \" doesn't exist!\");\r\n elem.onerror();\r\n }\r\n\r\n }\r\n }\r\n }\r\n\r\n };</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So, it will insert correct 'needed.png' to my src or 'no-image.png' from current dir.</p>\n"
},
{
"answer_id": 46010128,
"author": "Nabi K.A.Z.",
"author_id": 1407491,
"author_profile": "https://Stackoverflow.com/users/1407491",
"pm_score": 2,
"selected": false,
"text": "<p>jQuery 1.8</p>\n\n<pre><code>// If missing.png is missing, it is replaced by replacement.png\n$( \"img\" )\n .error(function() {\n $( this ).attr( \"src\", \"replacement.png\" );\n })\n .attr( \"src\", \"missing.png\" );\n</code></pre>\n\n<p>jQuery 3</p>\n\n<pre><code>// If missing.png is missing, it is replaced by replacement.png\n$( \"img\" )\n .on(\"error\", function() {\n $( this ).attr( \"src\", \"replacement.png\" );\n })\n .attr( \"src\", \"missing.png\" );\n</code></pre>\n\n<p><a href=\"https://api.jquery.com/error/\" rel=\"nofollow noreferrer\">reference</a></p>\n"
},
{
"answer_id": 47338718,
"author": "Dale Nguyen",
"author_id": 3103548,
"author_profile": "https://Stackoverflow.com/users/3103548",
"pm_score": 1,
"selected": false,
"text": "<p>I got the same problem. This code works well on my case. </p>\n\n<pre><code>// Replace broken images by a default img\n$('img').each(function(){\n if($(this).attr('src') === ''){\n this.src = '/default_feature_image.png';\n }\n});\n</code></pre>\n"
},
{
"answer_id": 48251382,
"author": "Lea Verou",
"author_id": 90826,
"author_profile": "https://Stackoverflow.com/users/90826",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes using the <code>error</code> event is not feasible, e.g. because you're trying to do something on a page that’s already loaded, such as when you’re running code via the console, a bookmarklet, or a script loaded asynchronously. In that case, checking that <code>img.naturalWidth</code> and <code>img.naturalHeight</code> are 0 seems to do the trick.</p>\n\n<p>For example, here's a snippet to reload all broken images from the console: </p>\n\n<pre><code>$$(\"img\").forEach(img => {\n if (!img.naturalWidth && !img.naturalHeight) {\n img.src = img.src;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48877973,
"author": "Casper",
"author_id": 3148642,
"author_profile": "https://Stackoverflow.com/users/3148642",
"pm_score": 2,
"selected": false,
"text": "<p>If the image cannot be loaded (for example, because it is not present at the supplied URL), image URL will be changed into default,</p>\n\n<p>For more about <a href=\"https://api.jquery.com/error/\" rel=\"nofollow noreferrer\">.error()</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('img').on('error', function (e) {\r\n $(this).attr('src', 'broken.png');\r\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50484874,
"author": "xianshenglu",
"author_id": 9147721,
"author_profile": "https://Stackoverflow.com/users/9147721",
"pm_score": 2,
"selected": false,
"text": "<p>I think I have a more elegant way with event delegation and event capturing on <code>window</code>'s <code>error</code> even when the backup image fail to load.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {\r\n width: 100px;\r\n height: 100px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script>\r\n window.addEventListener('error', windowErrorCb, {\r\n capture: true\r\n }, true)\r\n\r\n function windowErrorCb(event) {\r\n let target = event.target\r\n let isImg = target.tagName.toLowerCase() === 'img'\r\n if (isImg) {\r\n imgErrorCb()\r\n return\r\n }\r\n\r\n function imgErrorCb() {\r\n let isImgErrorHandled = target.hasAttribute('data-src-error')\r\n if (!isImgErrorHandled) {\r\n target.setAttribute('data-src-error', 'handled')\r\n target.src = 'backup.png'\r\n } else {\r\n //anything you want to do\r\n console.log(target.alt, 'both origin and backup image fail to load!');\r\n }\r\n }\r\n }\r\n</script>\r\n<img id=\"img\" src=\"error1.png\" alt=\"error1\">\r\n<img id=\"img\" src=\"error2.png\" alt=\"error2\">\r\n<img id=\"img\" src=\"https://i.stack.imgur.com/ZXCE2.jpg\" alt=\"avatar\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The point is :</p>\n\n<ol>\n<li><p>Put the code in the <code>head</code> and executed as the first inline script. So, it will listen the errors happen after the script.</p></li>\n<li><p>Use event capturing to catch the errors, especially for those events which don't bubble.</p></li>\n<li><p>Use event delegation which avoids binding events on each image.</p></li>\n<li><p>Give the error <code>img</code> element an attribute after giving them a <code>backup.png</code> to avoid disappearance of the <code>backup.png</code> and subsequent infinite loop like below:</p></li>\n</ol>\n\n<p><strong>img error->backup.png->error->backup.png->error->,,,,,</strong></p>\n"
},
{
"answer_id": 54471309,
"author": "buycanna.io",
"author_id": 345426,
"author_profile": "https://Stackoverflow.com/users/345426",
"pm_score": 0,
"selected": false,
"text": "<p>I found this to work best, if any image fails to load the first time, it is completely removed from the DOM. Executing <code>console.clear()</code> keeps the console window clean, since the 404 errors cannot be omitted with try/catch blocks. </p>\n\n<pre><code>$('img').one('error', function(err) {\n // console.log(JSON.stringify(err, null, 4))\n $(this).remove()\n console.clear()\n})\n</code></pre>\n"
},
{
"answer_id": 60654729,
"author": "ricardo_escovar",
"author_id": 1588802,
"author_profile": "https://Stackoverflow.com/users/1588802",
"pm_score": 1,
"selected": false,
"text": "<p>I use lazy load and have to do this in order to make it work properly:</p>\n\n<pre><code>lazyload();\n\nvar errorURL = \"https://example.com/thisimageexist.png\";\n\n$(document).ready(function () {\n $('[data-src]').on(\"error\", function () {\n $(this).attr('src', errorURL);\n });\n});\n</code></pre>\n"
},
{
"answer_id": 69400552,
"author": "Jawla",
"author_id": 5891662,
"author_profile": "https://Stackoverflow.com/users/5891662",
"pm_score": 2,
"selected": false,
"text": "<p><strong>For React Developers</strong>:</p>\n<pre><code><img \n src={"https://urlto/yourimage.png"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load\n width={200} \n alt={"Image"} \n onError={(event) => {\n event.target.onerror = "";\n event.target.src = "anyplaceholderimageUrlorPath"\n return true;\n }}\n />\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17702/"
]
| I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
---
--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul. | Handle the `onError` event for the image to reassign its source using JavaScript:
```
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
```
```
<img src="image.png" onerror="imgError(this);"/>
```
Or without a JavaScript function:
```
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
```
The following compatibility table lists the browsers that support the error facility:
<http://www.quirksmode.org/dom/events/error.html> |
92,781 | <p>I'm looking to have text display vertically, first letter at the bottom, last letter at the top, within a JLabel. Is this possible?</p>
| [
{
"answer_id": 92805,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it by messing with the paint command, sort of like this:</p>\n\n<pre><code>public class JVertLabel extends JComponent{\n private String text;\n\n public JVertLabel(String s){\n text = s;\n }\n\n public void paintComponent(Graphics g){\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D)g;\n\n g2d.rotate(Math.toRadians(270.0)); \n g2d.drawString(text, 0, 0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 92962,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 4,
"selected": true,
"text": "<p>I found this page: <a href=\"http://www.java2s.com/Tutorial/Java/0240__Swing/VerticalLabelUI.htm\" rel=\"noreferrer\">http://www.java2s.com/Tutorial/Java/0240__Swing/VerticalLabelUI.htm</a> when I needed to do that.</p>\n\n<p>I don't know if you want the letters 'standing' on each other or all rotated on their side.</p>\n\n<pre><code>/*\n * The contents of this file are subject to the Sapient Public License\n * Version 1.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * http://carbon.sf.net/License.html.\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for\n * the specific language governing rights and limitations under the License.\n *\n * The Original Code is The Carbon Component Framework.\n *\n * The Initial Developer of the Original Code is Sapient Corporation\n *\n * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.\n */\n\n\nimport java.awt.Dimension;\nimport java.awt.FontMetrics;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Insets;\nimport java.awt.Rectangle;\nimport java.awt.geom.AffineTransform;\n\nimport javax.swing.Icon;\nimport javax.swing.JComponent;\nimport javax.swing.JLabel;\nimport javax.swing.plaf.basic.BasicLabelUI;\n\n/**\n * This is the template for Classes.\n *\n *\n * @since carbon 1.0\n * @author Greg Hinkle, January 2002\n * @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:27 $)\n * @copyright 2002 Sapient\n */\n\npublic class VerticalLabelUI extends BasicLabelUI {\n static {\n labelUI = new VerticalLabelUI(false);\n }\n\n protected boolean clockwise;\n\n\n public VerticalLabelUI(boolean clockwise) {\n super();\n this.clockwise = clockwise;\n }\n\n\n public Dimension getPreferredSize(JComponent c) {\n Dimension dim = super.getPreferredSize(c);\n return new Dimension( dim.height, dim.width );\n }\n\n private static Rectangle paintIconR = new Rectangle();\n private static Rectangle paintTextR = new Rectangle();\n private static Rectangle paintViewR = new Rectangle();\n private static Insets paintViewInsets = new Insets(0, 0, 0, 0);\n\n public void paint(Graphics g, JComponent c) {\n\n JLabel label = (JLabel)c;\n String text = label.getText();\n Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();\n\n if ((icon == null) && (text == null)) {\n return;\n }\n\n FontMetrics fm = g.getFontMetrics();\n paintViewInsets = c.getInsets(paintViewInsets);\n\n paintViewR.x = paintViewInsets.left;\n paintViewR.y = paintViewInsets.top;\n\n // Use inverted height & width\n paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);\n paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);\n\n paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;\n paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;\n\n String clippedText =\n layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);\n\n Graphics2D g2 = (Graphics2D) g;\n AffineTransform tr = g2.getTransform();\n if (clockwise) {\n g2.rotate( Math.PI / 2 );\n g2.translate( 0, - c.getWidth() );\n } else {\n g2.rotate( - Math.PI / 2 );\n g2.translate( - c.getHeight(), 0 );\n }\n\n if (icon != null) {\n icon.paintIcon(c, g, paintIconR.x, paintIconR.y);\n }\n\n if (text != null) {\n int textX = paintTextR.x;\n int textY = paintTextR.y + fm.getAscent();\n\n if (label.isEnabled()) {\n paintEnabledText(label, g, clippedText, textX, textY);\n } else {\n paintDisabledText(label, g, clippedText, textX, textY);\n }\n }\n\n g2.setTransform( tr );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 116791,
"author": "ShawnD",
"author_id": 6186,
"author_profile": "https://Stackoverflow.com/users/6186",
"pm_score": 3,
"selected": false,
"text": "<p>Another way to show text in a JLabel vertically is to use HTML tags in the text of the JLabel. For example <code>setText(\"<HTML>H<br>E<br>L<br>L<br>O</HTML>\");</code> will set the text to\n<br>\nH<br>\nE<br>\nL<br>\nL<br>\nO<br></p>\n"
},
{
"answer_id": 32204257,
"author": "Bruno",
"author_id": 5264328,
"author_profile": "https://Stackoverflow.com/users/5264328",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the SwingX API</p>\n\n<p>Bottom to top :</p>\n\n<pre><code>JXLabel label = new JXLabel(\"MY TEXT\");\nlabel.setTextRotation(3 * Math.PI / 2);\n</code></pre>\n\n<p>Top to bottom :</p>\n\n<pre><code>JXLabel label = new JXLabel(\"MY TEXT\");\nlabel.setTextRotation(Math.PI / 2);\n</code></pre>\n"
},
{
"answer_id": 39345372,
"author": "Luke Usherwood",
"author_id": 932359,
"author_profile": "https://Stackoverflow.com/users/932359",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another solution that:</p>\n\n<ul>\n<li>Considers localisation</li>\n<li>Can draw characters either stacked vertically & centred, or rotated</li>\n</ul>\n\n<p><a href=\"http://www.macdevcenter.com/pub/a/mac/2002/03/22/vertical_text.html\" rel=\"nofollow\">http://www.macdevcenter.com/pub/a/mac/2002/03/22/vertical_text.html</a></p>\n\n<p>Highlighting a note in the Javadoc:</p>\n\n<blockquote>\n <p>Chinese/Japanese/Korean scripts have special rules when \n drawn vertically and should never be rotated</p>\n</blockquote>\n\n<p>See the article for some visual examples. </p>\n\n<p>Here's the main class <a href=\"http://www.macdevcenter.com/mac/2002/03/22/examples/VTextIcon.java\" rel=\"nofollow\">JTextIcon.java</a>, in case the article drops off the web:</p>\n\n<pre><code>/**\n VTextIcon is an Icon implementation which draws a short string vertically.\n It's useful for JTabbedPanes with LEFT or RIGHT tabs but can be used in any\n component which supports Icons, such as JLabel or JButton \n\n You can provide a hint to indicate whether to rotate the string \n to the left or right, or not at all, and it checks to make sure \n that the rotation is legal for the given string \n (for example, Chinese/Japanese/Korean scripts have special rules when \n drawn vertically and should never be rotated)\n */\npublic class VTextIcon implements Icon, PropertyChangeListener {\n String fLabel;\n String[] fCharStrings; // for efficiency, break the fLabel into one-char strings to be passed to drawString\n int[] fCharWidths; // Roman characters should be centered when not rotated (Japanese fonts are monospaced)\n int[] fPosition; // Japanese half-height characters need to be shifted when drawn vertically\n int fWidth, fHeight, fCharHeight, fDescent; // Cached for speed\n int fRotation;\n Component fComponent;\n\n static final int POSITION_NORMAL = 0;\n static final int POSITION_TOP_RIGHT = 1;\n static final int POSITION_FAR_TOP_RIGHT = 2;\n\n public static final int ROTATE_DEFAULT = 0x00;\n public static final int ROTATE_NONE = 0x01;\n public static final int ROTATE_LEFT = 0x02;\n public static final int ROTATE_RIGHT = 0x04;\n\n /**\n * Creates a <code>VTextIcon</code> for the specified <code>component</code>\n * with the specified <code>label</code>.\n * It sets the orientation to the default for the string\n * @see #verifyRotation\n */\n public VTextIcon(Component component, String label) {\n this(component, label, ROTATE_DEFAULT);\n }\n\n /**\n * Creates a <code>VTextIcon</code> for the specified <code>component</code>\n * with the specified <code>label</code>.\n * It sets the orientation to the provided value if it's legal for the string\n * @see #verifyRotation\n */\n public VTextIcon(Component component, String label, int rotateHint) {\n fComponent = component;\n fLabel = label;\n fRotation = verifyRotation(label, rotateHint);\n calcDimensions();\n fComponent.addPropertyChangeListener(this);\n }\n\n /**\n * sets the label to the given string, updating the orientation as needed\n * and invalidating the layout if the size changes\n * @see #verifyRotation\n */\n public void setLabel(String label) {\n fLabel = label;\n fRotation = verifyRotation(label, fRotation); // Make sure the current rotation is still legal\n recalcDimensions();\n }\n\n /**\n * Checks for changes to the font on the fComponent\n * so that it can invalidate the layout if the size changes\n */\n public void propertyChange(PropertyChangeEvent e) {\n String prop = e.getPropertyName();\n if(\"font\".equals(prop)) {\n recalcDimensions();\n }\n }\n\n /** \n * Calculates the dimensions. If they've changed,\n * invalidates the component\n */\n void recalcDimensions() {\n int wOld = getIconWidth();\n int hOld = getIconHeight();\n calcDimensions();\n if (wOld != getIconWidth() || hOld != getIconHeight())\n fComponent.invalidate();\n }\n\n void calcDimensions() {\n FontMetrics fm = fComponent.getFontMetrics(fComponent.getFont());\n fCharHeight = fm.getAscent() + fm.getDescent();\n fDescent = fm.getDescent();\n if (fRotation == ROTATE_NONE) {\n int len = fLabel.length();\n char data[] = new char[len];\n fLabel.getChars(0, len, data, 0);\n // if not rotated, width is that of the widest char in the string\n fWidth = 0;\n // we need an array of one-char strings for drawString\n fCharStrings = new String[len];\n fCharWidths = new int[len];\n fPosition = new int[len];\n char ch;\n for (int i = 0; i < len; i++) {\n ch = data[i];\n fCharWidths[i] = fm.charWidth(ch);\n if (fCharWidths[i] > fWidth)\n fWidth = fCharWidths[i];\n fCharStrings[i] = new String(data, i, 1); \n // small kana and punctuation\n if (sDrawsInTopRight.indexOf(ch) >= 0) // if ch is in sDrawsInTopRight\n fPosition[i] = POSITION_TOP_RIGHT;\n else if (sDrawsInFarTopRight.indexOf(ch) >= 0)\n fPosition[i] = POSITION_FAR_TOP_RIGHT;\n else\n fPosition[i] = POSITION_NORMAL;\n }\n // and height is the font height * the char count, + one extra leading at the bottom\n fHeight = fCharHeight * len + fDescent;\n } \n else {\n // if rotated, width is the height of the string\n fWidth = fCharHeight;\n // and height is the width, plus some buffer space \n fHeight = fm.stringWidth(fLabel) + 2*kBufferSpace;\n }\n }\n\n /**\n * Draw the icon at the specified location. Icon implementations\n * may use the Component argument to get properties useful for \n * painting, e.g. the foreground or background color.\n */\n public void paintIcon(Component c, Graphics g, int x, int y) {\n // We don't insist that it be on the same Component\n g.setColor(c.getForeground());\n g.setFont(c.getFont());\n if (fRotation == ROTATE_NONE) {\n int yPos = y + fCharHeight;\n for (int i = 0; i < fCharStrings.length; i++) {\n // Special rules for Japanese - \"half-height\" characters (like ya, yu, yo in combinations)\n // should draw in the top-right quadrant when drawn vertically\n // - they draw in the bottom-left normally\n int tweak;\n switch (fPosition[i]) {\n case POSITION_NORMAL: \n // Roman fonts should be centered. Japanese fonts are always monospaced. \n g.drawString(fCharStrings[i], x+((fWidth-fCharWidths[i])/2), yPos);\n break;\n case POSITION_TOP_RIGHT:\n tweak = fCharHeight/3; // Should be 2, but they aren't actually half-height\n g.drawString(fCharStrings[i], x+(tweak/2), yPos-tweak); \n break;\n case POSITION_FAR_TOP_RIGHT:\n tweak = fCharHeight - fCharHeight/3;\n g.drawString(fCharStrings[i], x+(tweak/2), yPos-tweak); \n break;\n }\n yPos += fCharHeight;\n }\n }\n else if (fRotation == ROTATE_LEFT) {\n g.translate(x+fWidth,y+fHeight);\n ((Graphics2D)g).rotate(-NINETY_DEGREES);\n g.drawString(fLabel, kBufferSpace, -fDescent);\n ((Graphics2D)g).rotate(NINETY_DEGREES);\n g.translate(-(x+fWidth),-(y+fHeight));\n } \n else if (fRotation == ROTATE_RIGHT) {\n g.translate(x,y);\n ((Graphics2D)g).rotate(NINETY_DEGREES);\n g.drawString(fLabel, kBufferSpace, -fDescent);\n ((Graphics2D)g).rotate(-NINETY_DEGREES);\n g.translate(-x,-y);\n } \n\n }\n\n /**\n * Returns the icon's width.\n *\n * @return an int specifying the fixed width of the icon.\n */\n public int getIconWidth() {\n return fWidth;\n }\n\n /**\n * Returns the icon's height.\n *\n * @return an int specifying the fixed height of the icon.\n */\n public int getIconHeight() {\n return fHeight;\n }\n\n /** \n verifyRotation\n\n returns the best rotation for the string (ROTATE_NONE, ROTATE_LEFT, ROTATE_RIGHT)\n\n This is public static so you can use it to test a string without creating a VTextIcon\n\n from http://www.unicode.org/unicode/reports/tr9/tr9-3.html\n When setting text using the Arabic script in vertical lines, \n it is more common to employ a horizontal baseline that \n is rotated by 90� counterclockwise so that the characters \n are ordered from top to bottom. Latin text and numbers \n may be rotated 90� clockwise so that the characters \n are also ordered from top to bottom.\n\n Rotation rules\n - Roman can rotate left, right, or none - default right (counterclockwise)\n - CJK can't rotate\n - Arabic must rotate - default left (clockwise)\n\n from the online edition of _The Unicode Standard, Version 3.0_, file ch10.pdf page 4\n Ideographs are found in three blocks of the Unicode Standard...\n U+4E00-U+9FFF, U+3400-U+4DFF, U+F900-U+FAFF\n\n Hiragana is U+3040-U+309F, katakana is U+30A0-U+30FF\n\n from http://www.unicode.org/unicode/faq/writingdirections.html\n East Asian scripts are frequently written in vertical lines \n which run from top-to-bottom and are arrange columns either \n from left-to-right (Mongolian) or right-to-left (other scripts). \n Most characters use the same shape and orientation when displayed \n horizontally or vertically, but many punctuation characters \n will change their shape when displayed vertically.\n\n Letters and words from other scripts are generally rotated through \n ninety degree angles so that they, too, will read from top to bottom. \n That is, letters from left-to-right scripts will be rotated clockwise \n and letters from right-to-left scripts counterclockwise, both \n through ninety degree angles.\n\n Unlike the bidirectional case, the choice of vertical layout \n is usually treated as a formatting style; therefore, \n the Unicode Standard does not define default rendering behavior \n for vertical text nor provide directionality controls designed to override such behavior\n\n */\n public static int verifyRotation(String label, int rotateHint) {\n boolean hasCJK = false;\n boolean hasMustRotate = false; // Arabic, etc\n\n int len = label.length();\n char data[] = new char[len];\n char ch;\n label.getChars(0, len, data, 0);\n for (int i = 0; i < len; i++) {\n ch = data[i];\n if ((ch >= '\\u4E00' && ch <= '\\u9FFF') ||\n (ch >= '\\u3400' && ch <= '\\u4DFF') ||\n (ch >= '\\uF900' && ch <= '\\uFAFF') ||\n (ch >= '\\u3040' && ch <= '\\u309F') ||\n (ch >= '\\u30A0' && ch <= '\\u30FF') )\n hasCJK = true;\n if ((ch >= '\\u0590' && ch <= '\\u05FF') || // Hebrew\n (ch >= '\\u0600' && ch <= '\\u06FF') || // Arabic\n (ch >= '\\u0700' && ch <= '\\u074F') ) // Syriac\n hasMustRotate = true;\n }\n // If you mix Arabic with Chinese, you're on your own\n if (hasCJK)\n return DEFAULT_CJK;\n\n int legal = hasMustRotate ? LEGAL_MUST_ROTATE : LEGAL_ROMAN;\n if ((rotateHint & legal) > 0)\n return rotateHint;\n\n // The hint wasn't legal, or it was zero\n return hasMustRotate ? DEFAULT_MUST_ROTATE : DEFAULT_ROMAN;\n }\n\n // The small kana characters and Japanese punctuation that draw in the top right quadrant:\n // small a, i, u, e, o, tsu, ya, yu, yo, wa (katakana only) ka ke\n static final String sDrawsInTopRight = \n \"\\u3041\\u3043\\u3045\\u3047\\u3049\\u3063\\u3083\\u3085\\u3087\\u308E\" + // hiragana \n \"\\u30A1\\u30A3\\u30A5\\u30A7\\u30A9\\u30C3\\u30E3\\u30E5\\u30E7\\u30EE\\u30F5\\u30F6\"; // katakana\n static final String sDrawsInFarTopRight = \"\\u3001\\u3002\"; // comma, full stop\n\n static final int DEFAULT_CJK = ROTATE_NONE;\n static final int LEGAL_ROMAN = ROTATE_NONE | ROTATE_LEFT | ROTATE_RIGHT;\n static final int DEFAULT_ROMAN = ROTATE_RIGHT; \n static final int LEGAL_MUST_ROTATE = ROTATE_LEFT | ROTATE_RIGHT;\n static final int DEFAULT_MUST_ROTATE = ROTATE_LEFT;\n\n static final double NINETY_DEGREES = Math.toRadians(90.0);\n static final int kBufferSpace = 5;\n}\n</code></pre>\n\n<p>Provided as free to use for any purpose.</p>\n\n<p>There's also a <code>CompositeIcon</code> class that lets you compose the vertical text with another icon (not given here)</p>\n\n<p>As per a comment in the article, add anti-aliasing in the <code>paintIcon</code> method:</p>\n\n<pre><code> Graphics2D g2 = (Graphics2D) g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16538/"
]
| I'm looking to have text display vertically, first letter at the bottom, last letter at the top, within a JLabel. Is this possible? | I found this page: <http://www.java2s.com/Tutorial/Java/0240__Swing/VerticalLabelUI.htm> when I needed to do that.
I don't know if you want the letters 'standing' on each other or all rotated on their side.
```
/*
* The contents of this file are subject to the Sapient Public License
* Version 1.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://carbon.sf.net/License.html.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is The Carbon Component Framework.
*
* The Initial Developer of the Original Code is Sapient Corporation
*
* Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
*/
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicLabelUI;
/**
* This is the template for Classes.
*
*
* @since carbon 1.0
* @author Greg Hinkle, January 2002
* @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:27 $)
* @copyright 2002 Sapient
*/
public class VerticalLabelUI extends BasicLabelUI {
static {
labelUI = new VerticalLabelUI(false);
}
protected boolean clockwise;
public VerticalLabelUI(boolean clockwise) {
super();
this.clockwise = clockwise;
}
public Dimension getPreferredSize(JComponent c) {
Dimension dim = super.getPreferredSize(c);
return new Dimension( dim.height, dim.width );
}
private static Rectangle paintIconR = new Rectangle();
private static Rectangle paintTextR = new Rectangle();
private static Rectangle paintViewR = new Rectangle();
private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
public void paint(Graphics g, JComponent c) {
JLabel label = (JLabel)c;
String text = label.getText();
Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
if ((icon == null) && (text == null)) {
return;
}
FontMetrics fm = g.getFontMetrics();
paintViewInsets = c.getInsets(paintViewInsets);
paintViewR.x = paintViewInsets.left;
paintViewR.y = paintViewInsets.top;
// Use inverted height & width
paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
String clippedText =
layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
Graphics2D g2 = (Graphics2D) g;
AffineTransform tr = g2.getTransform();
if (clockwise) {
g2.rotate( Math.PI / 2 );
g2.translate( 0, - c.getWidth() );
} else {
g2.rotate( - Math.PI / 2 );
g2.translate( - c.getHeight(), 0 );
}
if (icon != null) {
icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
}
if (text != null) {
int textX = paintTextR.x;
int textY = paintTextR.y + fm.getAscent();
if (label.isEnabled()) {
paintEnabledText(label, g, clippedText, textX, textY);
} else {
paintDisabledText(label, g, clippedText, textX, textY);
}
}
g2.setTransform( tr );
}
}
``` |
92,792 | <p>I have a user control which is loaded in the page dynamically using the following code in Init of the Page.</p>
<pre><code>Dim oCtl As Object
oCtl = LoadControl("~/Controls/UserControl1.ascx")
oCtl.Id = "UserControl11"
PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(oCtl)
</code></pre>
<p>The user control also contains a button and I am unable to capture the button click within the user control. </p>
| [
{
"answer_id": 92810,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>A few questions:</p>\n\n<ol>\n<li>At what point in the page lifecycle do you load the control?</li>\n<li>Where is the event handler code? In the control itself or do you try to hook it up to the page?</li>\n<li>What have you done so far to wire up the event?</li>\n</ol>\n\n<p>Finally, the style guidelines for .Net specifically recommend <em>against</em> using any hugarian prefix warts like the o in oCtl, and you should type it as a Control rather than an object.</p>\n"
},
{
"answer_id": 92852,
"author": "Doug Moore",
"author_id": 13179,
"author_profile": "https://Stackoverflow.com/users/13179",
"pm_score": -1,
"selected": false,
"text": "<p>You want to only load the control when not isPostBack</p>\n"
},
{
"answer_id": 92934,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure you load the control on every postback - if the control isn't in the tree of controls when the page posts back, ASP.NET will not raise the button click event. </p>\n"
},
{
"answer_id": 93013,
"author": "Dave Gray",
"author_id": 5605,
"author_profile": "https://Stackoverflow.com/users/5605",
"pm_score": 3,
"selected": false,
"text": "<p>You have to ensure that the control exists on the page prior to .NET entering the \"Postback event handling\" step of the page lifecycle. Since the control is added dynamically you have to ensure that on every post back you recreate that control so that it can find the control to fire the event.</p>\n"
},
{
"answer_id": 93120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the complete code for the Page</p>\n\n<pre><code>Partial Class DynamicLoad\n Inherits System.Web.UI.Page\n\n Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n If IsPostBack Then\n If Not (Session(\"ctl\") Is Nothing) Then\n Dim oCtl As Object\n oCtl = Session(\"ctl\")\n PlaceHolder1.Controls.Add(oCtl)\n End If\n End If\n End Sub\n\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not IsPostBack Then\n Dim oCtl As Object\n oCtl = LoadControl(\"~/Controls/UserControl1.ascx\")\n\n oCtl.Id = \"UserControl11\"\n PlaceHolder1.Controls.Clear()\n PlaceHolder1.Controls.Add(oCtl)\n\n Session(\"ctl\") = oCtl\n End If\n End Sub\nEnd Class\n</code></pre>\n\n<p>Here is the complete code for the user Control</p>\n\n<pre><code>Partial Class UserControl1\n Inherits System.Web.UI.UserControl\n Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click\n Label1.Text = \"This is Text AFTER Post Back in User Control 1\"\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 93355,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Since you asked, I'd write your init event like this. I'll leave the Load event as an exercise:</p>\n\n<pre><code>Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n If IsPostBack AndAlso Session(\"ctl\") IsNot Nothing Then\n Dim MyControl As Control = Session(\"ctl\")\n PlaceHolder1.Controls.Add(MyControl)\n End If\nEnd Sub\n</code></pre>\n\n<p>I'd also come up with a better name than 'mycontrol', but since I don't know what the control does this will have to do.</p>\n"
},
{
"answer_id": 93709,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know without trying it, but what if you programatically wire up the button's event handler? For instance, in the code-behind for the User Control itself, in Init or Load (not sure):</p>\n\n<pre><code>AddHandler Button1.Click, AddressOf Button1_Click\n</code></pre>\n\n<p>If that doesn't do anything, I know it's less efficient, but what if you don't store the User Control instance in Session and always recreate it in Page_Init every time?</p>\n"
},
{
"answer_id": 201166,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": false,
"text": "<p>There are a couple of things which you are doing that are both not needed and probably causing your problems.</p>\n\n<p>These are:</p>\n\n<ol>\n<li>There is no need to store the control object in the session. The Control itself should use ViewState and Session State to store information as required, not the whole instance.</li>\n<li>You shouldn't be checking for PostBack when creating the control. It must be created each time to allow both ViewState to work and the event to be wired.</li>\n<li>Controls loaded after the ViewState is loaded often have trouble operating correctly so avoid loading during the Page Load event wherever possible.</li>\n</ol>\n\n<p>This code works for me:</p>\n\n<hr>\n\n<p>Default.aspx</p>\n\n<pre><code><%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"Default.aspx.vb\" Inherits=\"Test_User_Control._Default\" %>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\"><title></title></head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <asp:PlaceHolder ID=\"PlaceHolder1\" runat=\"server\" />\n </form>\n</body>\n</html>\n</code></pre>\n\n<hr>\n\n<p>Default.aspx.vb</p>\n\n<pre><code>Partial Public Class _Default\n Inherits System.Web.UI.Page\n\n Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n\n Dim control As Control = LoadControl(\"~/UserControl1.ascx\")\n PlaceHolder1.Controls.Add(control)\n\n End Sub\nEnd Class\n</code></pre>\n\n<hr>\n\n<p>UserControl1.ascx</p>\n\n<pre><code><%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"UserControl1.ascx.vb\" Inherits=\"Test_User_Control.UserControl1\" %>\n<asp:Label ID=\"Label1\" Text=\"Before Button Press\" runat=\"server\" />\n<asp:Button ID=\"Button1\" Text=\"Push me\" runat=\"server\" />\n</code></pre>\n\n<hr>\n\n<p>UserControl1.ascx.vb</p>\n\n<pre><code>Public Partial Class UserControl1\n Inherits System.Web.UI.UserControl\n\n Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click\n Label1.Text = \"The button has been pressed!\"\n End Sub\n\nEnd Class\n</code></pre>\n\n<hr>\n"
},
{
"answer_id": 545569,
"author": "ljubomir",
"author_id": 11506,
"author_profile": "https://Stackoverflow.com/users/11506",
"pm_score": 2,
"selected": false,
"text": "<p>I just experienced similar problem as you did, except that in my case i didn't used a session to store the control.</p>\n\n<p>In my case, i located the problem in this line:</p>\n\n<p><code>PlaceHolder1.Controls.Clear()</code></p>\n\n<p>What i did is created a child controls and added them to the parent container on Page_Init, then processed some event handlers and after that on Page_PreRender i recreated the whole list again with the updated data.</p>\n\n<p>The solution i used in this case was to create the control collection once - in the early phase of the page cycle.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a user control which is loaded in the page dynamically using the following code in Init of the Page.
```
Dim oCtl As Object
oCtl = LoadControl("~/Controls/UserControl1.ascx")
oCtl.Id = "UserControl11"
PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(oCtl)
```
The user control also contains a button and I am unable to capture the button click within the user control. | You have to ensure that the control exists on the page prior to .NET entering the "Postback event handling" step of the page lifecycle. Since the control is added dynamically you have to ensure that on every post back you recreate that control so that it can find the control to fire the event. |
92,802 | <p>I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the <code>pause</code> command. Is there a Linux equivalent I can use in my script?</p>
| [
{
"answer_id": 92813,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 10,
"selected": true,
"text": "<p><code>read</code> does this:</p>\n\n<pre><code>user@host:~$ read -n1 -r -p \"Press any key to continue...\" key\n[...]\nuser@host:~$ \n</code></pre>\n\n<p>The <code>-n1</code> specifies that it only waits for a single character. The <code>-r</code> puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The <code>-p</code> specifies the prompt, which must be quoted if it contains spaces. The <code>key</code> argument is only necessary if you want to know which key they pressed, in which case you can access it through <code>$key</code>.</p>\n\n<p>If you are using Bash, you can also specify a timeout with <code>-t</code>, which causes read to return a failure when a key isn't pressed. So for example:</p>\n\n<pre><code>read -t5 -n1 -r -p 'Press any key in the next five seconds...' key\nif [ \"$?\" -eq \"0\" ]; then\n echo 'A key was pressed.'\nelse\n echo 'No key was pressed.'\nfi\n</code></pre>\n"
},
{
"answer_id": 92821,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>function pause(){\n read -p \"$*\"\n}\n</code></pre>\n"
},
{
"answer_id": 92913,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 4,
"selected": false,
"text": "<p><code>read</code> without any parameters will only continue if you press enter.\nThe DOS <code>pause</code> command will continue if you press any key. Use <code>read –n1</code> if you want this behaviour.</p>\n"
},
{
"answer_id": 17778773,
"author": "y.petremann",
"author_id": 1311620,
"author_profile": "https://Stackoverflow.com/users/1311620",
"pm_score": 7,
"selected": false,
"text": "<p>\nI use these ways a lot that are very short, and they are like @theunamedguy and @Jim solutions, but with timeout and silent mode in addition. </p>\n\n<p>I especially love the last case and use it in a lot of scripts that run in a loop until the user presses <kbd>Enter</kbd>.</p>\n\n<h1>Commands</h1>\n\n<ul>\n<li><p><strong>Enter solution</strong></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rsp $'Press enter to continue...\\n'\n</code></pre></li>\n<li><p><strong>Escape solution</strong> <em>(with -d $'\\e')</em></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rsp $'Press escape to continue...\\n' -d $'\\e'\n</code></pre></li>\n<li><p><strong>Any key solution</strong> <em>(with -n 1)</em></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rsp $'Press any key to continue...\\n' -n 1 key\n# echo $key\n</code></pre></li>\n<li><p><strong>Question with preselected choice</strong> <em>(with -ei $'Y')</em></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rp $'Are you sure (Y/n) : ' -ei $'Y' key;\n# echo $key\n</code></pre></li>\n<li><p><strong>Timeout solution</strong> <em>(with -t 5)</em></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rsp $'Press any key or wait 5 seconds to continue...\\n' -n 1 -t 5;\n</code></pre></li>\n<li><p><strong>Sleep enhanced alias</strong></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>read -rst 0.5; timeout=$?\n# echo $timeout\n</code></pre></li>\n</ul>\n\n<h1>Explanation</h1>\n\n<p><strong>-r</strong> specifies raw mode, which don't allow combined characters like \"\\\" or \"^\".</p>\n\n<p><strong>-s</strong> specifies silent mode, and because we don't need keyboard output.</p>\n\n<p><strong>-p $'<em>prompt</em>'</strong> specifies the prompt, which need to be between $' and ' to let spaces and escaped characters. Be careful, you must put between single quotes with dollars symbol to benefit escaped characters, otherwise you can use simple quotes.</p>\n\n<p><strong>-d $'<em>\\e</em>'</strong> specifies escappe as delimiter charater, so as a final character for current entry, this is possible to put any character but be careful to put a character that the user can type.</p>\n\n<p><strong>-n <em>1</em></strong> specifies that it only needs a single character.</p>\n\n<p><strong>-e</strong> specifies readline mode.</p>\n\n<p><strong>-i $'<em>Y</em>'</strong> specifies Y as initial text in readline mode.</p>\n\n<p><strong>-t <em>5</em></strong> specifies a timeout of 5 seconds</p>\n\n<p><strong><em>key</em></strong> serve in case you need to know the input, in -n1 case, the key that has been pressed.</p>\n\n<p><strong>$?</strong> serve to know the exit code of the last program, for read, 142 in case of timeout, 0 correct input. Put $? in a variable as soon as possible if you need to test it after somes commands, because all commands would rewrite $?</p>\n"
},
{
"answer_id": 24046880,
"author": "mikeserv",
"author_id": 2955202,
"author_profile": "https://Stackoverflow.com/users/2955202",
"pm_score": 4,
"selected": false,
"text": "<p><code>read -n1</code> is not portable. A portable way to do the same might be:</p>\n\n<pre><code>( trap \"stty $(stty -g;stty -icanon)\" EXIT\n LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1\n) </dev/tty\n</code></pre>\n\n<p>Besides using <code>read</code>, for just a press <code>ENTER</code> to continue prompt you could do:</p>\n\n<pre><code>sed -n q </dev/tty\n</code></pre>\n"
},
{
"answer_id": 39638013,
"author": "mwfearnley",
"author_id": 446106,
"author_profile": "https://Stackoverflow.com/users/446106",
"pm_score": 2,
"selected": false,
"text": "<p>If you just need to pause a loop or script, and you're happy to press Enter instead of any key, then <code>read</code> on its own will do the job.</p>\n\n<pre><code>do_stuff\nread\ndo_more_stuff\n</code></pre>\n\n<p>It's not end-user friendly, but may be enough in cases where you're writing a quick script for yourself, and you need to pause it to do something manually in the background.</p>\n"
},
{
"answer_id": 41728415,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me on multiple flavors of Linux, where some of these other solutions did not (including the most popular ones here). I think it's more readable too...</p>\n\n<pre><code>echo Press enter to continue; read dummy;\n</code></pre>\n\n<p>Note that a variable needs to be supplied as an argument to <code>read</code>.</p>\n"
},
{
"answer_id": 49656617,
"author": "SDsolar",
"author_id": 5093068,
"author_profile": "https://Stackoverflow.com/users/5093068",
"pm_score": 0,
"selected": false,
"text": "<p>Yes to using <code>read</code> - and there are a couple of tweaks that make it most useful in both <code>cron</code> and in the terminal. </p>\n\n<p>Example:</p>\n\n<pre><code>time rsync (options)\nread -n 120 -p \"Press 'Enter' to continue...\" ; echo \" \"\n</code></pre>\n\n<p>The -n 120 makes the read statement time out after 2 minutes so it does not block in <code>cron</code>. </p>\n\n<p>In terminal it gives 2 minutes to see how long the <code>rsync</code> command took to execute.</p>\n\n<p>Then the subsequent <code>echo</code> is so the subsequent bash prompt will appear on the next line.</p>\n\n<p>Otherwise it will show on the same line directly after \"continue...\" when <kbd>Enter</kbd> is pressed in terminal.</p>\n"
},
{
"answer_id": 51075278,
"author": "Tom Hale",
"author_id": 5353461,
"author_profile": "https://Stackoverflow.com/users/5353461",
"pm_score": 2,
"selected": false,
"text": "<p>This function works in both <code>bash</code> and <code>zsh</code>, and ensures I/O to the terminal:</p>\n\n<pre><code># Prompt for a keypress to continue. Customise prompt with $*\nfunction pause {\n >/dev/tty printf '%s' \"${*:-Press any key to continue... }\"\n [[ $ZSH_VERSION ]] && read -krs # Use -u0 to read from STDIN\n [[ $BASH_VERSION ]] && </dev/tty read -rsn1\n printf '\\n'\n}\nexport_function pause\n</code></pre>\n\n<p>Put it in your <code>.{ba,z}shrc</code> for Great Justice!</p>\n"
},
{
"answer_id": 69035133,
"author": "SwiftNinjaPro",
"author_id": 10355515,
"author_profile": "https://Stackoverflow.com/users/10355515",
"pm_score": 2,
"selected": false,
"text": "<p>This fixes it so pressing any key other than ENTER will still go to a new line</p>\n<pre><code>read -n1 -r -s -p "Press any key to continue..." ; echo\n</code></pre>\n<hr />\n<p>it's better than windows pause, because you can change the text to make it more useful</p>\n<pre><code>read -n1 -r -s -p "Press any key to continue... (cant find the ANY key? press ENTER) " ; echo\n</code></pre>\n"
},
{
"answer_id": 71361396,
"author": "Siddharth Maurya",
"author_id": 14165601,
"author_profile": "https://Stackoverflow.com/users/14165601",
"pm_score": 0,
"selected": false,
"text": "<p>I've built a little program to achieve <code>pause</code> command in Linux. I've uploaded the code on my GitHub <a href=\"https://github.com/savvysiddharth/pause-command\" rel=\"nofollow noreferrer\">repo</a>.</p>\n<p>To install it,</p>\n<pre><code>git clone https://github.com/savvysiddharth/pause-command.git\ncd pause-command\nsudo make install\n</code></pre>\n<p>With this installed, you can now use <code>pause</code> command similar to like you did in windows.</p>\n<p>It also supports optional custom string like <code>read</code>.</p>\n<p>Example:</p>\n<pre><code>pause "Pausing execution, Human intervention required..."\n</code></pre>\n<p>Using this, C/C++ programs using statements like <code>system("pause");</code> are now compatible with linux.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362/"
]
| I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the `pause` command. Is there a Linux equivalent I can use in my script? | `read` does this:
```
user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$
```
The `-n1` specifies that it only waits for a single character. The `-r` puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The `-p` specifies the prompt, which must be quoted if it contains spaces. The `key` argument is only necessary if you want to know which key they pressed, in which case you can access it through `$key`.
If you are using Bash, you can also specify a timeout with `-t`, which causes read to return a failure when a key isn't pressed. So for example:
```
read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
echo 'A key was pressed.'
else
echo 'No key was pressed.'
fi
``` |
92,820 | <pre><code>class A : IFoo
{
}
...
A[] arrayOfA = new A[10];
if(arrayOfA is IFoo[])
{
// this is not called
}
</code></pre>
<p>Q1: Why is <code>arrayOfA</code> not an array of <code>IFoos</code>?</p>
<p>Q2: Why can't I cast <code>arrayOfA</code> to <code>IFoo[]</code>?</p>
| [
{
"answer_id": 92856,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "<p>You could try</p>\n\n<pre><code>if (arrayofA[0] is IFoo) {.....}\n</code></pre>\n\n<p>which sort of answers your question. <code>arrayOfA</code> is an array. An array is an object which implements <code>ICloneable</code>, <code>IList</code>, <code>ICollection</code>, & <code>IEnumerable</code>. <code>IFoo</code> isn't among them.</p>\n"
},
{
"answer_id": 92876,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 4,
"selected": true,
"text": "<p><code>arrayOfA</code> <strong>is</strong> <code>IFoo[]</code>. </p>\n\n<p>There must be something else wrong with your program.</p>\n\n<p>You seem to have mocked up some code to show the problem, but in fact your code (see below) works as you expect. Try updating this question with the real code - or as close to real as you can - and we can take another look.</p>\n\n<pre><code>using System;\npublic class oink {\n public static void Main() {\n A[] aOa = new A[10];\n\n if (aOa is IFoo[]) { Console.WriteLine(\"aOa is IFoo[]\"); }\n\n }\n public interface IFoo {}\n public class A : IFoo {}\n}\n\nPS D:\\> csc test.cs\nMicrosoft (R) Visual C# 2008 Compiler version 3.5.30729.1\nfor Microsoft (R) .NET Framework version 3.5\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nPS D:\\> D:\\test.exe\naOa is IFoo[]\nPS D:\\>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
]
| ```
class A : IFoo
{
}
...
A[] arrayOfA = new A[10];
if(arrayOfA is IFoo[])
{
// this is not called
}
```
Q1: Why is `arrayOfA` not an array of `IFoos`?
Q2: Why can't I cast `arrayOfA` to `IFoo[]`? | `arrayOfA` **is** `IFoo[]`.
There must be something else wrong with your program.
You seem to have mocked up some code to show the problem, but in fact your code (see below) works as you expect. Try updating this question with the real code - or as close to real as you can - and we can take another look.
```
using System;
public class oink {
public static void Main() {
A[] aOa = new A[10];
if (aOa is IFoo[]) { Console.WriteLine("aOa is IFoo[]"); }
}
public interface IFoo {}
public class A : IFoo {}
}
PS D:\> csc test.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.
PS D:\> D:\test.exe
aOa is IFoo[]
PS D:\>
``` |
92,841 | <p>I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.</p>
| [
{
"answer_id": 92958,
"author": "Zach",
"author_id": 8720,
"author_profile": "https://Stackoverflow.com/users/8720",
"pm_score": 2,
"selected": false,
"text": "<p>I found an answer to my question. I can call</p>\n\n<pre><code>CodeCompiler.ValidateIdentifiers(class1);\n</code></pre>\n\n<p>where class1 is a CodeObject to validate all identifiers in that CodeDom tree and below. So I can call this right after I create my CodeTypeDeclaration class1 to validate just the class name, or I can build up my CodeDom and then call this at the end to validate all the identifiers in my tree. Just what I needed!</p>\n"
},
{
"answer_id": 92978,
"author": "Jason Diller",
"author_id": 2187,
"author_profile": "https://Stackoverflow.com/users/2187",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <code>CreateValidIdentifier</code> method on the <code>CSharpCodeProvider</code> class. </p>\n\n<pre><code>CSharpCodeProvider codeProvider = new CSharpCodeProvider(); \nstring sFixedName = codeProvider.CreateValidIdentifier(\"somePossiblyInvalidName\"); \nCodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); \n</code></pre>\n\n<p>It returns a valid name given some input. If you just want to validate the name and not fix it, compare the input and output. It won't alter valid input so the output will be equivalent. </p>\n"
},
{
"answer_id": 92982,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 6,
"selected": true,
"text": "<p>An easy way to determine if a string is a valid identifier for a class or variable is to call the static method </p>\n\n<pre><code>System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)\n</code></pre>\n"
},
{
"answer_id": 93919,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public static bool IsReservedKeyWord(string identifier)\n {\n Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();\n return csharpProvider.IsValidIdentifier(identifier);\n }\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720/"
]
| I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name. | An easy way to determine if a string is a valid identifier for a class or variable is to call the static method
```
System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)
``` |
92,847 | <p>How do I make an array shorter in Perl? I read some webpages indicating that I can assign:</p>
<pre><code>$#ARRAY = 42;
</code></pre>
<p>I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work:</p>
<pre><code>$#$ARRAY[$i] = 42;
</code></pre>
| [
{
"answer_id": 92865,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 0,
"selected": false,
"text": "<p>$#{$ARRAY[$i]} = 42;</p>\n"
},
{
"answer_id": 92883,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>You could do</p>\n\n<pre><code>splice @array, $length;\n#or\nsplice @{$arrays[$i]}, $length;\n</code></pre>\n"
},
{
"answer_id": 92935,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 3,
"selected": false,
"text": "<p>Your options are near limitless (I've outlined five approaches here) but your strategy will be dictated by exactly what your specific needs and goals are. (all examples will convert @array to have no more than $N elements)</p>\n\n<hr>\n\n<p>[EDIT]</p>\n\n<p>As others have pointed out, the way suggested in the original question is actually not deprecated, and it provides the fastest, tersest, but not necessarily the most readable solution. <strong>It also has the side effect of expanding an array of fewer than $N elements with empty elements</strong>:</p>\n\n<pre><code>$#array = $N-1;\n</code></pre>\n\n<hr>\n\n<p>Least code: </p>\n\n<pre><code>#best for trimming down large arrays into small arrays\n@array = $array[0..($N-1)];\n</code></pre>\n\n<p>Most efficient for trimming a small number off of a large array:</p>\n\n<pre><code>#This is a little less expensive and clearer\nsplice(@array, $n, @#array);\n</code></pre>\n\n<p>Undesirable in almost all cases, unless you really love delete():</p>\n\n<pre><code>#this is the worst solution yet because it requires resizing after the delete\nwhile($N-1 < $#array)\n{\n delete(array[$i]);\n}\n</code></pre>\n\n<p>Useful if you need the remainder of the list in reverse order:</p>\n\n<pre><code>#this is better than deleting because there is no resize\nwhile($N-1 < $#array)\n{\n pop @array;\n #or, \"push $array2, pop @array;\" for the reverse order remainder\n}\n</code></pre>\n\n<p>Useful for saving time in long run:</p>\n\n<pre><code>#don't put more values into the array than you actually want\n</code></pre>\n"
},
{
"answer_id": 92968,
"author": "Rob N",
"author_id": 12421,
"author_profile": "https://Stackoverflow.com/users/12421",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not aware of assigning <code>$#ARRAY</code> being deprecated; <code>perldoc perldata</code> from 5.10.0 certainly says nothing about it. It is the fastest way to truncate an array.</p>\n\n<p>If you want something a little more readable, use <code>splice</code>:</p>\n\n<pre><code>splice @ARRAY, 43;\n</code></pre>\n\n<p>(Note <code>43</code> instead of <code>42</code> - <code>$#ARRAY</code> gets you the last index of the array, whereas <code>splice</code> taks the <em>length</em> of the array instead).</p>\n\n<p>As for working on arrays of arrays, I assume you mean being able to truncate a nested array via a reference? In that case, you want:</p>\n\n<pre><code>$#{$ARRAY->[7]} = 42;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>splice @{$ARRAY->[7]}, 43;\n</code></pre>\n"
},
{
"answer_id": 93012,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>$#array is the <em>last index</em> of the array. </li>\n<li>$#$array <em>would be</em> the last index of an array <em>pointed at</em> by $array. </li>\n<li>$#$array[$i] means you're trying to index a scalar--can't be done. $#{$array[3]} properly resolves the subscripting of the main array before we try to reference the last index. </li>\n<li><p>Used alone </p>\n\n<p>$#{$array[3]} = 9;</p>\n\n<p>assigns a length of 9 to the <a href=\"http://en.wikipedia.org/wiki/Autovivification\" rel=\"nofollow noreferrer\">autovivified</a> array at $array[3].</p></li>\n<li><p>When in doubt, use Data::Dumper:</p>\n\n<pre><code>use Data::Dumper;\n$#{$array[3]} = 5;\n$#array = 10;\nprint Dumper( \\@array, $array ), \"\\n\";\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 93241,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 3,
"selected": false,
"text": "<p>You essentially gave the canonical answer yourself. You shorten an array by setting the last index:</p>\n\n<pre><code>$#Array = 42\n</code></pre>\n\n<p>The $#Foo notation for denoting the last index in the array is absolutely <em>not</em> deprecated. Similarly, assigning to it will not be deprecated either. Quoting the perldata documentation:</p>\n\n<blockquote>\n <p>The length of an array is a scalar value. <strong>You may find the length of\n array @days by evaluating $#days</strong>, as in csh. However, this isn’t the\n length of the array; it’s the subscript of the last element, which is a\n different value since there is ordinarily a 0th element. <strong>Assigning to\n $#days actually changes the length of the array.</strong> Shortening an array\n this way destroys intervening values. Lengthening an array that was\n previously shortened does not recover values that were in those\n elements. (It used to do so in Perl 4, but we had to break this to\n make sure destructors were called when expected.)</p>\n</blockquote>\n"
},
{
"answer_id": 94094,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://search.cpan.org/dist/perl-5.8.8/pod/perlvar.pod#%24%23\" rel=\"nofollow noreferrer\"><code>$#</code></a> variable is deprecated, but the <code>$#array</code> feature is not.</p>\n\n<p>To use the <code>$#array</code> syntax on an arbitrary expression that yields an array reference, do <code>$#{ EXPR }</code>.</p>\n\n<p>See the invaluable: <a href=\"http://perlmonks.org/?node=References+quick+reference\" rel=\"nofollow noreferrer\">http://perlmonks.org/?node=References+quick+reference</a></p>\n"
},
{
"answer_id": 95243,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 0,
"selected": false,
"text": "<p>There are two ways of interpreting the question.</p>\n\n<ul>\n<li>How to reduce the length of the array?</li>\n<li>How to reduce the amount of memory consumed by the array?</li>\n</ul>\n\n<p>Most of the answers so far focus on the former. In my view, the best answer to that is the <strong>splice</strong> function. For example, to remove 10 elements from the end:</p>\n\n<pre><code>splice @array, -10;\n</code></pre>\n\n<p>However, because of how Perl manages memory for arrays, the only way to ensure that an array takes less memory is to copy it to a new array (and let the memory of the old array be reclaimed). For this, I would tend to think about using a <em>slice</em> operation. E.g., to remove 10 elements:</p>\n\n<pre><code>@new = @old[ 0 .. $#old - 10 ]\n</code></pre>\n\n<p>Here's a comparison of different approaches for a 500 element array (using 2104 bytes):</p>\n\n<pre><code> original: length 500 => size 2104\n pound: length 490 => size 2208\n splice: length 490 => size 2104\n delete: length 490 => size 2104\n slice: length 490 => size 2064\n</code></pre>\n\n<p>You can see that only the slice operation (copied to a new array) has a smaller <em>size</em> than the original.</p>\n\n<p>Here's the code I used for this analysis:</p>\n\n<pre><code>use strict;\nuse warnings;\nuse 5.010;\nuse Devel::Size qw/size/;\n\nmy @original = (1 .. 500);\nshow( 'original', \\@original );\n\nmy @pound = @original;\n$#pound = $#pound - 10;\nshow( 'pound', \\@pound );\n\nmy @splice = @original;\nsplice(@splice,-10);\nshow( 'splice', \\@splice);\n\nmy @delete = @original;\ndelete @delete[ -10 .. -1 ];\nshow( 'delete', \\@delete );\n\nmy @slice = @original[0 .. $#original - 10];\nshow( 'slice', \\@slice);\n\nsub show {\n my ($name, $ref) = @_;\n printf( \"%10s: length %4d => size %d\\n\", $name, scalar @$ref, size($ref));\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454/"
]
| How do I make an array shorter in Perl? I read some webpages indicating that I can assign:
```
$#ARRAY = 42;
```
I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work:
```
$#$ARRAY[$i] = 42;
``` | I'm not aware of assigning `$#ARRAY` being deprecated; `perldoc perldata` from 5.10.0 certainly says nothing about it. It is the fastest way to truncate an array.
If you want something a little more readable, use `splice`:
```
splice @ARRAY, 43;
```
(Note `43` instead of `42` - `$#ARRAY` gets you the last index of the array, whereas `splice` taks the *length* of the array instead).
As for working on arrays of arrays, I assume you mean being able to truncate a nested array via a reference? In that case, you want:
```
$#{$ARRAY->[7]} = 42;
```
or
```
splice @{$ARRAY->[7]}, 43;
``` |
92,860 | <p>What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this:</p>
<pre><code>MyPage.aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceholder" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnSomeEvent="MyUserControl_OnSomeEvent" />
MyUserControl.ascx.cs:
public partial class MyUserControl: UserControl
{
public event EventHandler SomeEvent;
....
private void OnSomething()
{
if (SomeEvent!= null)
SomeEvent(this, EventArgs.Empty);
}
</code></pre>
<p>Question is what is best practise?</p>
| [
{
"answer_id": 92930,
"author": "Matias Nino",
"author_id": 17235,
"author_profile": "https://Stackoverflow.com/users/17235",
"pm_score": 2,
"selected": false,
"text": "<p>1) Declare a Public event in the user control</p>\n\n<p>2) Issue a RaiseEvent where appropriate inside the user control</p>\n\n<p>3) In the Init event of the parent page, use AddHandler to assign the control.event to the the handling procedure you want to use</p>\n\n<p>Simple as that!</p>\n"
},
{
"answer_id": 92959,
"author": "Doug Moore",
"author_id": 13179,
"author_profile": "https://Stackoverflow.com/users/13179",
"pm_score": 4,
"selected": true,
"text": "<p>You would want to create an event on the control that is subscribed to in the parent. See <a href=\"http://www.odetocode.com/code/94.aspx\" rel=\"noreferrer\">OdeToCode</a> for an example.</p>\n\n<p>Here is the article for longevity sake:</p>\n\n<p>Some user controls are entirely self contained, for example, a user control displaying current stock quotes does not need to interact with any other content on the page. Other user controls will contain buttons to post back. Although it is possible to subscribe to the button click event from the containing page, doing so would break some of the object oriented rules of encapsulation. A better idea is to publish an event in the user control to allow any interested parties to handle the event.</p>\n\n<p>This technique is commonly referred to as “event bubbling” since the event can continue to pass through layers, starting at the bottom (the user control) and perhaps reaching the top level (the page) like a bubble moving up a champagne glass.</p>\n\n<p>For starters, let’s create a user control with a button attached.</p>\n\n<pre><code><%@ Control Language=\"c#\" AutoEventWireup=\"false\" \n Codebehind=\"WebUserControl1.ascx.cs\" \n Inherits=\"aspnet.eventbubble.WebUserControl1\" \n TargetSchema=\"http://schemas.microsoft.com/intellisense/ie5\"\n%>\n<asp:Panel id=\"Panel1\" runat=\"server\" Width=\"128px\" Height=\"96px\">\n WebUserControl1 \n <asp:Button id=\"Button1\" Text=\"Button\" runat=\"server\"/>\n</asp:Panel>\n</code></pre>\n\n<p>The code behind for the user control looks like the following.</p>\n\n<pre><code>public class WebUserControl1 : System.Web.UI.UserControl\n{\n protected System.Web.UI.WebControls.Button Button1;\n protected System.Web.UI.WebControls.Panel Panel1;\n\n private void Page_Load(object sender, System.EventArgs e)\n {\n Response.Write(\"WebUserControl1 :: Page_Load <BR>\");\n }\n\n private void Button1_Click(object sender, System.EventArgs e)\n {\n Response.Write(\"WebUserControl1 :: Begin Button1_Click <BR>\");\n OnBubbleClick(e);\n Response.Write(\"WebUserControl1 :: End Button1_Click <BR>\");\n }\n\n public event EventHandler BubbleClick;\n\n protected void OnBubbleClick(EventArgs e)\n {\n if(BubbleClick != null)\n {\n BubbleClick(this, e);\n }\n } \n\n #region Web Form Designer generated code\n override protected void OnInit(EventArgs e)\n {\n InitializeComponent();\n base.OnInit(e);\n }\n\n private void InitializeComponent()\n {\n this.Button1.Click += new System.EventHandler(this.Button1_Click);\n this.Load += new System.EventHandler(this.Page_Load);\n\n }\n #endregion\n\n}\n</code></pre>\n\n<p>The user control specifies a public event (BubbleClick) which declares a delegate. Anyone interested in the BubbleClick event can add an EventHandler method to execute when the event fires – just like the user control adds an EventHandler for when the Button fires the Click event.</p>\n\n<p>In the OnBubbleClick event, we first check to see if anyone has attached to the event (BubbleClick != null), we can then invoke all the event handling methods by calling BubbleClick, passing through the EventArgs parameter and setting the user control (this) as the event sender. Notice we are also using Response.Write to follow the flow of execution.</p>\n\n<p>An ASPX page can now put the user control to work.</p>\n\n<pre><code><%@ Register TagPrefix=\"ksa\" \n TagName=\"BubbleControl\" \n Src=\"WebUserControl1.ascx\" \n%>\n<%@ Page language=\"c#\" Codebehind=\"WebForm1.aspx.cs\" \n AutoEventWireup=\"false\" Inherits=\"aspnet.eventbubble.WebForm1\" \n%>\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" >\n<HTML>\n <HEAD>\n <title>WebForm1</title>\n </HEAD>\n <body MS_POSITIONING=\"GridLayout\">\n <form id=\"Form1\" method=\"post\" runat=\"server\">\n <ksa:BubbleControl id=\"BubbleControl\" runat=\"server\" />\n </form>\n </body>\n</HTML>\n</code></pre>\n\n<p>In the code behind for the page.</p>\n\n<pre><code>public class WebForm1 : System.Web.UI.Page\n{\n protected WebUserControl1 BubbleControl;\n\n private void Page_Load(object sender, System.EventArgs e)\n {\n Response.Write(\"WebForm1 :: Page_Load <BR>\");\n }\n\n #region Web Form Designer generated code\n override protected void OnInit(EventArgs e)\n {\n InitializeComponent();\n base.OnInit(e);\n }\n\n private void InitializeComponent()\n { \n this.Load += new System.EventHandler(this.Page_Load);\n BubbleControl.BubbleClick += new EventHandler(WebForm1_BubbleClick);\n }\n #endregion\n\n private void WebForm1_BubbleClick(object sender, EventArgs e)\n {\n Response.Write(\"WebForm1 :: WebForm1_BubbleClick from \" + \n sender.GetType().ToString() + \"<BR>\"); \n }\n}\n</code></pre>\n\n<p>Notice the parent page simply needs to add an event handler during InitializeComponent method. When we receive the event we will again use Reponse.Write to follow the flow of execution.</p>\n\n<p>One word of warning: if at anytime events mysteriously stop work, check the InitializeComponent method to make sure the designer has not removed any of the code adding event handlers.</p>\n"
},
{
"answer_id": 30356695,
"author": "Eric Barr",
"author_id": 1313642,
"author_profile": "https://Stackoverflow.com/users/1313642",
"pm_score": 0,
"selected": false,
"text": "<p>I found the same solution on OdeToCode that @lordscarlet linked to in his accepted solution. The problem was that I needed a solution in VB rather than C#. It didn't translate perfectly. Specifically, checking if the event handler is null in OnBubbleClick didn't work in VB because the compiler thought I was trying to call the event, and was giving an error that said \"... cannot be called directly. Use a 'RaiseEvent' statement to raise an event.\" So here's a VB translation for the OdeToCode solution, using a control called CountryDropDownList.</p>\n\n<p>For starters, let’s create a user control with a dropdown attached.</p>\n\n<pre><code><%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"CountryDropDownList.ascx.vb\" Inherits=\"CountryDropDownList\" %>\n<asp:DropDownList runat=\"server\" ID=\"ddlCountryList\" OnSelectedIndexChanged=\"ddlCountryList_SelectedIndexChanged\" AutoPostBack=\"true\">\n <asp:ListItem Value=\"\"></asp:ListItem>\n <asp:ListItem value=\"US\">United States</asp:ListItem>\n <asp:ListItem value=\"AF\">Afghanistan</asp:ListItem>\n <asp:ListItem value=\"AL\">Albania</asp:ListItem>\n</asp:DropDownList>\n</code></pre>\n\n<p>The code behind for the user control looks like the following.</p>\n\n<pre><code>Public Class CountryDropDownList\n Inherits System.Web.UI.UserControl\n Public Event SelectedCountryChanged As EventHandler\n\n Protected Sub ddlCountryList_SelectedIndexChanged(sender As Object, e As EventArgs)\n ' bubble the event up to the parent\n RaiseEvent SelectedCountryChanged(Me, e)\n End Sub\nEnd Class\n</code></pre>\n\n<p>An ASPX page can now put the user control to work. </p>\n\n<pre><code><%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"UpdateProfile.aspx.vb\" Inherits=\"UpdateProfile\" MaintainScrollPositionOnPostback=\"true\" %>\n<%@ Register Src=\"~/UserControls/CountryDropDownList.ascx\" TagPrefix=\"SO\" TagName=\"ucCountryDropDownList\" %>\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" >\n<HTML>\n <HEAD>\n <title>WebForm1</title>\n </HEAD>\n <body>\n <form id=\"Form1\" method=\"post\" runat=\"server\">\n <SO:ucCountryDropDownList id=\"ddlCountry\" runat=\"server\" />\n </form>\n </body>\n</HTML>\n</code></pre>\n\n<p>In the code behind for the page:</p>\n\n<pre><code>Protected Sub OnSelectedCountryChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedCountryChanged\n ' add your code here\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15555/"
]
| What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this:
```
MyPage.aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceholder" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnSomeEvent="MyUserControl_OnSomeEvent" />
MyUserControl.ascx.cs:
public partial class MyUserControl: UserControl
{
public event EventHandler SomeEvent;
....
private void OnSomething()
{
if (SomeEvent!= null)
SomeEvent(this, EventArgs.Empty);
}
```
Question is what is best practise? | You would want to create an event on the control that is subscribed to in the parent. See [OdeToCode](http://www.odetocode.com/code/94.aspx) for an example.
Here is the article for longevity sake:
Some user controls are entirely self contained, for example, a user control displaying current stock quotes does not need to interact with any other content on the page. Other user controls will contain buttons to post back. Although it is possible to subscribe to the button click event from the containing page, doing so would break some of the object oriented rules of encapsulation. A better idea is to publish an event in the user control to allow any interested parties to handle the event.
This technique is commonly referred to as “event bubbling” since the event can continue to pass through layers, starting at the bottom (the user control) and perhaps reaching the top level (the page) like a bubble moving up a champagne glass.
For starters, let’s create a user control with a button attached.
```
<%@ Control Language="c#" AutoEventWireup="false"
Codebehind="WebUserControl1.ascx.cs"
Inherits="aspnet.eventbubble.WebUserControl1"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5"
%>
<asp:Panel id="Panel1" runat="server" Width="128px" Height="96px">
WebUserControl1
<asp:Button id="Button1" Text="Button" runat="server"/>
</asp:Panel>
```
The code behind for the user control looks like the following.
```
public class WebUserControl1 : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Panel Panel1;
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("WebUserControl1 :: Page_Load <BR>");
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("WebUserControl1 :: Begin Button1_Click <BR>");
OnBubbleClick(e);
Response.Write("WebUserControl1 :: End Button1_Click <BR>");
}
public event EventHandler BubbleClick;
protected void OnBubbleClick(EventArgs e)
{
if(BubbleClick != null)
{
BubbleClick(this, e);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
```
The user control specifies a public event (BubbleClick) which declares a delegate. Anyone interested in the BubbleClick event can add an EventHandler method to execute when the event fires – just like the user control adds an EventHandler for when the Button fires the Click event.
In the OnBubbleClick event, we first check to see if anyone has attached to the event (BubbleClick != null), we can then invoke all the event handling methods by calling BubbleClick, passing through the EventArgs parameter and setting the user control (this) as the event sender. Notice we are also using Response.Write to follow the flow of execution.
An ASPX page can now put the user control to work.
```
<%@ Register TagPrefix="ksa"
TagName="BubbleControl"
Src="WebUserControl1.ascx"
%>
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="aspnet.eventbubble.WebForm1"
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<ksa:BubbleControl id="BubbleControl" runat="server" />
</form>
</body>
</HTML>
```
In the code behind for the page.
```
public class WebForm1 : System.Web.UI.Page
{
protected WebUserControl1 BubbleControl;
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("WebForm1 :: Page_Load <BR>");
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
BubbleControl.BubbleClick += new EventHandler(WebForm1_BubbleClick);
}
#endregion
private void WebForm1_BubbleClick(object sender, EventArgs e)
{
Response.Write("WebForm1 :: WebForm1_BubbleClick from " +
sender.GetType().ToString() + "<BR>");
}
}
```
Notice the parent page simply needs to add an event handler during InitializeComponent method. When we receive the event we will again use Reponse.Write to follow the flow of execution.
One word of warning: if at anytime events mysteriously stop work, check the InitializeComponent method to make sure the designer has not removed any of the code adding event handlers. |
92,862 | <p>In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded.</p>
<p>This list may be incomplete but, here are some of the operators that cannot be overloaded: </p>
<pre><code>!, not, &&, and, ||, or
</code></pre>
| [
{
"answer_id": 92905,
"author": "Farrel",
"author_id": 7889,
"author_profile": "https://Stackoverflow.com/users/7889",
"pm_score": 5,
"selected": true,
"text": "<p>Methods are overloadable, those are part of the language syntax.</p>\n"
},
{
"answer_id": 92922,
"author": "Joe Van Dyk",
"author_id": 17076,
"author_profile": "https://Stackoverflow.com/users/17076",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://ola-bini.blogspot.com/2007/10/operator-overloading-in-ruby.html?showComment=1191704640000#c7207705878073349200\" rel=\"noreferrer\">\"The && and || operators are not overloadable, mainly because they provide \"short circuit\" evaluation that cannot be reproduced with pure method calls.\"</a></p>\n\n<p>-- Jim Weirich</p>\n"
},
{
"answer_id": 92931,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": false,
"text": "<p>Yep. Operators are not overloadable. Only methods.</p>\n\n<p>Some operators are not really. They're sugar for methods. So <code>5 + 5</code> is really <code>5.+(5)</code>, and <code>foo[bar] = baz</code> is really <code>foo.[]=(bar, baz)</code>.</p>\n"
},
{
"answer_id": 98232,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 1,
"selected": false,
"text": "<p>And let's not forget about <code><<</code> for example:</p>\n\n<pre><code>string = \"test\"\nstring << \"ing\"\n</code></pre>\n\n<p>is the same as calling:</p>\n\n<pre><code>string.<<(\"ing\")\n</code></pre>\n"
},
{
"answer_id": 109347,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": false,
"text": "<p>In Ruby 1.9, the <code>!</code> operator is actually also a method and can be overriden. This only leaves <code>&&</code> and <code>||</code> and their low-precedence counterparts <code>and</code> and <code>or</code>.</p>\n\n<p>There's also some other \"combined operators\" that cannot be overriden, e.g. <code>a != b</code> is actually <code>!(a == b)</code> and <code>a += b</code> is actually <code>a = a+b</code>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167846/"
]
| In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded.
This list may be incomplete but, here are some of the operators that cannot be overloaded:
```
!, not, &&, and, ||, or
``` | Methods are overloadable, those are part of the language syntax. |
92,928 | <p>In Python for *nix, does <code>time.sleep()</code> block the thread or the process?</p>
| [
{
"answer_id": 92953,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 5,
"selected": false,
"text": "<p>Just the thread.</p>\n"
},
{
"answer_id": 92986,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 6,
"selected": false,
"text": "<p>It will just sleep the thread except in the case where your application has only a single thread, in which case it will sleep the thread and effectively the process as well.</p>\n<p>The python documentation on <a href=\"https://docs.python.org/3/library/time.html#time.sleep\" rel=\"noreferrer\"><code>sleep()</code></a> doesn't specify this however, so I can certainly understand the confusion!</p>\n"
},
{
"answer_id": 93069,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 4,
"selected": false,
"text": "<p>The thread will block, but the process is still alive.</p>\n\n<p>In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.</p>\n"
},
{
"answer_id": 93179,
"author": "Nick Bastin",
"author_id": 1502059,
"author_profile": "https://Stackoverflow.com/users/1502059",
"pm_score": 10,
"selected": true,
"text": "<p>It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to <code>floatsleep()</code>, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:</p>\n\n<pre><code>import time\nfrom threading import Thread\n\nclass worker(Thread):\n def run(self):\n for x in xrange(0,11):\n print x\n time.sleep(1)\n\nclass waiter(Thread):\n def run(self):\n for x in xrange(100,103):\n print x\n time.sleep(5)\n\ndef run():\n worker().start()\n waiter().start()\n</code></pre>\n\n<p>Which will print:</p>\n\n<pre><code>>>> thread_test.run()\n0\n100\n>>> 1\n2\n3\n4\n5\n101\n6\n7\n8\n9\n10\n102\n</code></pre>\n"
},
{
"answer_id": 32216136,
"author": "Ali Abbasinasab",
"author_id": 5199427,
"author_profile": "https://Stackoverflow.com/users/5199427",
"pm_score": 2,
"selected": false,
"text": "<p>Only the thread unless your process has a single thread.</p>\n"
},
{
"answer_id": 40313394,
"author": "Denis The Menace",
"author_id": 628633,
"author_profile": "https://Stackoverflow.com/users/628633",
"pm_score": 2,
"selected": false,
"text": "<p>Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can't pause the process at all. It is simply not applicable to process.</p>\n"
},
{
"answer_id": 59821834,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>it blocks a thread if it is executed in the same thread not if it is executed from the main code</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17732/"
]
| In Python for \*nix, does `time.sleep()` block the thread or the process? | It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to `floatsleep()`, the substantive part of the sleep operation is wrapped in a Py\_BEGIN\_ALLOW\_THREADS and Py\_END\_ALLOW\_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
```
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
```
Which will print:
```
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
``` |
92,936 | <p>I want to use small flex charts with just 3 labels, for example a chart over the past 2 hours , with 3 horizontal label, as shown below:</p>
<pre><code> | | |
9:46 10:46 11:46
</code></pre>
<p>(of course, there are more than 3 values to display!)</p>
<p>I have been told this is not trivial, but how would you do it? </p>
<p>Also, do you know of any books that present how to achieve sophisticated layouts in Flex? The books I have found are code-oriented and usually limit formatting to a minimum, and it's not always straightforward to connect the names of attributes to what you are trying to do.</p>
| [
{
"answer_id": 104491,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look in the online <a href=\"http://livedocs.adobe.com/flex/3/langref/index.html\" rel=\"nofollow noreferrer\">Flex Language Guide</a> at the <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/charts/AxisRenderer.html\" rel=\"nofollow noreferrer\">AxisRenderer</a> class. </p>\n\n<p>It also has some helpful sample code and output.</p>\n"
},
{
"answer_id": 124964,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at the CategoryAxis type? Using this you can explicitly set the labels.</p>\n"
},
{
"answer_id": 126977,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 0,
"selected": false,
"text": "<p>I think you need \"[Bindable]\" before every variable you want to use as a dataProvider, so one more before <em>labels</em>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to use small flex charts with just 3 labels, for example a chart over the past 2 hours , with 3 horizontal label, as shown below:
```
| | |
9:46 10:46 11:46
```
(of course, there are more than 3 values to display!)
I have been told this is not trivial, but how would you do it?
Also, do you know of any books that present how to achieve sophisticated layouts in Flex? The books I have found are code-oriented and usually limit formatting to a minimum, and it's not always straightforward to connect the names of attributes to what you are trying to do. | Take a look in the online [Flex Language Guide](http://livedocs.adobe.com/flex/3/langref/index.html) at the [AxisRenderer](http://livedocs.adobe.com/flex/3/langref/mx/charts/AxisRenderer.html) class.
It also has some helpful sample code and output. |
92,971 | <p>I'm trying to detect the size of the screen I'm starting emacs on, and adjust the size and position the window it is starting in (I guess that's the frame in emacs-speak) accordingly. I'm trying to set up my .emacs so that I always get a "reasonably-big" window with it's top-left corner near the top-left of my screen.</p>
<p>I guess this is a <em>big</em> ask for the general case, so to narrow things down a bit I'm most interested in GNU Emacs 22 on Windows and (Debian) Linux.</p>
| [
{
"answer_id": 93005,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>(setq initial-frame-alist\n (append '((width . 263) (height . 112) (top . -5) (left . 5) (font . \"4.System VIO\"))\n initial-frame-alist))\n\n(setq default-frame-alist\n (append '((width . 263) (height . 112) (top . -5) (left . 5) (font . \"4.System VIO\"))\n default-frame-alist))\n</code></pre>\n"
},
{
"answer_id": 93019,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Taken from: <a href=\"http://www.gnu.org/software/emacs/windows/old/faq4.html\" rel=\"noreferrer\">http://www.gnu.org/software/emacs/windows/old/faq4.html</a></p>\n\n<pre><code>(setq default-frame-alist\n '((top . 200) (left . 400)\n (width . 80) (height . 40)\n (cursor-color . \"white\")\n (cursor-type . box)\n (foreground-color . \"yellow\")\n (background-color . \"black\")\n (font . \"-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1\")))\n\n(setq initial-frame-alist '((top . 10) (left . 30)))\n</code></pre>\n\n<p>The first setting applies to all emacs frames including the first one that pops up when you start. The second setting adds additional attributes to the first frame. This is because it is sometimes nice to know the original frame that you start emacs in.</p>\n"
},
{
"answer_id": 93084,
"author": "JB.",
"author_id": 12274,
"author_profile": "https://Stackoverflow.com/users/12274",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest way I've found to do that in an X-Window environment is through <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Table-of-Resources.html#Table-of-Resources\" rel=\"noreferrer\">X resources</a>. The relevant part of my .Xdefaults looks like this:</p>\n\n<pre><code>Emacs.geometry: 80x70\n</code></pre>\n\n<p>You should be able to suffix it with +0+0 location coordinates to force it to the upper-left corner of your display. (the reason I don't do it is that I occasionnally spawn new frames, and it makes things confusing if they appear in the exact same location as the previous one)</p>\n\n<p>According to the manual, <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/MS_002dWindows-Registry.html#MS_002dWindows-Registry\" rel=\"noreferrer\">this technique works on MS Windows too</a>, storing the resources as key/value pairs in the registry. I never tested that. It might be great, it might be much more of an inconvenience compared to simply editing a file.</p>\n"
},
{
"answer_id": 94172,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": false,
"text": "<p>I've got the following in my <code>.emacs</code>:</p>\n\n<pre><code>(if (window-system)\n (set-frame-height (selected-frame) 60))\n</code></pre>\n\n<p>You might also look at the functions <code>set-frame-size</code>, <code>set-frame-position</code>, and <code>set-frame-width</code>. Use <code>C-h f</code> (aka <code>M-x describe-function</code>) to bring up detailed documentation.</p>\n\n<p>I'm not sure if there's a way to compute the max height/width of a frame in the current windowing environment.</p>\n"
},
{
"answer_id": 94277,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 7,
"selected": true,
"text": "<p>If you want to change the size according to resolution you can do something like this (adjusting the preferred width and resolutions according to your specific needs):</p>\n\n<pre><code>(defun set-frame-size-according-to-resolution ()\n (interactive)\n (if window-system\n (progn\n ;; use 120 char wide window for largeish displays\n ;; and smaller 80 column windows for smaller displays\n ;; pick whatever numbers make sense for you\n (if (> (x-display-pixel-width) 1280)\n (add-to-list 'default-frame-alist (cons 'width 120))\n (add-to-list 'default-frame-alist (cons 'width 80)))\n ;; for the height, subtract a couple hundred pixels\n ;; from the screen height (for panels, menubars and\n ;; whatnot), then divide by the height of a char to\n ;; get the height we want\n (add-to-list 'default-frame-alist \n (cons 'height (/ (- (x-display-pixel-height) 200)\n (frame-char-height)))))))\n\n(set-frame-size-according-to-resolution)\n</code></pre>\n\n<p>Note that window-system is deprecated in newer versions of emacs. A suitable replacement is <code>(display-graphic-p)</code>. See <a href=\"https://stackoverflow.com/a/5795518/7432\">this answer</a> to the question <a href=\"https://stackoverflow.com/questions/5795451/how-to-detect-that-emacs-is-in-terminal-mode\">How to detect that emacs is in terminal-mode?</a> for a little more background. </p>\n"
},
{
"answer_id": 94329,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": false,
"text": "<p>You can also the -geometry parameter when firing up emacs: <code>emacs -geometry 80x60+20+30</code> will give you a window 80 characters wide, 60 rows high, with the top left corner 20 pixels to the right and 30 pixels down from the top left corner of the background.</p>\n"
},
{
"answer_id": 3538748,
"author": "Jérôme Radix",
"author_id": 3673,
"author_profile": "https://Stackoverflow.com/users/3673",
"pm_score": 3,
"selected": false,
"text": "<p>On windows, you could make emacs frame maximized using this function :</p>\n\n<pre><code>(defun w32-maximize-frame ()\n \"Maximize the current frame\"\n (interactive)\n (w32-send-sys-command 61488))\n</code></pre>\n"
},
{
"answer_id": 7660628,
"author": "ftravers",
"author_id": 408489,
"author_profile": "https://Stackoverflow.com/users/408489",
"pm_score": 3,
"selected": false,
"text": "<p>On ubuntu do:</p>\n\n<pre><code>(defun toggle-fullscreen ()\n (interactive)\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_VERT\" 0))\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_HORZ\" 0))\n)\n(toggle-fullscreen)\n</code></pre>\n"
},
{
"answer_id": 11912263,
"author": "WisdomFusion",
"author_id": 191071,
"author_profile": "https://Stackoverflow.com/users/191071",
"pm_score": 1,
"selected": false,
"text": "<pre><code>(defun set-frame-size-according-to-resolution ()\n (interactive)\n (if window-system\n (progn\n ;; use 120 char wide window for largeish displays\n ;; and smaller 80 column windows for smaller displays\n ;; pick whatever numbers make sense for you\n (if (> (x-display-pixel-width) 1280)\n (add-to-list 'default-frame-alist (cons 'width 120))\n (add-to-list 'default-frame-alist (cons 'width 80)))\n ;; for the height, subtract a couple hundred pixels\n ;; from the screen height (for panels, menubars and\n ;; whatnot), then divide by the height of a char to\n ;; get the height we want\n (add-to-list 'default-frame-alist \n (cons 'height (/ (- (x-display-pixel-height) 200)\n (frame-char-height)))))))\n\n(set-frame-size-according-to-resolution)\n</code></pre>\n\n<p>I prefer Bryan Oakley's settings. However the <strong>'height</strong> not work properly in my GNU Emacs 24.1.1.</p>\n"
},
{
"answer_id": 12334932,
"author": "norbux",
"author_id": 1657376,
"author_profile": "https://Stackoverflow.com/users/1657376",
"pm_score": 4,
"selected": false,
"text": "<p>Try adding the following code to <code>.emacs</code></p>\n\n<pre><code>(add-to-list 'default-frame-alist '(height . 24))\n\n(add-to-list 'default-frame-alist '(width . 80)) \n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402/"
]
| I'm trying to detect the size of the screen I'm starting emacs on, and adjust the size and position the window it is starting in (I guess that's the frame in emacs-speak) accordingly. I'm trying to set up my .emacs so that I always get a "reasonably-big" window with it's top-left corner near the top-left of my screen.
I guess this is a *big* ask for the general case, so to narrow things down a bit I'm most interested in GNU Emacs 22 on Windows and (Debian) Linux. | If you want to change the size according to resolution you can do something like this (adjusting the preferred width and resolutions according to your specific needs):
```
(defun set-frame-size-according-to-resolution ()
(interactive)
(if window-system
(progn
;; use 120 char wide window for largeish displays
;; and smaller 80 column windows for smaller displays
;; pick whatever numbers make sense for you
(if (> (x-display-pixel-width) 1280)
(add-to-list 'default-frame-alist (cons 'width 120))
(add-to-list 'default-frame-alist (cons 'width 80)))
;; for the height, subtract a couple hundred pixels
;; from the screen height (for panels, menubars and
;; whatnot), then divide by the height of a char to
;; get the height we want
(add-to-list 'default-frame-alist
(cons 'height (/ (- (x-display-pixel-height) 200)
(frame-char-height)))))))
(set-frame-size-according-to-resolution)
```
Note that window-system is deprecated in newer versions of emacs. A suitable replacement is `(display-graphic-p)`. See [this answer](https://stackoverflow.com/a/5795518/7432) to the question [How to detect that emacs is in terminal-mode?](https://stackoverflow.com/questions/5795451/how-to-detect-that-emacs-is-in-terminal-mode) for a little more background. |
92,984 | <p>A friend of mine and I were having a discussion regarding currying and partial function application in Javascript, and we came to very different conclusions as to whether either were achievable. I came up with this implementation of <code>Function.prototype.curry</code>, which was the basis of our discussion:</p>
<pre><code>Function.prototype.curry = function() {
if (!arguments.length) return this;
var args = Array.prototype.slice.apply(arguments);
var mmm_curry = this, args;
return function() {
var inner_args = Array.prototype.slice.apply(arguments);
return mmm_curry.apply(this, args.concat(inner_args));
}
}
</code></pre>
<p>Which is used as follows:</p>
<pre><code>var vindaloo = function(a, b) {
return (a + b);
}
var karahi = vindaloo.curry(1);
var masala = karahi(2);
var gulai = karahi(3);
print(masala);
print(other);
</code></pre>
<p>The output of which is as follows in Spidermonkey:</p>
<pre><code>$ js curry.js
3
4
</code></pre>
<p>His opinion was that since the Javascript <code>function</code> primitive does not natively support "partial function application", it's completely wrong to refer to the function bound to the variable <code>karahi</code> as partially applied. His argument was that when the <code>vindaloo</code> function is curried, the function itself is completely applied and a closure is returned, not a "partially applied function".</p>
<p>Now, my opinion is that while Javascript itself does not provide support for partial application in its' <code>function</code> primitives (unlike say, ML or Haskell), that doesn't mean you can't create a higher order function of the language which is capable of encapsulating concept of a partially applied function. Also, despite being "applied", the scope of the function is still bound to the closure returned by it causing it to remain "partially applied".</p>
<p>Which is correct?</p>
| [
{
"answer_id": 93191,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 0,
"selected": false,
"text": "<p>You should check out <a href=\"http://www.svendtofte.com/code/curried_javascript/\" rel=\"nofollow noreferrer\">Curried JavaScript Functions</a>. I haven't completely wrapped my head around his curry function, but it might have your answer.</p>\n\n<p>Edit: I would agree with your assessment, however.</p>\n"
},
{
"answer_id": 93203,
"author": "Rene Saarsoo",
"author_id": 15982,
"author_profile": "https://Stackoverflow.com/users/15982",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's perfectly OK to talk about partial function application\nin JavaScript - if it works like partial application, then it must\nbe one. How else would you name it?</p>\n\n<p>How your <em>curry</em> function accomplishes his goal is just an implementation\ndetail. In a similar way we could have partial application in the ECMAScript spec,\nbut when IE would then implement it just as you did, you would have\nno way to find out.</p>\n"
},
{
"answer_id": 93243,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 3,
"selected": true,
"text": "<p>Technically you're creating a brand new function that calls the original function. So if my understanding of partially applied functions is correct, this is not a partially applied function. A partially applied function would be closer to this (note that this isn't a general solution):</p>\n\n<pre><code>vindaloo.curry = function(a) {\n return function(b) {\n return a + b;\n };\n};\n</code></pre>\n\n<p>IIUC, this still wouldn't be a partially applied function. But it's closer. A true partially applied function would actually look like this if you can examine the code:</p>\n\n<pre><code>function karahi(b) {\n return 1 + b;\n};\n</code></pre>\n\n<p>So, technically, your original method <em>is</em> just returning a function bound within a closure. The only way I can think of to truly partially apply a function in JavaScript would be to parse the function, apply the changes, and then run it through an eval().</p>\n\n<p>However, your solution is a good practical application of the concept to JavaScript, so practically speaking accomplishes the goal, even if it is not technically exact.</p>\n"
},
{
"answer_id": 93677,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "<p>The technical details don't matter to me - if the semantics remain the same and, for all intents and purposes, the function acts as if it were really a partially-applied function, who cares? </p>\n\n<p>I used to be as academic about things, but worrying about such particulars doesn't get real work done in the end.</p>\n\n<p>Personally, I use <a href=\"http://www.mochikit.com\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a>; it has a nice partial() function which assists in the creation of such. I loves it.</p>\n"
},
{
"answer_id": 36359346,
"author": "risto",
"author_id": 1589324,
"author_profile": "https://Stackoverflow.com/users/1589324",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>His opinion was that since the Javascript function primitive does not natively support \"partial function application\"</p>\n</blockquote>\n\n<p>You can do currying in ES6 pretty elegantly:</p>\n\n<pre><code>> const add = a => b => a + b\n> const add10 = add(10)\n> [1,2,3].map(add10)\n[ 11, 12, 13 ]\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/92984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109/"
]
| A friend of mine and I were having a discussion regarding currying and partial function application in Javascript, and we came to very different conclusions as to whether either were achievable. I came up with this implementation of `Function.prototype.curry`, which was the basis of our discussion:
```
Function.prototype.curry = function() {
if (!arguments.length) return this;
var args = Array.prototype.slice.apply(arguments);
var mmm_curry = this, args;
return function() {
var inner_args = Array.prototype.slice.apply(arguments);
return mmm_curry.apply(this, args.concat(inner_args));
}
}
```
Which is used as follows:
```
var vindaloo = function(a, b) {
return (a + b);
}
var karahi = vindaloo.curry(1);
var masala = karahi(2);
var gulai = karahi(3);
print(masala);
print(other);
```
The output of which is as follows in Spidermonkey:
```
$ js curry.js
3
4
```
His opinion was that since the Javascript `function` primitive does not natively support "partial function application", it's completely wrong to refer to the function bound to the variable `karahi` as partially applied. His argument was that when the `vindaloo` function is curried, the function itself is completely applied and a closure is returned, not a "partially applied function".
Now, my opinion is that while Javascript itself does not provide support for partial application in its' `function` primitives (unlike say, ML or Haskell), that doesn't mean you can't create a higher order function of the language which is capable of encapsulating concept of a partially applied function. Also, despite being "applied", the scope of the function is still bound to the closure returned by it causing it to remain "partially applied".
Which is correct? | Technically you're creating a brand new function that calls the original function. So if my understanding of partially applied functions is correct, this is not a partially applied function. A partially applied function would be closer to this (note that this isn't a general solution):
```
vindaloo.curry = function(a) {
return function(b) {
return a + b;
};
};
```
IIUC, this still wouldn't be a partially applied function. But it's closer. A true partially applied function would actually look like this if you can examine the code:
```
function karahi(b) {
return 1 + b;
};
```
So, technically, your original method *is* just returning a function bound within a closure. The only way I can think of to truly partially apply a function in JavaScript would be to parse the function, apply the changes, and then run it through an eval().
However, your solution is a good practical application of the concept to JavaScript, so practically speaking accomplishes the goal, even if it is not technically exact. |
93,039 | <p>In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:</p>
<pre><code>
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);
} }
</code></pre>
<p>If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.</p>
<p>But where is the storage allocated?</p>
<p>To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I <em>believe</em> that there <strong>has</strong> to be some space reserved in the executable file for those static variables.<br>
For discussion purposes, lets assume we use the GCC toolchain.</p>
| [
{
"answer_id": 93079,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 5,
"selected": false,
"text": "<p>The storage location of the data will be implementation dependent.</p>\n\n<p>However, the meaning of <strong>static</strong> is \"internal linkage\". Thus, the symbol is <em>internal</em> to the compilation unit (foo.c, bar.c) and cannot be referenced outside that compilation unit. So, there can be no name collisions.</p>\n"
},
{
"answer_id": 93081,
"author": "trotterdylan",
"author_id": 17695,
"author_profile": "https://Stackoverflow.com/users/17695",
"pm_score": 3,
"selected": false,
"text": "<p>It depends on the platform and compiler that you're using. Some compilers store directly in the code segment. Static variables are always only accessible to the current translation unit and the names are not exported thus the reason name collisions never occur.</p>\n"
},
{
"answer_id": 93092,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>The answer might very well depend on the compiler, so you probably want to edit your question (I mean, even the notion of segments is not mandated by ISO C nor ISO C++). For instance, on Windows an executable doesn't carry symbol names. One 'foo' would be offset 0x100, the other perhaps 0x2B0, and code from both translation units is compiled knowing the offsets for \"their\" foo.</p>\n"
},
{
"answer_id": 93103,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>I don't believe there will be a collision. Using static at the file level (outside functions) marks the variable as local to the current compilation unit (file). It's never visible outside the current file so never has to have a name that can be used externally.</p>\n\n<p>Using static <em>inside</em> a function is different - the variable is only visible to the function (whether static or not), it's just its value is preserved across calls to that function.</p>\n\n<p>In effect, static does two different things depending on where it is. In <em>both</em> cases however, the variable visibility is limited in such a way that you can easily prevent namespace clashes when linking.</p>\n\n<p>Having said that, I believe it would be stored in the <code>DATA</code> section, which tends to have variables that are initialized to values other than zero. This is, of course, an implementation detail, not something mandated by the standard - it only cares about <em>behaviour,</em> not how things are done under the covers.</p>\n"
},
{
"answer_id": 93138,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 0,
"selected": false,
"text": "<p>they're both going to be stored independently, however if you want to make it clear to other developers you might want to wrap them up in namespaces.</p>\n"
},
{
"answer_id": 93188,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 4,
"selected": false,
"text": "<p>in the \"global and static\" area :)</p>\n\n<p>There are several memory areas in C++:</p>\n\n<ul>\n<li>heap</li>\n<li>free store</li>\n<li>stack</li>\n<li>global & static</li>\n<li>const</li>\n</ul>\n\n<p>See <a href=\"http://www.gotw.ca/gotw/009.htm\" rel=\"nofollow noreferrer\">here</a> for a detailed answer to your question:</p>\n\n<blockquote>\n <p>The following summarizes a C++ program's major distinct memory areas. Note that some of the names (e.g., \"heap\") do not appear as such in the draft [standard].</p>\n</blockquote>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code> Memory Area Characteristics and Object Lifetimes\n -------------- ------------------------------------------------\n\n Const Data The const data area stores string literals and\n other data whose values are known at compile\n time. No objects of class type can exist in\n this area. All data in this area is available\n during the entire lifetime of the program.\n\n Further, all of this data is read-only, and the\n results of trying to modify it are undefined.\n This is in part because even the underlying\n storage format is subject to arbitrary\n optimization by the implementation. For\n example, a particular compiler may store string\n literals in overlapping objects if it wants to.\n\n\n Stack The stack stores automatic variables. Typically\n allocation is much faster than for dynamic\n storage (heap or free store) because a memory\n allocation involves only pointer increment\n rather than more complex management. Objects\n are constructed immediately after memory is\n allocated and destroyed immediately before\n memory is deallocated, so there is no\n opportunity for programmers to directly\n manipulate allocated but uninitialized stack\n space (barring willful tampering using explicit\n dtors and placement new).\n\n\n Free Store The free store is one of the two dynamic memory\n areas, allocated/freed by new/delete. Object\n lifetime can be less than the time the storage\n is allocated; that is, free store objects can\n have memory allocated without being immediately\n initialized, and can be destroyed without the\n memory being immediately deallocated. During\n the period when the storage is allocated but\n outside the object's lifetime, the storage may\n be accessed and manipulated through a void* but\n none of the proto-object's nonstatic members or\n member functions may be accessed, have their\n addresses taken, or be otherwise manipulated.\n\n\n Heap The heap is the other dynamic memory area,\n allocated/freed by malloc/free and their\n variants. Note that while the default global\n new and delete might be implemented in terms of\n malloc and free by a particular compiler, the\n heap is not the same as free store and memory\n allocated in one area cannot be safely\n deallocated in the other. Memory allocated from\n the heap can be used for objects of class type\n by placement-new construction and explicit\n destruction. If so used, the notes about free\n store object lifetime apply similarly here.\n\n\n Global/Static Global or static variables and objects have\n their storage allocated at program startup, but\n may not be initialized until after the program\n has begun executing. For instance, a static\n variable in a function is initialized only the\n first time program execution passes through its\n definition. The order of initialization of\n global variables across translation units is not\n defined, and special care is needed to manage\n dependencies between global objects (including\n class statics). As always, uninitialized proto-\n objects' storage may be accessed and manipulated\n through a void* but no nonstatic members or\n member functions may be used or referenced\n outside the object's actual lifetime.\n</code></pre>\n"
},
{
"answer_id": 93352,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 2,
"selected": false,
"text": "<p>static variable stored in data segment or code segment as mentioned before.<br>\nYou can be sure that it will not be allocated on stack or heap.<br>\nThere is no risk for collision since <code>static</code> keyword define the scope of the variable to be a file or function, in case of collision there is a compiler/linker to warn you about.<br>\nA nice <a href=\"http://faq.zanvar.in/storage-of-static-variable/\" rel=\"nofollow noreferrer\">example</a></p>\n"
},
{
"answer_id": 93411,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 8,
"selected": true,
"text": "<p>Where your statics go depends on whether they are <em>zero-initialized</em>. <em>zero-initialized</em> static data goes in <a href=\"http://en.wikipedia.org/wiki/.bss\" rel=\"noreferrer\">.BSS (Block Started by Symbol)</a>, <em>non-zero-initialized</em> data goes in <a href=\"http://en.wikipedia.org/wiki/Data_segment\" rel=\"noreferrer\">.DATA</a></p>\n"
},
{
"answer_id": 96545,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 3,
"selected": false,
"text": "<p>Data declared in a compilation unit will go into the .BSS or the .Data of that files output. Initialised data in BSS, uninitalised in DATA.</p>\n\n<p>The difference between static and global data comes in the inclusion of symbol information in the file. Compilers tend to include the symbol information but only mark the global information as such.</p>\n\n<p>The linker respects this information. The symbol information for the static variables is either discarded or mangled so that static variables can still be referenced in some way (with debug or symbol options). In neither case can the compilation units gets affected as the linker resolves local references first.</p>\n"
},
{
"answer_id": 109120,
"author": "yogeesh",
"author_id": 9030,
"author_profile": "https://Stackoverflow.com/users/9030",
"pm_score": 5,
"selected": false,
"text": "<p>In fact, a variable is tuple (storage, scope, type, address, value):</p>\n\n<pre><code>storage : where is it stored, for example data, stack, heap...\nscope : who can see us, for example global, local...\ntype : what is our type, for example int, int*...\naddress : where are we located\nvalue : what is our value\n</code></pre>\n\n<p>Local scope could mean local to either the translational unit (source file), the function or the block depending on where its defined. To make variable visible to more than one function, it definitely has to be in either DATA or the BSS area (depending on whether its initialized explicitly or not, respectively). Its then scoped accordingly to either all function(s) or function(s) within source file.</p>\n"
},
{
"answer_id": 5371529,
"author": "lukmac",
"author_id": 555951,
"author_profile": "https://Stackoverflow.com/users/555951",
"pm_score": 1,
"selected": false,
"text": "<p>Well this question is bit too old, but since nobody points out any useful information:\nCheck the post by 'mohit12379' explaining the store of static variables with same name in the symbol table: \n<a href=\"http://www.geekinterview.com/question_details/24745\" rel=\"nofollow\">http://www.geekinterview.com/question_details/24745</a></p>\n"
},
{
"answer_id": 11698458,
"author": "karn",
"author_id": 1395802,
"author_profile": "https://Stackoverflow.com/users/1395802",
"pm_score": 7,
"selected": false,
"text": "<p>When a program is loaded into memory, it’s organized into different segments. One of the segment is <b>DATA segment</b>. The Data segment is further sub-divided into two parts:</p>\n<ul>\n<li><b> Initialized data segment: </b> All the global, static and constant data are stored here.</li>\n<li><b> Uninitialized data segment (BSS): </b> All the uninitialized data are stored in this segment.</li>\n</ul>\n<p>Here is a diagram to explain this concept:</p>\n<p><img src=\"https://i.stack.imgur.com/JQjKp.png\" alt=\"enter image description here\" /></p>\n<p>Here is very good link explaining these concepts: <a href=\"https://web.archive.org/web/20170829060314/http://www.inf.udec.cl/%7Eleo/teoX.pdf\" rel=\"noreferrer\">Memory Management in C: The Heap and the Stack</a></p>\n"
},
{
"answer_id": 24484939,
"author": "Anurag Bhakuni",
"author_id": 3767017,
"author_profile": "https://Stackoverflow.com/users/3767017",
"pm_score": -1,
"selected": false,
"text": "<p>you already know either it store in bss(block start by symbol) also referred as uninitialized data segment or in initialized data segment.</p>\n\n<p>lets take an simple example</p>\n\n<pre><code>void main(void)\n{\nstatic int i;\n}\n</code></pre>\n\n<p>the above static variable is not initialized , so it goes to uninitialized data segment(bss).</p>\n\n<pre><code>void main(void)\n{\nstatic int i=10;\n}\n</code></pre>\n\n<p>and of course it initialized by 10 so it goes to initialized data segment. </p>\n"
},
{
"answer_id": 26345806,
"author": "Dan",
"author_id": 173611,
"author_profile": "https://Stackoverflow.com/users/173611",
"pm_score": 2,
"selected": false,
"text": "<p>I tried it with objdump and gdb, here is the result what I get:</p>\n\n<pre><code>(gdb) disas fooTest\nDump of assembler code for function fooTest:\n 0x000000000040052d <+0>: push %rbp\n 0x000000000040052e <+1>: mov %rsp,%rbp\n 0x0000000000400531 <+4>: mov 0x200b09(%rip),%eax # 0x601040 <foo>\n 0x0000000000400537 <+10>: add $0x1,%eax\n 0x000000000040053a <+13>: mov %eax,0x200b00(%rip) # 0x601040 <foo>\n 0x0000000000400540 <+19>: mov 0x200afe(%rip),%eax # 0x601044 <bar.2180>\n 0x0000000000400546 <+25>: add $0x1,%eax\n 0x0000000000400549 <+28>: mov %eax,0x200af5(%rip) # 0x601044 <bar.2180>\n 0x000000000040054f <+34>: mov 0x200aef(%rip),%edx # 0x601044 <bar.2180>\n 0x0000000000400555 <+40>: mov 0x200ae5(%rip),%eax # 0x601040 <foo>\n 0x000000000040055b <+46>: mov %eax,%esi\n 0x000000000040055d <+48>: mov $0x400654,%edi\n 0x0000000000400562 <+53>: mov $0x0,%eax\n 0x0000000000400567 <+58>: callq 0x400410 <printf@plt>\n 0x000000000040056c <+63>: pop %rbp\n 0x000000000040056d <+64>: retq \nEnd of assembler dump.\n\n(gdb) disas barTest\nDump of assembler code for function barTest:\n 0x000000000040056e <+0>: push %rbp\n 0x000000000040056f <+1>: mov %rsp,%rbp\n 0x0000000000400572 <+4>: mov 0x200ad0(%rip),%eax # 0x601048 <foo>\n 0x0000000000400578 <+10>: add $0x1,%eax\n 0x000000000040057b <+13>: mov %eax,0x200ac7(%rip) # 0x601048 <foo>\n 0x0000000000400581 <+19>: mov 0x200ac5(%rip),%eax # 0x60104c <bar.2180>\n 0x0000000000400587 <+25>: add $0x1,%eax\n 0x000000000040058a <+28>: mov %eax,0x200abc(%rip) # 0x60104c <bar.2180>\n 0x0000000000400590 <+34>: mov 0x200ab6(%rip),%edx # 0x60104c <bar.2180>\n 0x0000000000400596 <+40>: mov 0x200aac(%rip),%eax # 0x601048 <foo>\n 0x000000000040059c <+46>: mov %eax,%esi\n 0x000000000040059e <+48>: mov $0x40065c,%edi\n 0x00000000004005a3 <+53>: mov $0x0,%eax\n 0x00000000004005a8 <+58>: callq 0x400410 <printf@plt>\n 0x00000000004005ad <+63>: pop %rbp\n 0x00000000004005ae <+64>: retq \nEnd of assembler dump.\n</code></pre>\n\n<p>here is the objdump result</p>\n\n<pre><code>Disassembly of section .data:\n\n0000000000601030 <__data_start>:\n ...\n\n0000000000601038 <__dso_handle>:\n ...\n\n0000000000601040 <foo>:\n 601040: 01 00 add %eax,(%rax)\n ...\n\n0000000000601044 <bar.2180>:\n 601044: 02 00 add (%rax),%al\n ...\n\n0000000000601048 <foo>:\n 601048: 0a 00 or (%rax),%al\n ...\n\n000000000060104c <bar.2180>:\n 60104c: 14 00 adc $0x0,%al\n</code></pre>\n\n<p>So, that's to say, your four variables are located in data section event the the same name, but with different offset.</p>\n"
},
{
"answer_id": 30642087,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "<p><strong>How to find it yourself with <code>objdump -Sr</code></strong></p>\n\n<p>To actually understand what is going on, you must understand linker relocation. If you've never touched that, consider <a href=\"https://stackoverflow.com/a/30507725/895245\">reading this post first</a>.</p>\n\n<p>Let's analyze a Linux x86-64 ELF example to see it ourselves:</p>\n\n<pre><code>#include <stdio.h>\n\nint f() {\n static int i = 1;\n i++;\n return i;\n}\n\nint main() {\n printf(\"%d\\n\", f());\n printf(\"%d\\n\", f());\n return 0;\n}\n</code></pre>\n\n<p>Compile with:</p>\n\n<pre><code>gcc -ggdb -c main.c\n</code></pre>\n\n<p>Decompile the code with:</p>\n\n<pre><code>objdump -Sr main.o\n</code></pre>\n\n<ul>\n<li><code>-S</code> decompiles the code with the original source intermingled</li>\n<li><code>-r</code> shows relocation information</li>\n</ul>\n\n<p>Inside the decompilation of <code>f</code> we see:</p>\n\n<pre><code> static int i = 1;\n i++;\n4: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # a <f+0xa>\n 6: R_X86_64_PC32 .data-0x4\n</code></pre>\n\n<p>and the <code>.data-0x4</code> says that it will go to the first byte of the <code>.data</code> segment.</p>\n\n<p>The <code>-0x4</code> is there because we are using RIP relative addressing, thus the <code>%rip</code> in the instruction and <code>R_X86_64_PC32</code>.</p>\n\n<p>It is required because RIP points to the <em>following</em> instruction, which starts 4 bytes after <code>00 00 00 00</code> which is what will get relocated. I have explained this in more detail at: <a href=\"https://stackoverflow.com/a/30515926/895245\">https://stackoverflow.com/a/30515926/895245</a></p>\n\n<p>Then, if we modify the source to <code>i = 1</code> and do the same analysis, we conclude that:</p>\n\n<ul>\n<li><code>static int i = 0</code> goes on <code>.bss</code></li>\n<li><code>static int i = 1</code> goes on <code>.data</code></li>\n</ul>\n"
},
{
"answer_id": 49234040,
"author": "Yousha Aleayoub",
"author_id": 1429432,
"author_profile": "https://Stackoverflow.com/users/1429432",
"pm_score": 4,
"selected": false,
"text": "<p>This is how (easy to understand):</p>\n\n<p><a href=\"https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg\" rel=\"noreferrer\"><img src=\"https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg\" alt=\"stack, heap and static data\"></a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
| In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:
```
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);
} }
```
If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.
But where is the storage allocated?
To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I *believe* that there **has** to be some space reserved in the executable file for those static variables.
For discussion purposes, lets assume we use the GCC toolchain. | Where your statics go depends on whether they are *zero-initialized*. *zero-initialized* static data goes in [.BSS (Block Started by Symbol)](http://en.wikipedia.org/wiki/.bss), *non-zero-initialized* data goes in [.DATA](http://en.wikipedia.org/wiki/Data_segment) |
93,056 | <p>this should be simple...could someone provide me a simple code sample that has an aspx page hosting both a silverlight app (consisting of, say a button) and an iframe (pointing to, say stackoverflow.com). The silverlight app and iframe could be in separate div's, the same div, whatever. </p>
<p>Everything I've tried so far leaves me with a page that has no silverlight control rendered on it.</p>
<p>EDIT: At the request for what my xaml looks like (Plus I should point out that my controls render just fine if I comment out the iframe.)</p>
<pre><code><UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="Pink">
<Button Content="Click Me!"/>
</Grid>
</UserControl>
</code></pre>
<p>Thats it. Just for good measure here is my aspx page...</p>
<pre><code><form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<div style="height:100%;">
<asp:Silverlight ID="Silverlight1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="400" Height="400" />
</div>
<iframe src ="http://www.google.com" width="400"/>
</form>
</code></pre>
| [
{
"answer_id": 93637,
"author": "Ola Karlsson",
"author_id": 10696,
"author_profile": "https://Stackoverflow.com/users/10696",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm, sound a bit odd, a quick google gave me <a href=\"http://silverlight.net/forums/p/21584/75457.aspx\" rel=\"nofollow noreferrer\">this top result</a> which talks about using an Iframe and Silverlight on the same page, without problems.</p>\n\n<p>Also a quick test with the following code:</p>\n\n<pre><code><%@ Page Language=\"C#\" AutoEventWireup=\"true\" %>\n\n<%@ Register Assembly=\"System.Web.Silverlight\" Namespace=\"System.Web.UI.SilverlightControls\"\n TagPrefix=\"asp\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height:100%;\">\n<head runat=\"server\">\n <title>Test Page</title>\n</head>\n<body style=\"height:100%;margin:0;\">\n <form id=\"form1\" runat=\"server\" style=\"height:100%;\">\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\"></asp:ScriptManager>\n <div style=\"height:100%;\">\n <asp:Silverlight ID=\"Xaml1\" runat=\"server\" Source=\"~/ClientBin/Test.xap\" MinimumVersion=\"2.0.30523\" Width=\"400\" Height=\"400\" />\n </div>\n <iframe src =\"http://www.google.com\" width=\"400\"></iframe>\n </form>\n</body>\n</html>\n</code></pre>\n\n<p>Renders out both Silverlight and the Iframe quite happily.</p>\n\n<p>What code were you using when trying and it didn't work?</p>\n"
},
{
"answer_id": 94089,
"author": "Ola Karlsson",
"author_id": 10696,
"author_profile": "https://Stackoverflow.com/users/10696",
"pm_score": 0,
"selected": false,
"text": "<p>What does your XAML look like? </p>\n\n<p>It could be something along the lines of the size set on the usercontrol in XAML, doesn't match the size set on the plugin on the aspx page. In that case, your button might be there but just not in the viewable area... Try checking the size of things, make sure they match.</p>\n\n<p>A quick test you could do is to change the background color of your root element in the XAML and see if anything happen on the page.</p>\n\n<p>Also, does the silverlight work if you remove the Iframe but leave everything else as is?</p>\n\n<p>Sorry if this a too simple suggestion but without knowing your experience level with XAML... </p>\n"
},
{
"answer_id": 101119,
"author": "Senkwe",
"author_id": 6419,
"author_profile": "https://Stackoverflow.com/users/6419",
"pm_score": 0,
"selected": false,
"text": "<p>Funny enough, I just solved this issue by ensuring that I specify the iframe dimensions by pixel.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6419/"
]
| this should be simple...could someone provide me a simple code sample that has an aspx page hosting both a silverlight app (consisting of, say a button) and an iframe (pointing to, say stackoverflow.com). The silverlight app and iframe could be in separate div's, the same div, whatever.
Everything I've tried so far leaves me with a page that has no silverlight control rendered on it.
EDIT: At the request for what my xaml looks like (Plus I should point out that my controls render just fine if I comment out the iframe.)
```
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="Pink">
<Button Content="Click Me!"/>
</Grid>
</UserControl>
```
Thats it. Just for good measure here is my aspx page...
```
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<div style="height:100%;">
<asp:Silverlight ID="Silverlight1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="400" Height="400" />
</div>
<iframe src ="http://www.google.com" width="400"/>
</form>
``` | Hmm, sound a bit odd, a quick google gave me [this top result](http://silverlight.net/forums/p/21584/75457.aspx) which talks about using an Iframe and Silverlight on the same page, without problems.
Also a quick test with the following code:
```
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head runat="server">
<title>Test Page</title>
</head>
<body style="height:100%;margin:0;">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height:100%;">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/Test.xap" MinimumVersion="2.0.30523" Width="400" Height="400" />
</div>
<iframe src ="http://www.google.com" width="400"></iframe>
</form>
</body>
</html>
```
Renders out both Silverlight and the Iframe quite happily.
What code were you using when trying and it didn't work? |
93,100 | <p>We all know that prepared statements are one of the best way of fending of SQL injection attacks. What is the best way of creating a prepared statement with an "IN" clause. Is there an easy way to do this with an unspecified number of values? Take the following query for example.</p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (1,2,3)
</code></pre>
<p>Currently I'm using a loop over my possible values to build up a string such as. </p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDVAL_1,@IDVAL_2,@IDVAL_3)
</code></pre>
<p>Is it possible to use just pass an array as the value of the query paramter and use a query as follows?</p>
<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDArray)
</code></pre>
<p>In case it's important I'm working with SQL Server 2000, in VB.Net</p>
| [
{
"answer_id": 93184,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>If you would like to pass an array, you will need a function in sql that can turn that array into a sub-select.</p>\n\n<p>These functions are very common, and most home grown systems take advantage of them.</p>\n\n<p>Most commercial, or rather professional ORM's do ins by doing a bunch of variables, so if you have that working, I think that is the standard method.</p>\n"
},
{
"answer_id": 93225,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": -1,
"selected": false,
"text": "<p>In SQL Server 2008, they finally got around to addressing this classic problem by adding a new \"table\" datatype. Apparently, that lets you pass in an array of values, which can be used in a sub-select to accomplish the same as an IN statement.</p>\n\n<p>If you're using SQL Server 2008, then you might look into that.</p>\n"
},
{
"answer_id": 93247,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 3,
"selected": false,
"text": "<p>Here you go - first create the following function...</p>\n\n<pre><code>Create Function [dbo].[SeparateValues]\n(\n @data VARCHAR(MAX),\n @delimiter VARCHAR(10) \n) \n RETURNS @tbldata TABLE(col VARCHAR(10))\nAs\nBegin\n DECLARE @pos INT\n DECLARE @prevpos INT\n\n SET @pos = 1 \n SET @prevpos = 0\n\n WHILE @pos > 0 \n BEGIN\n\n SET @pos = CHARINDEX(@delimiter, @data, @prevpos+1)\n\n if @pos > 0 \n INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, @pos-@prevpos-1))))\n\n else\n\n INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, len(@data)-@prevpos))))\n\n SET @prevpos = @pos \n End\n\n RETURN\n\nEND\n</code></pre>\n\n<p>then use the following...</p>\n\n<pre><code>Declare @CommaSeparated varchar(50)\nSet @CommaSeparated = '112,112,122'\nSELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (select col FROM [SeparateValues](@CommaSeparated, ','))\n</code></pre>\n\n<p>I think sql server 2008 will allow table functions.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>You'll squeeze some extra performance using the following syntax...</p>\n\n<pre><code>SELECT ID,Column1,Column2 FROM MyTable\nCross Apply [SeparateValues](@CommaSeparated, ',') s\nWhere MyTable.id = s.col\n</code></pre>\n\n<p>Because the previous syntax causes SQL Server to run an extra \"Sort\" command using the \"IN\" clause. Plus - in my opinion it looks nicer :D!</p>\n"
},
{
"answer_id": 93258,
"author": "Mike",
"author_id": 1115144,
"author_profile": "https://Stackoverflow.com/users/1115144",
"pm_score": -1,
"selected": false,
"text": "<p>Here's one technique I use</p>\n\n<pre><code>ALTER Procedure GetProductsBySearchString\n@SearchString varchar(1000),\nas\nset nocount on\ndeclare @sqlstring varchar(6000)\nselect @sqlstring = 'set nocount on\nselect a.productid, count(a.productid) as SumOf, sum(a.relevence) as CountOf \n from productkeywords a \n where rtrim(ltrim(a.term)) in (''' + Replace(@SearchString,' ', ''',''') + ''')\n group by a.productid order by SumOf desc, CountOf desc'\n\nexec(@sqlstring)\n</code></pre>\n"
},
{
"answer_id": 97339,
"author": "Stefan Schweizer",
"author_id": 13559,
"author_profile": "https://Stackoverflow.com/users/13559",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a temporary table TempTable with a single column VALUE and insert all IDs. Then you could do it with a subselect:</p>\n\n<pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (SELECT VALUE FROM TempTable)\n</code></pre>\n"
},
{
"answer_id": 145004,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 0,
"selected": false,
"text": "<p>Go with the solution posted by digiguru. It's a great reusable solution and we use the same technique as well. New team members love it, as it saves time and keeps our stored procedures consistent. The solution also works well with SQL Reports, as the parameters passed to stored procedures to create the recordsets pass in varchar(8000). You just hook it up and go.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
]
| We all know that prepared statements are one of the best way of fending of SQL injection attacks. What is the best way of creating a prepared statement with an "IN" clause. Is there an easy way to do this with an unspecified number of values? Take the following query for example.
```
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (1,2,3)
```
Currently I'm using a loop over my possible values to build up a string such as.
```
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDVAL_1,@IDVAL_2,@IDVAL_3)
```
Is it possible to use just pass an array as the value of the query paramter and use a query as follows?
```
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDArray)
```
In case it's important I'm working with SQL Server 2000, in VB.Net | Here you go - first create the following function...
```
Create Function [dbo].[SeparateValues]
(
@data VARCHAR(MAX),
@delimiter VARCHAR(10)
)
RETURNS @tbldata TABLE(col VARCHAR(10))
As
Begin
DECLARE @pos INT
DECLARE @prevpos INT
SET @pos = 1
SET @prevpos = 0
WHILE @pos > 0
BEGIN
SET @pos = CHARINDEX(@delimiter, @data, @prevpos+1)
if @pos > 0
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, @pos-@prevpos-1))))
else
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, len(@data)-@prevpos))))
SET @prevpos = @pos
End
RETURN
END
```
then use the following...
```
Declare @CommaSeparated varchar(50)
Set @CommaSeparated = '112,112,122'
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (select col FROM [SeparateValues](@CommaSeparated, ','))
```
I think sql server 2008 will allow table functions.
**UPDATE**
You'll squeeze some extra performance using the following syntax...
```
SELECT ID,Column1,Column2 FROM MyTable
Cross Apply [SeparateValues](@CommaSeparated, ',') s
Where MyTable.id = s.col
```
Because the previous syntax causes SQL Server to run an extra "Sort" command using the "IN" clause. Plus - in my opinion it looks nicer :D! |
93,105 | <p>Need a function that takes a character as a parameter and returns true if it is a letter.</p>
| [
{
"answer_id": 93108,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 3,
"selected": false,
"text": "<p>This was part of the code posted by <a href=\"https://stackoverflow.com/users/4007/rpetrich\">rpetrich</a> in response to a <a href=\"https://stackoverflow.com/questions/61598/code-to-make-a-dhtmled-control-replace-straight-quotes-with-curly-quotes\">question</a> by <a href=\"https://stackoverflow.com/users/4/joel-spolsky\">Joel Spolsky</a>. I felt it needed a post specific to the problem it solves. It really is brilliant.</p>\n\n<pre><code>Private Function IsLetter(ByVal character As String) As Boolean\n IsLetter = UCase$(character) <> LCase$(character)\nEnd Function\n</code></pre>\n\n<p>You may be thinking to yourself, \"Will this always work?\" The documentation on the UCase and LCase functions, confirms that it will:</p>\n\n<blockquote>\n <p><strong>UCase Function</strong> Only lowercase letters are converted to uppercase;\n <em>all uppercase letters and nonletter characters remain unchanged</em>.</p>\n \n <p><strong>LCase Function</strong> Only uppercase letters are converted to lowercase;\n <em>all lowercase letters and nonletter characters remain unchanged</em>.</p>\n</blockquote>\n"
},
{
"answer_id": 93152,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>What's wrong with the following, which doesn't rely on obscure language behaviour?</p>\n\n<pre><code>Private Function IsLetter(ByVal ch As String) As Boolean\n IsLetter = (ch >= \"A\" and ch <= \"Z\") or (ch >= \"a\" and ch <= \"z\")\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 93194,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't exactly document itself. And it may be slow. It's a clever hack, but that's all it is. I'd be tempted to be more obvious in my checking. Either use regex's or write a more obvious test. </p>\n\n<pre><code>public bool IsAlpha(String strToCheck)\n{\n Regex objAlphaPattern=new Regex(\"[^a-zA-Z]\");\n return !objAlphaPattern.IsMatch(strToCheck);\n}\n\npublic bool IsCharAlpha(char chToCheck)\n{\n return ((chToCheck=>'a') and (chToCheck<='z')) or ((chToCheck=>'A') and (chToCheck<='Z'))\n}\n</code></pre>\n"
},
{
"answer_id": 93299,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 0,
"selected": false,
"text": "<p>Looking around a bit came up with the following...</p>\n\n<pre><code>Private Declare Function IsCharAlphaA Lib \"user32\" Alias \"IsCharAlphaA\" (ByVal cChar As Byte) As Long\n</code></pre>\n\n<p>I believe IsCharAlphaA tests ANSI character sets and IsCharAlpha tests ASCII. I may be wrong. </p>\n"
},
{
"answer_id": 96098,
"author": "Keith Maurino",
"author_id": 1096640,
"author_profile": "https://Stackoverflow.com/users/1096640",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Private Function IsAlpha(ByVal vChar As String) As Boolean\n Const letters$ = \"abcdefghijklmnopqrstuvwxyz\"\n\n If InStr(1, letters, LCase$(vChar)) > 0 Then IsAlpha = True\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 105474,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Private Function IsLetter(Char As String) As Boolean\n IsLetter = UCase(Char) Like \"[ABCDEFGHIJKLMNOPQRSTUVWXYZ]\"\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 109201,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 3,
"selected": true,
"text": "<p>Seanyboy's <code>IsCharAlphaA</code> <a href=\"https://stackoverflow.com/questions/93105/whats-the-best-way-to-determine-if-a-character-is-a-letter-in-vb6/93299#93299\">answer</a> is close. The best method is to use the W version like so:</p>\n\n<pre><code>Private Declare Function IsCharAlphaW Lib \"user32\" (ByVal cChar As Integer) As Long\nPublic Property Get IsLetter(character As String) As Boolean\n IsLetter = IsCharAlphaW(AscW(character))\nEnd Property\n</code></pre>\n\n<p>Of course, this all rarely matters as all of VB6's controls are ANSI only</p>\n"
},
{
"answer_id": 1024618,
"author": "Bob77",
"author_id": 126278,
"author_profile": "https://Stackoverflow.com/users/126278",
"pm_score": 1,
"selected": false,
"text": "<p>I believe we can improve upon this a little more. <strong>rpetrich</strong>'s code will work, but perhaps only by luck. The API call's parameter should be a TCHAR (WCHAR here actually) and not a Long. This also means no fiddling with converting to a Long or masking with &HFFFF. This by the way is Integer and adds an implicit conversion to Long here too. Perhaps he meant &HFFFF& in this case?</p>\n\n<p>On top of that it might be best to explictly call the UnicoWS wrapper for this API call, for Win9X compatibility. The UnicoWS.dll may need to be deployed but at least we gain that option. Then again maybe from VB6 this is automagically redirected, I don't have Win9X installed to test it.</p>\n\n<pre><code>Option Explicit\n\nPrivate Declare Function IsCharAlphaW Lib \"unicows\" (ByVal WChar As Integer) As Long\n\nPrivate Function IsLetter(Character As String) As Boolean\n IsLetter = IsCharAlphaW(AscW(Character))\nEnd Function\n\nPrivate Sub Main()\n MsgBox IsLetter(\"^\")\n MsgBox IsLetter(\"A\")\n MsgBox IsLetter(ChrW$(&H34F))\n MsgBox IsLetter(ChrW$(&HFEF0))\n MsgBox IsLetter(ChrW$(&HFEFC))\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 22345939,
"author": "Hartmut",
"author_id": 3409673,
"author_profile": "https://Stackoverflow.com/users/3409673",
"pm_score": 0,
"selected": false,
"text": "<p>I use this in VBA</p>\n\n<pre><code>Function IsLettersOnly(Value As String) As Boolean\n IsLettersOnly = Len(Value) > 0 And Not UCase(Value) Like \"*[!A-Z]*\"\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
]
| Need a function that takes a character as a parameter and returns true if it is a letter. | Seanyboy's `IsCharAlphaA` [answer](https://stackoverflow.com/questions/93105/whats-the-best-way-to-determine-if-a-character-is-a-letter-in-vb6/93299#93299) is close. The best method is to use the W version like so:
```
Private Declare Function IsCharAlphaW Lib "user32" (ByVal cChar As Integer) As Long
Public Property Get IsLetter(character As String) As Boolean
IsLetter = IsCharAlphaW(AscW(character))
End Property
```
Of course, this all rarely matters as all of VB6's controls are ANSI only |
93,128 | <p>I'm importing a MySQL dump and getting the following error.</p>
<pre><code>$ mysql foo < foo.sql
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes
</code></pre>
<p>Apparently there are attachments in the database, which makes for very large inserts.</p>
<hr>
<p>This is on my local machine, a Mac with MySQL 5 installed from the MySQL package.</p>
<p>Where do I change <code>max_allowed_packet</code> to be able to import the dump? </p>
<p>Is there anything else I should set? </p>
<p>Just running <code>mysql --max_allowed_packet=32M …</code> resulted in the same error.</p>
| [
{
"answer_id": 93165,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 6,
"selected": false,
"text": "<p>This can be changed in your <code>my.ini</code> file (on Windows, located in \\Program Files\\MySQL\\MySQL Server) under the server section, for example:</p>\n\n<pre><code>[mysqld]\n\nmax_allowed_packet = 10M\n</code></pre>\n"
},
{
"answer_id": 93168,
"author": "Tomasz Tybulewicz",
"author_id": 17405,
"author_profile": "https://Stackoverflow.com/users/17405",
"pm_score": 3,
"selected": false,
"text": "<p>Use a <code>max_allowed_packet</code> variable issuing a command like</p>\n\n<p><code>mysql --max_allowed_packet=32M\n -u root -p database < dump.sql</code></p>\n"
},
{
"answer_id": 95792,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.</p>\n\n<p>That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.</p>\n"
},
{
"answer_id": 104176,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 10,
"selected": true,
"text": "<p>You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import.</p>\n<p>For the client, you can specify it on the command line:</p>\n<pre><code>mysql --max_allowed_packet=100M -u root -p database < dump.sql\n</code></pre>\n<p>Also, <strong>change the my.cnf or my.ini file</strong> (usually found in /etc/mysql/) under the mysqld section and set:<br/></p>\n<pre><code>max_allowed_packet=100M\n</code></pre>\n<p>or you could run these <strong>commands</strong> in a MySQL console connected to that same server:</p>\n<pre><code>set global net_buffer_length=1000000; \nset global max_allowed_packet=1000000000;\n</code></pre>\n<p>(Use a very large value for the packet size.)</p>\n"
},
{
"answer_id": 105334,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 4,
"selected": false,
"text": "<h3>Re my.cnf on Mac OS X when using MySQL from the mysql.com dmg package distribution</h3>\n\n<p>By default, my.cnf is nowhere to be found.</p>\n\n<p>You need to copy one of <code>/usr/local/mysql/support-files/my*.cnf</code> to <code>/etc/my.cnf</code> and restart <code>mysqld</code>. (Which you can do in the MySQL preference pane if you installed it.)</p>\n"
},
{
"answer_id": 722656,
"author": "Joshua Fox",
"author_id": 39242,
"author_profile": "https://Stackoverflow.com/users/39242",
"pm_score": 7,
"selected": false,
"text": "<p>As michaelpryor said, you have to change it for <em>both</em> the client <em>and</em> the daemon mysqld server.</p>\n\n<p>His solution for the client command-line is good, but the ini files don't always do the trick, depending on configuration. </p>\n\n<p>So, open a terminal, type mysql to get a mysql prompt, and issue these commands:</p>\n\n<pre><code>set global net_buffer_length=1000000; \nset global max_allowed_packet=1000000000; \n</code></pre>\n\n<p>Keep the mysql prompt open, and run your command-line SQL execution on a second terminal..</p>\n"
},
{
"answer_id": 2684040,
"author": "jplindstrom",
"author_id": 10155,
"author_profile": "https://Stackoverflow.com/users/10155",
"pm_score": 3,
"selected": false,
"text": "<p>Slightly unrelated to your problem, so here's one for Google.</p>\n\n<p>If you didn't mysqldump the SQL, it might be that your SQL is broken. </p>\n\n<p>I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.</p>\n\n<p>That's a fantastic error message to get for a runaway string, thanks for that MySQL!</p>\n"
},
{
"answer_id": 19145731,
"author": "Mike Castro Demaria",
"author_id": 902279,
"author_profile": "https://Stackoverflow.com/users/902279",
"pm_score": 3,
"selected": false,
"text": "<p>On CENTOS 6 /etc/my.cnf , under [mysqld] section the correct syntax is:</p>\n\n<pre><code>[mysqld]\n# added to avoid err \"Got a packet bigger than 'max_allowed_packet' bytes\"\n#\nnet_buffer_length=1000000 \nmax_allowed_packet=1000000000\n#\n</code></pre>\n"
},
{
"answer_id": 20273704,
"author": "Primoz Rome",
"author_id": 255710,
"author_profile": "https://Stackoverflow.com/users/255710",
"pm_score": 4,
"selected": false,
"text": "<p>The fix is to increase the MySQL daemon’s max_allowed_packet. You can do this to a running daemon by logging in as Super and running the following commands. </p>\n\n<pre><code># mysql -u admin -p\n\nmysql> set global net_buffer_length=1000000;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> set global max_allowed_packet=1000000000;\nQuery OK, 0 rows affected (0.00 sec)\n</code></pre>\n\n<p>Then to import your dump:</p>\n\n<pre><code>gunzip < dump.sql.gz | mysql -u admin -p database\n</code></pre>\n"
},
{
"answer_id": 21524811,
"author": "Amirtha Rajan",
"author_id": 3061477,
"author_profile": "https://Stackoverflow.com/users/3061477",
"pm_score": 4,
"selected": false,
"text": "<p>In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to</p>\n\n<pre><code>max_allowed_packet=100000000\nnet_buffer_length=1000000 \n</code></pre>\n\n<p>if this is not working then try changing to</p>\n\n<pre><code>max_allowed_packet=100M\nnet_buffer_length=100K \n</code></pre>\n"
},
{
"answer_id": 22153978,
"author": "Raj Pawan Gumdal",
"author_id": 260665,
"author_profile": "https://Stackoverflow.com/users/260665",
"pm_score": 1,
"selected": false,
"text": "<p>I am working in a shared hosting environment and I have hosted a website based on Drupal. I cannot edit the <code>my.ini</code> file or <code>my.conf</code> file too.</p>\n\n<p>So, I deleted all the tables which were related to <code>Cache</code> and hence I could resolve this issue. Still I am looking for a perfect solution / way to handle this problem.</p>\n\n<p><strong>Edit</strong> - Deleting the tables created problems for me, coz Drupal was expecting that these tables should be existing. So I emptied the contents of these tables which solved the problem.</p>\n"
},
{
"answer_id": 33164481,
"author": "Grzegorz Brzęczyszczykiewicz",
"author_id": 2111633,
"author_profile": "https://Stackoverflow.com/users/2111633",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes type setting:</p>\n\n<pre><code>max_allowed_packet = 16M\n</code></pre>\n\n<p>in my.ini is not working. </p>\n\n<p>Try to determine the my.ini as follows:</p>\n\n<pre><code>set-variable = max_allowed_packet = 32M\n</code></pre>\n\n<p>or</p>\n\n<pre><code>set-variable = max_allowed_packet = 1000000000\n</code></pre>\n\n<p>Then restart the server:</p>\n\n<pre><code>/etc/init.d/mysql restart\n</code></pre>\n"
},
{
"answer_id": 38580700,
"author": "Shiva",
"author_id": 6160636,
"author_profile": "https://Stackoverflow.com/users/6160636",
"pm_score": 2,
"selected": false,
"text": "<p>It is a security risk to have <code>max_allowed_packet</code> at higher value, as an attacker can push bigger sized packets and crash the system. </p>\n\n<p>So, Optimum Value of <code>max_allowed_packet</code> to be tuned and tested.</p>\n\n<p>It is to better to change when required <em>(using <code>set global max_allowed_packet = xxx</code>)</em> \nthan to have it as part of <em>my.ini</em> or <em>my.conf</em>.</p>\n"
},
{
"answer_id": 54415138,
"author": "Tính Ngô Quang",
"author_id": 2949104,
"author_profile": "https://Stackoverflow.com/users/2949104",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Error:</strong></p>\n\n<blockquote>\n <p>ERROR 1153 (08S01) at line 6772: Got a packet bigger than\n 'max_allowed_packet' bytes Operation failed with exitcode 1</p>\n</blockquote>\n\n<p><strong>QUERY:</strong></p>\n\n<pre><code>SET GLOBAL max_allowed_packet=1073741824;\nSHOW VARIABLES LIKE 'max_allowed_packet'; \n</code></pre>\n\n<p><strong>Max value:</strong></p>\n\n<pre><code>Default Value (MySQL >= 8.0.3) 67108864\nDefault Value (MySQL <= 8.0.2) 4194304\nMinimum Value 1024\nMaximum Value 1073741824\n</code></pre>\n"
},
{
"answer_id": 70503808,
"author": "Ali Raza Khan",
"author_id": 14214444,
"author_profile": "https://Stackoverflow.com/users/14214444",
"pm_score": 3,
"selected": false,
"text": "<p>I have resolved my issue by this query</p>\n<pre><code>SET GLOBAL max_allowed_packet=1073741824;\n</code></pre>\n<p>and check max_allowed_packet with this query</p>\n<pre><code>SHOW VARIABLES LIKE 'max_allowed_packet';\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
]
| I'm importing a MySQL dump and getting the following error.
```
$ mysql foo < foo.sql
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes
```
Apparently there are attachments in the database, which makes for very large inserts.
---
This is on my local machine, a Mac with MySQL 5 installed from the MySQL package.
Where do I change `max_allowed_packet` to be able to import the dump?
Is there anything else I should set?
Just running `mysql --max_allowed_packet=32M …` resulted in the same error. | You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import.
For the client, you can specify it on the command line:
```
mysql --max_allowed_packet=100M -u root -p database < dump.sql
```
Also, **change the my.cnf or my.ini file** (usually found in /etc/mysql/) under the mysqld section and set:
```
max_allowed_packet=100M
```
or you could run these **commands** in a MySQL console connected to that same server:
```
set global net_buffer_length=1000000;
set global max_allowed_packet=1000000000;
```
(Use a very large value for the packet size.) |
93,150 | <p>The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000.</p>
<p>With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a <code>WITH OPTION (HASH JOIN, MERGE JOIN)</code>, which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile.</p>
<p>This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select.</p>
<p>I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common.</p>
<p>The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low.</p>
<p>The statistics for all the tables in the DB are up to date and refreshed automatically.</p>
<p>One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized.</p>
<p>I believe that the root problem is the bad row count estimate after certain joins, so my main questions are:</p>
<ul>
<li>How can I fix the QO's post join rowcount estimate?</li>
<li>Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually?</li>
</ul>
| [
{
"answer_id": 93182,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 0,
"selected": false,
"text": "<p>can't you prod the QO with a well-placed query hint?</p>\n"
},
{
"answer_id": 114811,
"author": "Chris Smith",
"author_id": 9073,
"author_profile": "https://Stackoverflow.com/users/9073",
"pm_score": 3,
"selected": true,
"text": "<p>Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage.</p>\n\n<pre><code>UPDATE STATISTICS <table> WITH FULLSCAN, ALL\n</code></pre>\n\n<p>The query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9073/"
]
| The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000.
With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a `WITH OPTION (HASH JOIN, MERGE JOIN)`, which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile.
This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select.
I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common.
The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low.
The statistics for all the tables in the DB are up to date and refreshed automatically.
One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized.
I believe that the root problem is the bad row count estimate after certain joins, so my main questions are:
* How can I fix the QO's post join rowcount estimate?
* Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually? | Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage.
```
UPDATE STATISTICS <table> WITH FULLSCAN, ALL
```
The query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds. |
93,162 | <p>Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how?</p>
| [
{
"answer_id": 93437,
"author": "Paul Mrozowski",
"author_id": 3656,
"author_profile": "https://Stackoverflow.com/users/3656",
"pm_score": 7,
"selected": false,
"text": "<p>This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work:</p>\n\n<pre><code>using System.ServiceModel;\nusing System.ServiceModel.Channels;\n\nOperationContext context = OperationContext.Current;\nMessageProperties prop = context.IncomingMessageProperties;\nRemoteEndpointMessageProperty endpoint =\n prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;\nstring ip = endpoint.Address;\n</code></pre>\n"
},
{
"answer_id": 188088,
"author": "Gaz",
"author_id": 3856,
"author_profile": "https://Stackoverflow.com/users/3856",
"pm_score": 6,
"selected": true,
"text": "<p>It turns out you can, so long as (a) your service is being hosted in a Web Service (obviously) and (b) you enable AspNetCompatibility mode, as follows:</p>\n\n<pre><code> <system.serviceModel>\n <!-- this enables WCF services to access ASP.Net http context -->\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\"/>\n...\n </system.serviceModel>\n</code></pre>\n\n<p>And then you can get the IP address by:</p>\n\n<pre><code>HttpContext.Current.Request.UserHostAddress\n</code></pre>\n"
},
{
"answer_id": 190513,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can if you are targeting .NET 3.0 SP1.</p>\n\n<pre><code>OperationContext context = OperationContext.Current;\nMessageProperties prop = context.IncomingMessageProperties;\nRemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;\nstring ip = endpoint.Address;\n</code></pre>\n\n<p>Credits:\n<a href=\"http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx</a></p>\n\n<p>Reference:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3856/"
]
| Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how? | It turns out you can, so long as (a) your service is being hosted in a Web Service (obviously) and (b) you enable AspNetCompatibility mode, as follows:
```
<system.serviceModel>
<!-- this enables WCF services to access ASP.Net http context -->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
</system.serviceModel>
```
And then you can get the IP address by:
```
HttpContext.Current.Request.UserHostAddress
``` |
93,171 | <p>I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins:</p>
<pre>o o o o
o o o
o o
o</pre>
<p>Images are used to represent the pins. So, for the back row, I have four <em>img</em> tags, then a <em>br</em> tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this:</p>
<pre>o o o
o
o o o
o o
o</pre>
<p>or</p>
<pre>o o
o o
o o
o
o o
o</pre>
<p>The structure is:</p>
<pre><code><tr>
<td>
<!-- some whitespace -->
<div class="..."><img .../><img .../><img .../><img .../><br/>...</div>
<!-- some whitespace -->
</td>
</tr>
</code></pre>
<p>There is no whitespace inside the inner div. If you look at <a href="http://www.bowlsk.com/games/view-series.html?series=13717" rel="nofollow noreferrer">this page</a> in a regular browser, it should display fine. If you look at it in IEMobile, it does not.</p>
<p>Any hints or suggestions? Maybe some sort of &nbsp; that doesn't actually add a space?</p>
<hr/>
<h3>Follow-up/Summary</h3>
<p>I have received and tried several good suggestions, including:</p>
<ul>
<li>Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on <a href="https://en.wikipedia.org/wiki/Google_App_Engine" rel="nofollow noreferrer">GAE</a>), and a bit more code than I'd like to write. These images could also be cached after the first generation.</li>
<li>Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view.</li>
</ul>
<h3>What I ended up doing</h3>
<em>*hangs head and mumbles something*</em>
<p>Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like:</p>
<pre><code><table class="game">
<tr class="analysis leave">
<!-- ... -->
<td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td>
<!-- ... -->
</tr>
</table>
</code></pre>
<p>And CSS:</p>
<pre class="lang-css prettyprint-override"><code>div.smallpins {
background: url(/img/lane.gif) repeat;
text-align: center;
padding: 0;
white-space: nowrap;
}
div.smallpins img {
width: 1em;
height: 1em;
}
div.smallpins img.spacer {
width: 4.5em;
height: 0px;
}
table.game tr.leave td{
padding: 0;
margin: 0;
}
table.game tr.leave .smallpins {
min-width: 4em;
white-space: nowrap;
background: none;
}
</code></pre>
<p>P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :)</p>
| [
{
"answer_id": 93189,
"author": "Paul Whelan",
"author_id": 3050,
"author_profile": "https://Stackoverflow.com/users/3050",
"pm_score": 2,
"selected": false,
"text": "<p>Why not have an image for all possible outcomes for the pins? No Messing with layouts for browsers an image is an image</p>\n\n<p>Generate them on the fly caching the created images for reuse.</p>\n"
},
{
"answer_id": 93197,
"author": "Josh Stodola",
"author_id": 54420,
"author_profile": "https://Stackoverflow.com/users/54420",
"pm_score": 0,
"selected": false,
"text": "<p>You might need an actual space immediately following the semi-colon in </p>\n"
},
{
"answer_id": 93210,
"author": "Tim Cochran",
"author_id": 2626,
"author_profile": "https://Stackoverflow.com/users/2626",
"pm_score": 2,
"selected": false,
"text": "<p>I've got around this type of issue in the past by dynamically creating the entire image (with appropriate pin arrangement) as a single image. If you are using ASP.NET, this is pretty easy to do with GDI calls. You just dynamically create the image with pin placement, then serve to the page as a single image. Takes all the alignment issues out of the picture (pun intended).</p>\n"
},
{
"answer_id": 93227,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>Since you are using images anyway, why not generate an image representing the whole layout on the fly? You can use something like <a href=\"http://www.boutell.com/gd/\" rel=\"nofollow noreferrer\">GD</a> or <a href=\"http://www.imagemagick.org/script/index.php\" rel=\"nofollow noreferrer\">ImageMagick</a> to do the trick.</p>\n"
},
{
"answer_id": 93237,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 0,
"selected": false,
"text": "<p>Try it with the <code><div></code> tag on the same line as <code><td>...</td></code></p>\n"
},
{
"answer_id": 93244,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 0,
"selected": false,
"text": "<p>I may have misunderstood what you are after but I think that you can do what I've done <a href=\"http://woarl.com/board/robMap.html\" rel=\"nofollow noreferrer\">for logos on a map</a>.</p>\n\n<p>The map background tile is drawn then each image is told to float left and given some interesting margins so that they are positioned as I want them to be (view source to see how it's done).</p>\n"
},
{
"answer_id": 93248,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": -1,
"selected": false,
"text": "<p>Would it not be easier if you do it like this?</p>\n\n<pre><code><div id=\"container\">\n <div id=\"row1\">\n <img/><img/><img/><img/>\n </div>\n <div id=\"row2\">\n <img/><img/><img/>\n </div>\n <div id=\"row3\">\n <img/><img/>\n </div>\n <div id=\"row4\">\n <img/>\n </div>\n</div>\n</code></pre>\n\n<p>Whereby your CSS would handle the alignment?</p>\n\n<pre><code>.container div{\n text-align:center;\n}\n</code></pre>\n"
},
{
"answer_id": 93254,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 6,
"selected": true,
"text": "<p>You could try the css \"nowrap\" option in the containing div.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>{white-space: nowrap;}\n</code></pre>\n\n<p>Not sure how widely that is supported.</p>\n"
},
{
"answer_id": 93285,
"author": "racurry",
"author_id": 17751,
"author_profile": "https://Stackoverflow.com/users/17751",
"pm_score": 2,
"selected": false,
"text": "<p>What would make the most sense is changing out which image is displayed on the fly:</p>\n\n<pre><code><div id=\"pin-images\">\n <img src=\"fivepins.jpg\" />\n <img src=\"fourpins.jpg\" />\n <img src=\"threepins.jpg\" />\n <img src=\"twopins.jpg\" />\n <img src=\"onepin.jpg\" />\n</div>\n</code></pre>\n"
},
{
"answer_id": 93304,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Add a \"nowrap\" in your td tag...</p>\n"
},
{
"answer_id": 93403,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "<p>Use the word joiner character, U+2060 (i.e. <code>&#x2060;</code>)</p>\n"
},
{
"answer_id": 93429,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe this is just one case where you could use tables to enforce layout. It's not optimal, and I know you aren't supposed to use tables for things that aren't tabular, but you could do something like this. </p>\n\n<pre><code><table>\n<tr>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;></td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n</tr>\n<tr>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n</tr>\n<tr>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n</tr>\n<tr>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td><img src=\"Pin.jpg\"></td>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n</tr>\n</table>\n</code></pre>\n"
},
{
"answer_id": 93518,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Since you're going for maximum compatibility, consider generating a single image representing the frame.</p>\n<p>If you're using PHP, you can use GD to dynamically create images representing the frames based on the same input that you would use to create the HTML in your question. The biggest advantage to doing this is that any browser which could display a PNG or GIF would be able to display your frame.</p>\n"
},
{
"answer_id": 93817,
"author": "Michel",
"author_id": 17316,
"author_profile": "https://Stackoverflow.com/users/17316",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have tried to define a width for the column? Like <code><td width=\"123px\"></code> or <code><td style=\"width:123px\"></code>. And maybe also for the div ?</p>\n"
},
{
"answer_id": 94006,
"author": "Michel",
"author_id": 17316,
"author_profile": "https://Stackoverflow.com/users/17316",
"pm_score": 0,
"selected": false,
"text": "<p>You can replace img with span and use a background image with each span, depending on a CSS class:</p>\n<pre><code><p class="..."><span class="pin"></span><span>&nbsp;</span><span class="pin"></span>...\n<p class="..."><span class="pin"></span><span>&nbsp;</span><span class="pin"></span>...\n<p class="..."><span class="pin"></span><span>&nbsp;</span><span class="pin"></span>...\n<p class="..."><span class="pin"></span><span>&nbsp;</span><span class="pin"></span>...\n</code></pre>\n<p>(Personally I think it's better to have four lines with a <code>p</code> tag instead of a single <code>div</code> with <code>br</code>.)</p>\n<p>Then in CSS you can have something like this:</p>\n<pre class=\"lang-css prettyprint-override\"><code>p.smallpins {\n margin: 0;\n padding: 0;\n height: 11px;\n font-size: 1px;\n}\np.smallpins span {\n width: 11px;\n background-image: url(nopinsmall.gif);\n background-repeat: ...\n background-position: ...\n}\np.smallpins span.pin {\n background-image: url(pinsmall.gif);\n}\n</code></pre>\n"
},
{
"answer_id": 95564,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>There isn't any <strong><a href=\"http://devedge-temp.mozilla.org/library/manuals/1998/htmlguide/tags15.html#1107540\" rel=\"nofollow noreferrer\">nobr</a></strong> HTML tag; I am not sure how well-supported this is, though.</li>\n<li>You could use CSS <strong>overflow:visible</strong> and non-breaking spaces between your elements (images), but no other white space in the HTML content for those lines.</li>\n</ul>\n"
},
{
"answer_id": 102860,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 0,
"selected": false,
"text": "<p>Have separate images for every possible arrangement <strong>of each row</strong>.</p>\n\n<p>That would only require 30 images (16+8+4+2)</p>\n"
},
{
"answer_id": 402531,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I figured out that there is a setting on the client where they can select the view as 1) <em>Single Column</em>, 2) <em>Desktop View</em>, and 3) <em>Fit Window</em>.</p>\n<p>According to MSDN, the default is supposed to be to <em>Fit Window</em>. But my wife's IE Mobile phone was defaulting to a <em>Single Column</em>. <em>So no matter what</em>, it would wrap everything into a single column. If I switched to any of the other two options it looked fine.</p>\n<p>Well, you can set this with a meta tag:</p>\n<pre><code><meta name="MobileOptimized" content="320">\n</code></pre>\n<p>will set the page width to 320 pixels. But I don't know how to make it go to auto.</p>\n<p>This does <em>not</em> work on <a href=\"https://en.wikipedia.org/wiki/BlackBerry\" rel=\"nofollow noreferrer\">BlackBerry's</a> prior to v4.6 - you're stuck with single column unless the user manually changes to desktop view. With 4.6 or later, the following is supposed to work, but I haven't tested it:</p>\n<pre><code><meta name="viewport" content="width=320">\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
]
| I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins:
```
o o o o
o o o
o o
o
```
Images are used to represent the pins. So, for the back row, I have four *img* tags, then a *br* tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this:
```
o o o
o
o o o
o o
o
```
or
```
o o
o o
o o
o
o o
o
```
The structure is:
```
<tr>
<td>
<!-- some whitespace -->
<div class="..."><img .../><img .../><img .../><img .../><br/>...</div>
<!-- some whitespace -->
</td>
</tr>
```
There is no whitespace inside the inner div. If you look at [this page](http://www.bowlsk.com/games/view-series.html?series=13717) in a regular browser, it should display fine. If you look at it in IEMobile, it does not.
Any hints or suggestions? Maybe some sort of that doesn't actually add a space?
---
### Follow-up/Summary
I have received and tried several good suggestions, including:
* Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on [GAE](https://en.wikipedia.org/wiki/Google_App_Engine)), and a bit more code than I'd like to write. These images could also be cached after the first generation.
* Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view.
### What I ended up doing
*\*hangs head and mumbles something\**
Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like:
```
<table class="game">
<tr class="analysis leave">
<!-- ... -->
<td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td>
<!-- ... -->
</tr>
</table>
```
And CSS:
```css
div.smallpins {
background: url(/img/lane.gif) repeat;
text-align: center;
padding: 0;
white-space: nowrap;
}
div.smallpins img {
width: 1em;
height: 1em;
}
div.smallpins img.spacer {
width: 4.5em;
height: 0px;
}
table.game tr.leave td{
padding: 0;
margin: 0;
}
table.game tr.leave .smallpins {
min-width: 4em;
white-space: nowrap;
background: none;
}
```
P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :) | You could try the css "nowrap" option in the containing div.
```css
{white-space: nowrap;}
```
Not sure how widely that is supported. |
93,208 | <p>I'd like to automatically generate database scripts on a regular basis. Is this possible.</p>
| [
{
"answer_id": 93282,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": true,
"text": "<p>To generate script for an object you have to pass up to six parameters:</p>\n\n<pre><code>exec proc_genscript \n @ServerName = 'Server Name', \n @DBName = 'Database Name', \n @ObjectName = 'Object Name to generate script for', \n @ObjectType = 'Object Type', \n @TableName = 'Parent table name for index and trigger',\n @ScriptFile = 'File name to save the script'\n</code></pre>\n\n<p><a href=\"http://www.databasejournal.com/features/mssql/article.php/2205291\" rel=\"noreferrer\">http://www.databasejournal.com/features/mssql/article.php/2205291</a></p>\n"
},
{
"answer_id": 93303,
"author": "DaveCrawford",
"author_id": 16865,
"author_profile": "https://Stackoverflow.com/users/16865",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to look at the SQL Server Management Objects (SMO). There are objects for scripting that will assist in generating T-SQL scripts from database objects. A good reference for this is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596004796\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">\"Programming SQL Server 2005\"</a> by Bill Hamilton. Chapter 12 in particular references the SMO utility classes.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'd like to automatically generate database scripts on a regular basis. Is this possible. | To generate script for an object you have to pass up to six parameters:
```
exec proc_genscript
@ServerName = 'Server Name',
@DBName = 'Database Name',
@ObjectName = 'Object Name to generate script for',
@ObjectType = 'Object Type',
@TableName = 'Parent table name for index and trigger',
@ScriptFile = 'File name to save the script'
```
<http://www.databasejournal.com/features/mssql/article.php/2205291> |
93,214 | <p>Given the code from the <a href="http://railscasts.com/episodes/75" rel="nofollow noreferrer">Complex Form part III</a> how would you go about testing the virtual attribute?</p>
<pre><code> def new_task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
</code></pre>
<p>I am currently trying to test it like this:</p>
<pre><code> def test_adding_task_to_project
p = Project.new
params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
p.new_tasks_attributes=(params)
p.save
assert p.tasks.length == 1
end
</code></pre>
<p>But I am getting the following error:</p>
<blockquote>
<p>NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String</p>
</blockquote>
<p>Any suggestions on improving this test would be greatly appreciated.</p>
| [
{
"answer_id": 93393,
"author": "Jason Wadsworth",
"author_id": 11078,
"author_profile": "https://Stackoverflow.com/users/11078",
"pm_score": 3,
"selected": true,
"text": "<p>It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:</p>\n\n<pre><code>def test_adding_task_to_project\n p = Project.new\n new_tasks_attributes = [{ \"name\" => \"paint fence\"}]\n p.new_tasks_attributes = (new_tasks_attributes)\n p.save\n assert p.tasks.length == 1\nend\n</code></pre>\n"
},
{
"answer_id": 93440,
"author": "Ben Hamill",
"author_id": 9619,
"author_profile": "https://Stackoverflow.com/users/9619",
"pm_score": 0,
"selected": false,
"text": "<p>Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?</p>\n\n<p>Also, params looks odd to me. Is tasks.build() expecting input like this: <code>[\"new_tasks_attribute\", {\"name\" => \"paint fence\"}]</code> ?</p>\n\n<p>If not, maybe you actually want Hash#each_key() instead of Hash#each()?</p>\n\n<p>Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
| Given the code from the [Complex Form part III](http://railscasts.com/episodes/75) how would you go about testing the virtual attribute?
```
def new_task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
```
I am currently trying to test it like this:
```
def test_adding_task_to_project
p = Project.new
params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
p.new_tasks_attributes=(params)
p.save
assert p.tasks.length == 1
end
```
But I am getting the following error:
>
> NoMethodError: undefined method `stringify\_keys!' for "new\_tasks\_attributes":String
>
>
>
Any suggestions on improving this test would be greatly appreciated. | It looks as if new\_task\_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
```
def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
``` |
93,222 | <p>I recently received an email from my girlfriend that spamassassin marked as spam, mostly because spamassassin detected a tracker ID... except there wasn't one. I'd like to know what triggered it, so that I can report a sensible bug.</p>
| [
{
"answer_id": 93393,
"author": "Jason Wadsworth",
"author_id": 11078,
"author_profile": "https://Stackoverflow.com/users/11078",
"pm_score": 3,
"selected": true,
"text": "<p>It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:</p>\n\n<pre><code>def test_adding_task_to_project\n p = Project.new\n new_tasks_attributes = [{ \"name\" => \"paint fence\"}]\n p.new_tasks_attributes = (new_tasks_attributes)\n p.save\n assert p.tasks.length == 1\nend\n</code></pre>\n"
},
{
"answer_id": 93440,
"author": "Ben Hamill",
"author_id": 9619,
"author_profile": "https://Stackoverflow.com/users/9619",
"pm_score": 0,
"selected": false,
"text": "<p>Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?</p>\n\n<p>Also, params looks odd to me. Is tasks.build() expecting input like this: <code>[\"new_tasks_attribute\", {\"name\" => \"paint fence\"}]</code> ?</p>\n\n<p>If not, maybe you actually want Hash#each_key() instead of Hash#each()?</p>\n\n<p>Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
]
| I recently received an email from my girlfriend that spamassassin marked as spam, mostly because spamassassin detected a tracker ID... except there wasn't one. I'd like to know what triggered it, so that I can report a sensible bug. | It looks as if new\_task\_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
```
def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
``` |
93,231 | <p>I'm having a problem debugging an Eclipse Application from Eclipse. When I launch the Debug Configuration, the Eclipse Application starts up and then stops repeatedly. It shows the splash screen and then disappears. This is the farthest it gets before restarting:</p>
<pre><code>MyDebugConfiguration [Eclipse Application]
org.eclipse.equinox.launcher.Main at localhost:2599
Thread [main] (Running)
Daemon Thread [Signal Dispatcher] (Running)
Daemon Thread [State Data Manager] (Running)
Daemon Thread [Framework Event Dispatcher] (Running)
Thread [State Saver] (Running)
Daemon Thread [Start Level Event Dispatcher] (Running)
Thread [Refresh Packages] (Running)
C:\MyApp\eclipse\jdk\jre\bin\javaw.exe (Sep 18, 2008 9:38:19 AM)
</code></pre>
<p>I am using Version 3.4.0 of the Eclipse SDK.</p>
<p>What is causing this?</p>
| [
{
"answer_id": 93393,
"author": "Jason Wadsworth",
"author_id": 11078,
"author_profile": "https://Stackoverflow.com/users/11078",
"pm_score": 3,
"selected": true,
"text": "<p>It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:</p>\n\n<pre><code>def test_adding_task_to_project\n p = Project.new\n new_tasks_attributes = [{ \"name\" => \"paint fence\"}]\n p.new_tasks_attributes = (new_tasks_attributes)\n p.save\n assert p.tasks.length == 1\nend\n</code></pre>\n"
},
{
"answer_id": 93440,
"author": "Ben Hamill",
"author_id": 9619,
"author_profile": "https://Stackoverflow.com/users/9619",
"pm_score": 0,
"selected": false,
"text": "<p>Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?</p>\n\n<p>Also, params looks odd to me. Is tasks.build() expecting input like this: <code>[\"new_tasks_attribute\", {\"name\" => \"paint fence\"}]</code> ?</p>\n\n<p>If not, maybe you actually want Hash#each_key() instead of Hash#each()?</p>\n\n<p>Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
]
| I'm having a problem debugging an Eclipse Application from Eclipse. When I launch the Debug Configuration, the Eclipse Application starts up and then stops repeatedly. It shows the splash screen and then disappears. This is the farthest it gets before restarting:
```
MyDebugConfiguration [Eclipse Application]
org.eclipse.equinox.launcher.Main at localhost:2599
Thread [main] (Running)
Daemon Thread [Signal Dispatcher] (Running)
Daemon Thread [State Data Manager] (Running)
Daemon Thread [Framework Event Dispatcher] (Running)
Thread [State Saver] (Running)
Daemon Thread [Start Level Event Dispatcher] (Running)
Thread [Refresh Packages] (Running)
C:\MyApp\eclipse\jdk\jre\bin\javaw.exe (Sep 18, 2008 9:38:19 AM)
```
I am using Version 3.4.0 of the Eclipse SDK.
What is causing this? | It looks as if new\_task\_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
```
def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
``` |
93,264 | <p>I have created a foreign key (in SQL Server) by:</p>
<pre><code>alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
</code></pre>
<p>I then run this query:</p>
<pre><code>alter table company drop column CountryID;
</code></pre>
<p>and I get this error:</p>
<blockquote>
<p><em>Msg 5074, Level 16, State 4, Line 2<br>
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.<br>
Msg 4922, Level 16, State 9, Line 2<br>
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column</em></p>
</blockquote>
<p>I have tried this, yet it does not seem to work:</p>
<pre><code>alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
</code></pre>
<p>What do I need to do to drop the <code>CountryID</code> column?</p>
<p>Thanks.</p>
| [
{
"answer_id": 93292,
"author": "Mike",
"author_id": 1115144,
"author_profile": "https://Stackoverflow.com/users/1115144",
"pm_score": 9,
"selected": true,
"text": "<p>Try</p>\n\n<pre><code>alter table company drop constraint Company_CountryID_FK\n\n\nalter table company drop column CountryID\n</code></pre>\n"
},
{
"answer_id": 93306,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know MSSQL but would it not be:</p>\n\n<pre><code>alter table company drop **constraint** Company_CountryID_FK;\n</code></pre>\n"
},
{
"answer_id": 93314,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 4,
"selected": false,
"text": "<pre><code>alter table company drop constraint Company_CountryID_FK\n</code></pre>\n"
},
{
"answer_id": 93324,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 6,
"selected": false,
"text": "<p>This will work:</p>\n\n<pre><code>ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]\n</code></pre>\n"
},
{
"answer_id": 2951957,
"author": "Gerardo Jaramillo",
"author_id": 132994,
"author_profile": "https://Stackoverflow.com/users/132994",
"pm_score": 1,
"selected": false,
"text": "<p>You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.</p>\n"
},
{
"answer_id": 15638387,
"author": "Philip Wade",
"author_id": 1017395,
"author_profile": "https://Stackoverflow.com/users/1017395",
"pm_score": 1,
"selected": false,
"text": "<p>Are you trying to drop the FK constraint or the column itself?</p>\n\n<p>To drop the constraint:</p>\n\n<pre><code>alter table company drop constraint Company_CountryID_FK\n</code></pre>\n\n<p>You won't be able to drop the column until you drop the constraint.</p>\n"
},
{
"answer_id": 20857604,
"author": "Samir Savasani",
"author_id": 2868162,
"author_profile": "https://Stackoverflow.com/users/2868162",
"pm_score": 5,
"selected": false,
"text": "<p>I think this will helpful to you...</p>\n\n<pre><code>DECLARE @ConstraintName nvarchar(200)\nSELECT \n @ConstraintName = KCU.CONSTRAINT_NAME\nFROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC \nINNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU\n ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG \n AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA \n AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME\nWHERE\n KCU.TABLE_NAME = 'TABLE_NAME' AND\n KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'\nIF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName)\n</code></pre>\n\n<p>It will delete foreign Key Constraint based on specific table and column.</p>\n"
},
{
"answer_id": 24214560,
"author": "Naeem Iqbal",
"author_id": 3411412,
"author_profile": "https://Stackoverflow.com/users/3411412",
"pm_score": 5,
"selected": false,
"text": "<p>First check of existence of the constraint then drop it. </p>\n\n<pre><code>if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')\nbegin\nalter table company drop constraint Company_CountryID_FK\nend\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
]
| I have created a foreign key (in SQL Server) by:
```
alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
```
I then run this query:
```
alter table company drop column CountryID;
```
and I get this error:
>
> *Msg 5074, Level 16, State 4, Line 2
>
> The object 'Company\_CountryID\_FK' is dependent on column 'CountryID'.
>
> Msg 4922, Level 16, State 9, Line 2
>
> ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column*
>
>
>
I have tried this, yet it does not seem to work:
```
alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
```
What do I need to do to drop the `CountryID` column?
Thanks. | Try
```
alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
``` |
93,274 | <p>What is the <em>definitive</em> way to mimic the CSS property min-width in Internet Explorer 6? Is it better not to try?</p>
| [
{
"answer_id": 93286,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>do your css tag as _Width: 500px or whatever.</p>\n"
},
{
"answer_id": 93296,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 4,
"selected": true,
"text": "<pre class=\"lang-css prettyprint-override\"><code>foo { min-width: 100px } // for everyone\n* html foo { width: 100px } // just for IE\n</code></pre>\n\n<p>(or serve a separate stylesheet to IE using <a href=\"http://www.quirksmode.org/css/condcom.html\" rel=\"nofollow noreferrer\">conditional comments</a>)</p>\n"
},
{
"answer_id": 93307,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 0,
"selected": false,
"text": "<p>This works pretty well...</p>\n\n<pre><code>div.container {\n min-width: 760px; \n width:expression(document.body.clientWidth < 760? \"760px\": \"auto\" ); \n}\n</code></pre>\n"
},
{
"answer_id": 93344,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.cssplay.co.uk/boxes/minwidth.html\" rel=\"nofollow noreferrer\">This article</a> on CSS Play, by Stu Nicholls, shows the different methods for achieving min-width in IE, in all modes (Quirks, etc) and even for IE/Mac.</p>\n"
},
{
"answer_id": 93530,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 3,
"selected": false,
"text": "<p>You could use an expression (as suggested by HBoss), but if you are worried about performance then the best way to do this is to add a shim inside the element you want to apply a min-width to.</p>\n\n<pre><code><div id=\"container\">\n The \"shim\" div will hold the container div open to at least 500px!\n You should be able to put it anywhere in the container div.\n <div class=\"shim\">&nbsp;</div>\n</div>\n\n#container .shim {\n width: 500px;\n height: 0;\n line-height: 0;\n}\n</code></pre>\n\n<p>This requires a little non-semantic markup but is a truly cross-browser solution and doesn't require the overhead of using an expression.</p>\n"
},
{
"answer_id": 93558,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.dustindiaz.com/min-height-fast-hack/\" rel=\"nofollow noreferrer\">Min-height fast hack</a> works for me (also works for width)</p>\n"
},
{
"answer_id": 121179,
"author": "mmcglynn",
"author_id": 4241,
"author_profile": "https://Stackoverflow.com/users/4241",
"pm_score": -1,
"selected": false,
"text": "<p>Use conditional comments to reference and MSIE 6 specific style sheet, then create CSS as below.</p>\n\n<p>Compliant browsers will use:</p>\n\n<pre><code>min-width: 660px;\n</code></pre>\n\n<p>Then MSIE 6 will use:</p>\n\n<pre><code>width: expression((document.body.clientWidth < 659)? \"660px\" : \"auto\");\n</code></pre>\n"
},
{
"answer_id": 188239,
"author": "Mike",
"author_id": 25371,
"author_profile": "https://Stackoverflow.com/users/25371",
"pm_score": 2,
"selected": false,
"text": "<p>I've fiddled with every answer given here in the past month. And after playing with Pretaul's method (<a href=\"https://stackoverflow.com/questions/93274/min-width-in-msie-6#93530\">Min-width in MSIE 6</a>), it seems to be the best alternative to min-width. No hacks or anything, just straight up compliant CSS code which takes 30 seconds to implement.</p>\n\n<p>From Googling around, expressions seem to be the most popular. For me anyways, ittended to randomly lock up my browser (both IE and FF).</p>\n"
},
{
"answer_id": 231174,
"author": "adgoudz",
"author_id": 30527,
"author_profile": "https://Stackoverflow.com/users/30527",
"pm_score": 0,
"selected": false,
"text": "<p>The shim example is fine for forcing the browser to show a horizontal scroll bar when the container gets to a certain size but you'll notice that the content in the container will still be resized as the window gets smaller. I imagine that this is not the overall goal when trying to achieve minimum width in IE 6.</p>\n\n<p><a href=\"http://www.mediafire.com/imgbnc.php/260264acec99b5aba3e77c1c4cdc54e94g.jpg\" rel=\"nofollow noreferrer\">Incomplete min-width technique http://www.mediafire.com/imgbnc.php/260264acec99b5aba3e77c1c4cdc54e94g.jpg</a></p>\n\n<p>Furthermore, the use of expressions and other crazy CSS hacks just isn't good practice. They are unsafe and unclean. This <a href=\"http://www.digital-web.com/articles/keep_css_simple/\" rel=\"nofollow noreferrer\">article</a> explains the caveats of CSS hacks and why they should be avoided altogether.</p>\n\n<p>I personally consider scaryjeff's post to be the best advice for achieving true min-width in IE6 and as an experienced CSS layout developer I've yet to find a better solution that is as applicable to problems of this kind.</p>\n\n<blockquote>\n <p>This <a href=\"http://www.cssplay.co.uk/boxes/minwidth.html\" rel=\"nofollow noreferrer\">article</a> on CSS Play, by Stu Nicholls, shows the different methods for achieving min-width in IE, in all modes (Quirks, etc) and even for IE/Mac.</p>\n</blockquote>\n\n<p>I've provided an answer to a similar question that details the use of this technique to correctly achieve min-width. It can be viewed here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/191429/css-two-50-fluid-columns-not-respecting-min-width#230152\">CSS: Two 50% fluid columns not respecting min width</a></p>\n\n<p>The technique is simple, valid CSS that can be used in almost any situation. Applied to the shim example above it results in what I consider to be correct min-width functionality.</p>\n\n<p><a href=\"http://www.mediafire.com/imgbnc.php/a67b2820bfbd6a5b588bea23c4c0462f4g.jpg\" rel=\"nofollow noreferrer\">Correct min-width technique http://www.mediafire.com/imgbnc.php/a67b2820bfbd6a5b588bea23c4c0462f4g.jpg</a></p>\n"
},
{
"answer_id": 1008605,
"author": "Dean Peters",
"author_id": 441512,
"author_profile": "https://Stackoverflow.com/users/441512",
"pm_score": 2,
"selected": false,
"text": "<p>I dunno, I had some success with:</p>\n\n<pre><code> min-width: 193px;\n width:auto !important; \n _width: 193px; /* IE6 hack */\n</code></pre>\n\n<p>A combination of dustin diaz' min-height fast hack & <a href=\"https://stackoverflow.com/questions/56658/how-do-i-specify-in-html-or-css-the-absolute-minimum-width-of-a-table-cell\">How do I specify in HTML or CSS the absolute minimum width of a table cell</a></p>\n"
},
{
"answer_id": 3415821,
"author": "Fatih Hayrioğlu",
"author_id": 296373,
"author_profile": "https://Stackoverflow.com/users/296373",
"pm_score": 0,
"selected": false,
"text": "<p>Single line button </p>\n\n<pre><code>button{\nbackground-color:#069;\nfloat:left;\nmin-width:200px;\nwidth:auto !important;\nwidth:200px;\nwhite-space: nowrap}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4241/"
]
| What is the *definitive* way to mimic the CSS property min-width in Internet Explorer 6? Is it better not to try? | ```css
foo { min-width: 100px } // for everyone
* html foo { width: 100px } // just for IE
```
(or serve a separate stylesheet to IE using [conditional comments](http://www.quirksmode.org/css/condcom.html)) |
93,277 | <p>I have a rails form with a datetime_select field. When I try to submit the form, I get the following exception:</p>
<pre><code>ActiveRecord::MultiparameterAssignmentErrors in WidgetsController#update
1 error(s) on assignment of multiparameter attributes
</code></pre>
<p>If it's a validation error, why don't I see an error on the page?</p>
<p>This is in Rails 2.0.2</p>
| [
{
"answer_id": 93327,
"author": "Jason Wadsworth",
"author_id": 11078,
"author_profile": "https://Stackoverflow.com/users/11078",
"pm_score": 5,
"selected": true,
"text": "<p>It turns out that rails uses something called Multi-parameter assignment to transmit dates and times in small parts that are reassembled when you assign params to the model instance.</p>\n\n<p>My problem was that I was using a datetime_select form field for a date model field. It apparently chokes when the multi-parameter magic tries to set the time on a Date object.</p>\n\n<p>The solution was to use a <code>date_select</code> form field rather than a <code>datetime_select</code>.</p>\n"
},
{
"answer_id": 1871611,
"author": "franee",
"author_id": 149250,
"author_profile": "https://Stackoverflow.com/users/149250",
"pm_score": 2,
"selected": false,
"text": "<p>ActiveRecord throws the MultiparameterAssignmentErrors exception when you try to set an invalid date to a models attribute.</p>\n\n<p>Try to pick a Nov 31 date from the date_select or datetime_select dropdown and you will get this error.</p>\n"
},
{
"answer_id": 2224752,
"author": "Zubin",
"author_id": 258826,
"author_profile": "https://Stackoverflow.com/users/258826",
"pm_score": 0,
"selected": false,
"text": "<p>This error can also occur with webrat/cucumber when filling in form data using a table.</p>\n\n<p>eg this doesn't work:</p>\n\n<pre><code>When I fill in the following:\n | report_from_1i | 2010 |\n | report_from_2i | January |\n | report_from_3i | 1 |\n | report_to_1i | 2010 |\n | report_to_2i | February |\n | report_to_3i | 1 |\n</code></pre>\n\n<p>but this does:</p>\n\n<pre><code>When I fill in the following:\n | report_from_1i | 2010 |\n | report_from_2i | 1 |\n | report_from_3i | 1 |\n | report_to_1i | 2010 |\n | report_to_2i | 2 |\n | report_to_3i | 1 |\n</code></pre>\n"
},
{
"answer_id": 2246545,
"author": "Lance",
"author_id": 169992,
"author_profile": "https://Stackoverflow.com/users/169992",
"pm_score": 3,
"selected": false,
"text": "<p>Super hack, but I needed to solve this problem right away for a client project. It's still a bug with Rails 2.3.5.</p>\n\n<p>Using either <code>date_select</code> or <code>datetime_select</code>, if you add this to your model in the <code>initialize</code> method, you can pre-parse the passed form-serialized attributes to make it work:</p>\n\n<pre><code>def initialize(attributes={})\n date_hack(attributes, \"deliver_date\")\n super(attributes)\nend\n\ndef date_hack(attributes, property)\n keys, values = [], []\n attributes.each_key {|k| keys << k if k =~ /#{property}/ }.sort\n keys.each { |k| values << attributes[k]; attributes.delete(k); }\n attributes[property] = values.join(\"-\")\nend\n</code></pre>\n\n<p>I am using this with a nested, polymorphic, model. <a href=\"https://stackoverflow.com/questions/2234077/restfully-destroy-polymorphic-association-in-rails\">Here's a question I had showing the models I'm using</a>. So I needed <code>accepts_nested_attributes_for</code> with a datetime.</p>\n\n<p>Here's the input and output using the console:</p>\n\n<pre><code>e = Event.last\n=> #<Event id: 1052158304 ...>\ne.model_surveys\n=> []\ne.model_surveys_attributes = [{\"survey_id\"=>\"864743981\", \"deliver_date(1i)\"=>\"2010\", \"deliver_date(2i)\"=>\"2\", \"deliver_date(3i)\"=>\"11\"}]\nPRE ATTRIBUTES: {\"survey_id\"=>\"864743981\", \"deliver_date(1i)\"=>\"2010\", \"deliver_date(2i)\"=>\"2\", \"deliver_date(3i)\"=>\"11\"}\n# run date_hack\nPOST ATTRIBUTES: {\"survey_id\"=>\"864743981\", \"deliver_date\"=>\"2010-2-11\"}\ne.model_surveys\n=> [#<ModelSurvey id: 121, ..., deliver_date: \"2010-02-11 05:00:00\">]\n>> e.model_surveys.last.deliver_date.class\n=> ActiveSupport::TimeWithZone\n</code></pre>\n\n<p>Otherwise it was either null, or it would throw the error:</p>\n\n<p><code>1 error(s) on assignment of multiparameter attributes</code></p>\n\n<p>Hope that helps,\nLance</p>\n"
},
{
"answer_id": 2765839,
"author": "mikezter",
"author_id": 109274,
"author_profile": "https://Stackoverflow.com/users/109274",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the ActiveRecord am/pm plugin caused the error through an incorrect <code>alias_method_chain</code> resulting in an <code>StackLevelTooDeep</code> exception.</p>\n\n<p>The plugin was included by the unobtrusive_date_picker plugin.</p>\n\n<p>The look into this before hacking away.</p>\n"
},
{
"answer_id": 3952736,
"author": "nutcracker",
"author_id": 19588,
"author_profile": "https://Stackoverflow.com/users/19588",
"pm_score": 1,
"selected": false,
"text": "<p>Like Zubin I've seen this exception when the form submits a month as a month name rather than a numerical month string (eg. October rather than 10). </p>\n\n<p>One user agent I've encountered seems to submit the contents of the option tag rather than the value attribute:</p>\n\n<blockquote>\n <p>Mozilla/5.0 (SymbianOS/9.2; U;\n Series60/3.1 NokiaE66-1/300.21.012;\n Profile/MIDP-2.0\n Configuration/CLDC-1.1 )\n AppleWebKit/413 (KHTML, like Gecko)\n Safari/413</p>\n</blockquote>\n\n<p>So in the case of submitting a multi-parameter date from a helper generated select (from date_select helper) your params will have:</p>\n\n<pre><code>\"event\"=> {\n \"start_on(2i)\"=>\"October\",\n \"start_on(3i)\"=>\"19\",\n \"start_on(1i)\"=>\"2010\"\n}\n</code></pre>\n\n<p>This creates an exception: <em>ActiveRecord::MultiparameterAssignmentErrors: 1 error(s) on assignment of multiparameter attributes</em></p>\n\n<p>Most user agents will correctly submit:</p>\n\n<pre><code>\"event\"=> {\n \"start_on(2i)\"=>\"10\",\n \"start_on(3i)\"=>\"19\",\n \"start_on(1i)\"=>\"2010\"\n}\n</code></pre>\n"
},
{
"answer_id": 4964837,
"author": "MDaubs",
"author_id": 612373,
"author_profile": "https://Stackoverflow.com/users/612373",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a bug in Rails, it is the intended behavior of the multi-parameter attribute writer. I'm willing to bet that the original poster's deliver_date field in the database is a varchar as opposed to a date or datetime type. ActiveRecord uses each part of the multi-parameter attribute to send to the new method of the serialized type. The number 1, 2, 3, etc indicates the constructor parameter position and the \"i\" tells ActiveRecord to call to_i on the parameter before passing it to the constructor. In this case they are all \"i's\" because DateTime.new(year, month, day) expects three Integers not three Strings.</p>\n\n<p>If the deliver_date column in the database isn't a type that's serialized to a DateTime then ActiveRecord will throw a ActiveRecord::MultiparameterAssignmentErrors exception because String.new(2010,2,11) won't be successful.</p>\n\n<p>Source:\n<a href=\"https://github.com/rails/rails/blob/v3.0.4/activerecord/lib/active_record/base.rb#L1739\" rel=\"nofollow\">https://github.com/rails/rails/blob/v3.0.4/activerecord/lib/active_record/base.rb#L1739</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11078/"
]
| I have a rails form with a datetime\_select field. When I try to submit the form, I get the following exception:
```
ActiveRecord::MultiparameterAssignmentErrors in WidgetsController#update
1 error(s) on assignment of multiparameter attributes
```
If it's a validation error, why don't I see an error on the page?
This is in Rails 2.0.2 | It turns out that rails uses something called Multi-parameter assignment to transmit dates and times in small parts that are reassembled when you assign params to the model instance.
My problem was that I was using a datetime\_select form field for a date model field. It apparently chokes when the multi-parameter magic tries to set the time on a Date object.
The solution was to use a `date_select` form field rather than a `datetime_select`. |
93,294 | <p>So I have a nasty stack overflow I have been trying to track down / solve for the past 8 hours or so, and I'm at the point where i think i need advice. </p>
<p>The details:
Interestingly enough this code runs fine when called in the context of our regular winforms application -- but I am tasked with writing a web-based version of our software, and this same exact code causes the stack overflow when called out of an ASPX page running on IIS. The first thing I did was attach and attempt normal .NET debugging through visual studio. At the point of the exception the call stack seemed relatively shallow (about 11 frames deep, of our code), and I could find none of the usual suspects on a stack overflow (bad recursion, self-calling constructors, exception loops).</p>
<p>So I resigned myself to breaking out windbg and S.O.S. -- which i know can be useful for this sort of thing, although I had limited experience with it myself. After hours of monkeying around I think I have some useful data, but I need some help analyzing it.</p>
<p>First up is a !dumpstack I took while broken just before the stack overflow was about to come down.</p>
<pre><code>0:015> !dumpstack
PDB symbol for mscorwks.dll not loaded
OS Thread Id: 0x1110 (15)
Current frame: ntdll!KiFastSystemCallRet
ChildEBP RetAddr Caller,Callee
01d265a8 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d265ac 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d2661c 79e789c6 mscorwks!LogHelp_NoGuiOnAssert+0x58ca
01d26660 79e7898f mscorwks!LogHelp_NoGuiOnAssert+0x5893, calling mscorwks!LogHelp_NoGuiOnAssert+0x589b
01d26680 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d26694 79fc1d6b mscorwks!CorExeMain+0x8724, calling kernel32!InterlockedDecrement
01d26698 79ef3892 mscorwks!GetCLRFunction+0x107de, calling mscorwks+0x17c0
01d266b0 79e78944 mscorwks!LogHelp_NoGuiOnAssert+0x5848, calling mscorwks!LogHelp_NoGuiOnAssert+0x584c
01d266c4 7a14de5d mscorwks!CorLaunchApplication+0x2f243, calling mscorwks!LogHelp_NoGuiOnAssert+0x5831
01d266ec 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d266f8 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d26714 7c8279bb ntdll!NtSetEvent+0xc
01d26718 77e62321 kernel32!SetEvent+0x10, calling ntdll!NtSetEvent
01d26748 7a14df79 mscorwks!CorLaunchApplication+0x2f35f, calling mscorwks!CorLaunchApplication+0x2f17c
01d2675c 7a022dde mscorwks!NGenCreateNGenWorker+0x4516b, calling mscorwks!CorLaunchApplication+0x2f347
01d26770 79fbc685 mscorwks!CorExeMain+0x303e, calling mscorwks+0x1bbe
01d26788 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d2678c 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d267a8 7a2d259e mscorwks!CreateHistoryReader+0xafd3
01d267b4 7a2e6292 mscorwks!CreateHistoryReader+0x1ecc7, calling mscorwks!CreateHistoryReader+0xaf9d
01d26814 7a064d52 mscorwks!NGenCreateNGenWorker+0x870df, calling mscorwks!CreateHistoryReader+0x1eb43
01d26854 79f91643 mscorwks!ClrCreateManagedInstance+0x46ff, calling mscorwks!ClrCreateManagedInstance+0x4720
01d2688c 79f915c4 mscorwks!ClrCreateManagedInstance+0x4680
01d268b4 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d268cc 79f04e98 mscorwks!GetCLRFunction+0x21de4, calling mscorwks!GetCLRFunction+0x21e4b
01d26900 79f0815e mscorwks!GetCLRFunction+0x250aa, calling mscorwks!GetCLRFunction+0x21d35
01d2691c 7c858135 ntdll!RtlIpv4StringToAddressExW+0x167b7, calling ntdll!RtlReleaseResource
01d2692c 79f080a7 mscorwks!GetCLRFunction+0x24ff3, calling mscorwks!GetCLRFunction+0x25052
01d26950 7c828752 ntdll!RtlRaiseStatus+0xe0
01d26974 7c828723 ntdll!RtlRaiseStatus+0xb1, calling ntdll!RtlRaiseStatus+0xba
01d26998 7c8315c2 ntdll!RtlSubtreePredecessor+0x208, calling ntdll!RtlRaiseStatus+0x7e
01d26a1c 7c82855e ntdll!KiUserExceptionDispatcher+0xe, calling ntdll!RtlSubtreePredecessor+0x17c
01d26d20 13380333 (MethodDesc 0x10936710 +0x243 ASI.ParadigmPlus.LoadedWindows.WID904.QuestionChangeLogic(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Question)) ====> Exception Code 0 cxr@1d26a54 exr@1d26000
01d26bd8 77e64590 kernel32!VirtualAllocEx+0x4b, calling kernel32!GetTickCount+0x73
01d26bec 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d26bf0 79e78d11 mscorwks!LogHelp_NoGuiOnAssert+0x5c15, calling ntdll!RtlFreeHeap
01d3e86c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e88c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e8b0 103b3e6b (MethodDesc 0xebb4b38 +0x23 ASI.CommonLibrary.ASIArrayList3.get_Item(Int32))
01d3e8d4 103b3d70 (MethodDesc 0xf304e98 +0x1b0 ASI.ParadigmPlus.Window.TrackQuestionChange())
01d3e910 0f90febf (MethodDesc 0xf30d250 +0x190f ASI.ParadigmPlus.Data.RemoteDataAccess.GetWindow(Int32))
01d3ec0c 10a2a572 (MethodDesc 0x10935aa0 +0x1f2 ASI.ParadigmPlus.LoadedWindowSets.WSID904.ApplyLayoutChanges()), calling 02259472
01d3ecec 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed0c 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed54 0f4d2388 (MethodDesc 0x22261a0 +0x5e8 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f264 0f4d1d7f (MethodDesc 0x2226180 +0x47 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs)), calling (MethodDesc 0x22261a0 +0 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f284 0e810a05 (MethodDesc 0x22260f8 +0x145 WebConfigurator.NewDefault.Page_Load(System.Object, System.EventArgs)), calling (MethodDesc 0x2226180 +0 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs))
01d3f2a8 793ae896 (MethodDesc 0x79256848 +0x52 System.MulticastDelegate.RemoveImpl(System.Delegate))
01d3f2ac 79e7bee8 mscorwks!LogHelp_TerminateOnAssert+0x2bd0, calling mscorwks!LogHelp_TerminateOnAssert+0x2b60
01d3f2c4 66f12980 (MethodDesc 0x66f1bcd0 +0x10 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2d0 6628efd2 (MethodDesc 0x66474328 +0x22 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(System.Object, System.EventArgs)), calling (MethodDesc 0x66f1bcd0 +0 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2e4 6613cb04 (MethodDesc 0x66468a58 +0x64 System.Web.UI.Control.OnLoad(System.EventArgs))
01d3f2f8 6613cb50 (MethodDesc 0x66468a60 +0x30 System.Web.UI.Control.LoadRecursive())
01d3f30c 6614e12d (MethodDesc 0x66467688 +0x59d System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f4e0 6614c717 (MethodDesc 0x66467430 +0x63 System.Web.UI.Page.AddWrappedFileDependencies(System.Object)), calling (MethodDesc 0x66478de8 +0 System.Web.ResponseDependencyList.AddDependencies(System.String[], System.String, Boolean, System.String))
01d3f504 6614d8c3 (MethodDesc 0x66467650 +0x67 System.Web.UI.Page.ProcessRequest(Boolean, Boolean)), calling (MethodDesc 0x66467688 +0 System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f528 79371311 (MethodDesc 0x7925ac80 +0x25 System.Globalization.CultureInfo.get_UserDefaultUICulture()), calling (JitHelp: CORINFO_HELP_GETSHARED_GCSTATIC_BASE)
01d3f53c 6614d80f (MethodDesc 0x66467648 +0x57 System.Web.UI.Page.ProcessRequest()), calling (MethodDesc 0x66467650 +0 System.Web.UI.Page.ProcessRequest(Boolean, Boolean))
01d3f560 6615055c (MethodDesc 0x664676f0 +0x184 System.Web.UI.Page.SetIntrinsics(System.Web.HttpContext, Boolean)), calling (MethodDesc 0x664726b0 +0 System.Web.UI.TemplateControl.HookUpAutomaticHandlers())
01d3f578 6614d72f (MethodDesc 0x66467630 +0x13 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext)), calling (MethodDesc 0x66467648 +0 System.Web.UI.Page.ProcessRequest())
01d3f580 6614d6c2 (MethodDesc 0x66467620 +0x32 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467630 +0 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext))
01d3f594 0e810206 (MethodDesc 0x22265a0 +0x1e ASP.newdefault_aspx.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467620 +0 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext))
01d3f5a0 65fe6bfb (MethodDesc 0x66470fc0 +0x167 System.Web.HttpApplication+CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()), calling 01dee5da
01d3f5d4 65fe3f51 (MethodDesc 0x6642f090 +0x41 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef)), calling 01de7d0a
01d3f610 65fe7733 (MethodDesc 0x66470cd0 +0x1b3 System.Web.HttpApplication+ApplicationStepManager.ResumeSteps(System.Exception)), calling (MethodDesc 0x6642f090 +0 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef))
01d3f64c 7939eef2 (MethodDesc 0x7925eda8 +0x26 System.Runtime.InteropServices.GCHandle.Alloc(System.Object)), calling mscorwks!InstallCustomModule+0x1e8d
01d3f664 65fccbfe (MethodDesc 0x6642ebb0 +0x8e System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext, System.AsyncCallback, System.Object))
01d3f678 65fd19c5 (MethodDesc 0x6642cde8 +0x1b5 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest)), calling 01de7cba
01d3f69c 7938111c (MethodDesc 0x79262df0 +0xc System.DateTime.get_UtcNow()), calling mscorwks!GetCLRFunction+0x109f9
01d3f6a4 01c32cbc 01c32cbc, calling 01daa248
01d3f6b4 65fd16b2 (MethodDesc 0x664619e0 +0x62 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest)), calling (MethodDesc 0x6642cde8 +0 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest))
01d3f6c0 65fcfa6d (MethodDesc 0x6642d4a0 +0xfd System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling (MethodDesc 0x664619e0 +0 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest))
01d3f6d8 65fcf9f4 (MethodDesc 0x6642d4a0 +0x84 System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling *** ERROR: Symbol file could not be found. Defaulted to export symbols for \\?\C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\webengine.dll -
webengine!GetEcb
01d3f710 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f720 01c32cbc 01c32cbc, calling 01daa248
01d3f730 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f75c 79f01621 mscorwks!GetCLRFunction+0x1e56d, calling mscorwks+0x1b86
01d3f770 79ef98cf mscorwks!GetCLRFunction+0x1681b, calling mscorwks!GetCLRFunction+0x1682f
01d3f7d0 79e74f98 mscorwks!LogHelp_NoGuiOnAssert+0x1e9c, calling mscorwks!LogHelp_NoGuiOnAssert+0x1ec1
01d3f7e8 79f0462c mscorwks!GetCLRFunction+0x21578, calling mscorwks!GetCLRFunction+0x215b0
01d3f7f8 01c32cbc 01c32cbc, calling 01daa248
01d3f844 79f044fa mscorwks!GetCLRFunction+0x21446, calling mscorwks!GetCLRFunction+0x21541
01d3f854 01c32cbc 01c32cbc, calling 01daa248
01d3f898 660167e9 (MethodDesc 0x6646f6b0 +0x5 System.Web.RequestQueue.TimerCompletionCallback(System.Object)), calling (MethodDesc 0x6646f698 +0 System.Web.RequestQueue.ScheduleMoreWorkIfNeeded())
01d3f89c 793af6c6 (MethodDesc 0x792672b0 +0x1a System.Threading._TimerCallback.TimerCallback_Context(System.Object))
01d3f8b4 793af647 (MethodDesc 0x7914fc18 +0x5b System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling (MethodDesc 0x7914e0d8 +0 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object))
01d3f8b8 793af654 (MethodDesc 0x7914fc18 +0x68 System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling mscorwks!LogHelp_TerminateOnAssert
01d3f8f8 79e74466 mscorwks!LogHelp_NoGuiOnAssert+0x136a, calling mscorwks+0x1813
01d3f8fc 79e7c709 mscorwks!LogHelp_TerminateOnAssert+0x33f1, calling mscorwks!LogHelp_NoGuiOnAssert+0x1360
01d3f964 7c829f3d ntdll!RtlFreeHeap+0x126, calling ntdll!RtlGetNtGlobalFlags+0x12
01d3f96c 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d3f9ac 6a2a9998 webengine!CSharelock::ChangeExclusiveLockToSharedLock+0x2d, calling kernel32!InterlockedCompareExchange
01d3f9b4 6a2ab03b webengine!EcbGetUnicodeServerVariables+0x3d5, calling kernel32!InterlockedIncrement
01d3f9f4 01c32cbc 01c32cbc, calling 01daa248
01d3fa28 01daa295 01daa295, calling mscorwks!GetCLRFunction+0x2119e
01d3fa50 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fa6c 01c32cbc 01c32cbc, calling 01daa248
01d3fa70 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fac8 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d3facc 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d3fad8 79f00c03 mscorwks!GetCLRFunction+0x1db4f, calling mscorwks!LogHelp_NoGuiOnAssert+0xf0
01d3fadc 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fae0 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb1c 79ef30c3 mscorwks!GetCLRFunction+0x1000f, calling mscorwks!GetCLRFunction+0x10040
01d3fb64 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb68 79f02a93 mscorwks!GetCLRFunction+0x1f9df, calling mscorwks!GetCLRFunction+0x1d8e5
01d3fb70 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fb74 79f02aa7 mscorwks!GetCLRFunction+0x1f9f3, calling mscorwks+0x1b86
01d3fb88 79f00e8d mscorwks!GetCLRFunction+0x1ddd9, calling mscorwks+0x18bb
01d3fb8c 79f00f03 mscorwks!GetCLRFunction+0x1de4f, calling mscorwks!GetCLRFunction+0x1dd84
01d3fbc0 79f02978 mscorwks!GetCLRFunction+0x1f8c4, calling mscorwks!GetCLRFunction+0x1de1a
01d3fbfc 79e73220 mscorwks!LogHelp_NoGuiOnAssert+0x124, calling (JitHelp: CORINFO_HELP_GET_THREAD)
01d3fc08 79ef2884 mscorwks!GetCLRFunction+0xf7d0, calling mscorwks!LogHelp_NoGuiOnAssert+0x118
01d3fc0c 79ef28ab mscorwks!GetCLRFunction+0xf7f7, calling mscorwks+0x17c0
01d3fc24 79e7904f mscorwks!LogHelp_NoGuiOnAssert+0x5f53, calling mscorwks+0x1b95
01d3fc38 79ef31ca mscorwks!GetCLRFunction+0x10116, calling mscorwks!LogHelp_NoGuiOnAssert+0x5f3d
01d3fc3c 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fc40 79ef31d9 mscorwks!GetCLRFunction+0x10125, calling mscorwks+0x1b86
01d3fc90 7c829fb5 ntdll!RtlGetNtGlobalFlags+0x38, calling ntdll!ExpInterlockedPopEntrySListEnd+0x11
01d3fc94 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d3fc98 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d3fca4 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d3fdb4 6a2aa748 webengine!CookieAuthConstructTicket+0x33b, calling webengine!CookieAuthConstructTicket+0x11d
01d3fdc4 6a2aa715 webengine!CookieAuthConstructTicket+0x308
01d3fddc 79f024cf mscorwks!GetCLRFunction+0x1f41b
01d3fdf4 79ef3a3f mscorwks!GetCLRFunction+0x1098b, calling mscorwks+0x17c0
01d3fe28 79f0202a mscorwks!GetCLRFunction+0x1ef76
01d3fe3c 79f021a0 mscorwks!GetCLRFunction+0x1f0ec, calling mscorwks!GetCLRFunction+0x1eef9
01d3fe94 79fc9840 mscorwks!CorExeMain+0x101f9
01d3ffa4 79fc982e mscorwks!CorExeMain+0x101e7, calling mscorwks!LogHelp_NoGuiOnAssert+0x61c0
01d3ffb8 77e64829 kernel32!GetModuleHandleA+0xdf
</code></pre>
<p>Lot of stuff there, but nothing that in my (admittedly limited) stack analyzing knowledge indicates looping. I think this next section might have some value however. This is a !dumpstackobjects I got at the same breakpoint:</p>
<pre><code>0:000> ~16e !dumpstackobjects
OS Thread Id: 0x172c (16)
ESP/REG Object Name
01d0ee30 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef68 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef6c 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef74 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0f280 0295f810 ASI.ParadigmPlus.Question
01d0f284 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cec 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cf0 0295f674 ASI.ParadigmPlus.QuestionList
01d26cf4 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cf8 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cfc 0295f810 ASI.ParadigmPlus.Question
01d26d00 0295f810 ASI.ParadigmPlus.Question
01d26d08 0295f810 ASI.ParadigmPlus.Question
01d26d30 06c3a958 System.String SP1:SP1
01d26d40 029c232c System.String TNE:TNE
01d26d50 06c3a958 System.String SP1:SP1
01d26d54 029c232c System.String TNE:TNE
01d26d60 029c232c System.String TNE:TNE
01d26d78 06c3a958 System.String SP1:SP1
01d26d7c 06c3a958 System.String SP1:SP1
01d26d84 06c3a958 System.String SP1:SP1
01d26da4 06c357a0 System.String SB1:SB1
01d26da8 06c357a0 System.String SB1:SB1
01d26db0 06c3a958 System.String SP1:SP1
01d26db4 06ba3d08 System.String WHT:WHT
01d26db8 06b987c8 System.String WHT:WHT
01d26dbc 06b8aa10 System.String WF:WF
01d26dc0 029fab00 System.String L:L
01d26dc4 06c3a958 System.String SP1:SP1
01d26dc8 06c4a518 System.String S000:S000
01d26dd4 06c4a518 System.String S000:S000
01d26dd8 0296b404 ASI.ParadigmPlus.Question
01d26ddc 0296a00c ASI.ParadigmPlus.Question
01d26de0 02968a90 ASI.ParadigmPlus.Question
01d26de4 02966af8 ASI.ParadigmPlus.Question
01d26de8 06be6e1c ASI.ParadigmPlus.Answer
01d26dec 06c357a0 System.String SB1:SB1
01d26df0 029fab00 System.String L:L
01d26df4 0295fa54 ASI.ParadigmPlus.QuestionGroup
01d26df8 02963f80 ASI.ParadigmPlus.QuestionGroup
01d26dfc 029662fc ASI.ParadigmPlus.QuestionGroup
01d26e00 02961cb4 ASI.ParadigmPlus.QuestionGroup
01d26e0c 0295f810 ASI.ParadigmPlus.Question
01d26e10 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d270d4 06c38ddc ASI.ParadigmPlus.Answer
01d270dc 06c4bc0c ASI.ParadigmPlus.Dimension
01d270e0 06c4b99c ASI.ParadigmPlus.DimensionList
01d27104 029607f8 ASI.ParadigmPlus.Question
01d27108 0295fa80 ASI.ParadigmPlus.QuestionList
01d27118 06c38e74 System.String 5:5
01d2711c 02960564 ASI.ParadigmPlus.Question
01d27120 0295fa80 ASI.ParadigmPlus.QuestionList
01d2781c 029fac84 ASI.ParadigmPlus.Answer
01d27820 02960464 ASI.ParadigmPlus.AnswerList
01d27824 029fcbd8 ASI.ParadigmPlus.Answer
01d27828 02960464 ASI.ParadigmPlus.AnswerList
01d2782c 029fca28 ASI.ParadigmPlus.Answer
01d27830 02960464 ASI.ParadigmPlus.AnswerList
01d27844 029faa84 ASI.ParadigmPlus.Answer
01d2784c 06c38e74 System.String 5:5
01d27850 02960564 ASI.ParadigmPlus.Question
01d27854 0295fa80 ASI.ParadigmPlus.QuestionList
01d27860 06c38e74 System.String 5:5
01d27864 02960564 ASI.ParadigmPlus.Question
01d27868 0295fa80 ASI.ParadigmPlus.QuestionList
01d27870 06c38e74 System.String 5:5
01d27874 02960564 ASI.ParadigmPlus.Question
01d27878 0295fa80 ASI.ParadigmPlus.QuestionList
01d2787c 029faa84 ASI.ParadigmPlus.Answer
01d27880 02960464 ASI.ParadigmPlus.AnswerList
01d27884 029fab84 ASI.ParadigmPlus.Answer
01d27888 02960464 ASI.ParadigmPlus.AnswerList
01d27974 02960e80 ASI.ParadigmPlus.Question
01d27978 0295fa80 ASI.ParadigmPlus.QuestionList
01d27bd0 06c3a8dc ASI.ParadigmPlus.Answer
01d27c08 06c3b924 ASI.ParadigmPlus.Answer
01d27c0c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c10 06c3b860 ASI.ParadigmPlus.Answer
01d27c14 02960f44 ASI.ParadigmPlus.AnswerList
01d27c18 06c3ac90 ASI.ParadigmPlus.Answer
01d27c1c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c20 06c3abcc ASI.ParadigmPlus.Answer
01d27c24 02960f44 ASI.ParadigmPlus.AnswerList
01d27c28 06c3ab08 ASI.ParadigmPlus.Answer
01d27c2c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c30 06c3aa44 ASI.ParadigmPlus.Answer
01d27c34 02960f44 ASI.ParadigmPlus.AnswerList
01d27c38 06c3b4dc ASI.ParadigmPlus.Answer
01d27c3c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c40 06c3a990 ASI.ParadigmPlus.Answer
01d27c44 02960f44 ASI.ParadigmPlus.AnswerList
01d27c48 06c3a8dc ASI.ParadigmPlus.Answer
01d27c4c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c6c 02960e80 ASI.ParadigmPlus.Question
01d27c70 0295fa80 ASI.ParadigmPlus.QuestionList
01d27e04 029628d0 ASI.ParadigmPlus.Question
01d27e08 02961ce0 ASI.ParadigmPlus.QuestionList
01d27e28 029628d0 ASI.ParadigmPlus.Question
01d27e2c 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f14 06b89804 ASI.ParadigmPlus.Answer
01d27f18 02962994 ASI.ParadigmPlus.AnswerList
01d27f1c 029628d0 ASI.ParadigmPlus.Question
01d27f20 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f38 06c38e74 System.String 5:5
01d27f3c 02960564 ASI.ParadigmPlus.Question
01d27f40 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f4c 06c38e74 System.String 5:5
01d27f50 02960564 ASI.ParadigmPlus.Question
01d27f54 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f60 06c38e74 System.String 5:5
01d27f64 02960564 ASI.ParadigmPlus.Question
01d27f68 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f88 06b89964 ASI.ParadigmPlus.Answer
01d27f8c 029628d0 ASI.ParadigmPlus.Question
01d27f90 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fa8 06c4b34c System.String FDIA:FDIA
01d27fac 0295fd84 ASI.ParadigmPlus.Question
01d27fb0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fb4 06b896dc ASI.ParadigmPlus.Answer
01d27fb8 02962994 ASI.ParadigmPlus.AnswerList
01d27fbc 029628d0 ASI.ParadigmPlus.Question
01d27fc0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fc8 029fab00 System.String L:L
01d27fcc 029603a0 ASI.ParadigmPlus.Question
01d27fd0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fd4 06b89964 ASI.ParadigmPlus.Answer
01d27fd8 02962994 ASI.ParadigmPlus.AnswerList
01d27fdc 029628d0 ASI.ParadigmPlus.Question
01d27fe0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fe4 029628d0 ASI.ParadigmPlus.Question
01d27fe8 02961ce0 ASI.ParadigmPlus.QuestionList
01d28610 06b987c8 System.String WHT:WHT
01d28614 02961dd8 ASI.ParadigmPlus.Question
01d28618 02961ce0 ASI.ParadigmPlus.QuestionList
01d2872c 06ba3d08 System.String WHT:WHT
01d28730 029621f0 ASI.ParadigmPlus.Question
01d28734 02961ce0 ASI.ParadigmPlus.QuestionList
01d28778 029f1d94 ASI.ParadigmPlus.Answer
01d2877c 02963c14 ASI.ParadigmPlus.AnswerList
01d28780 06c37884 ASI.ParadigmPlus.Answer
01d28784 02963c14 ASI.ParadigmPlus.AnswerList
01d28788 06c379cc ASI.ParadigmPlus.Answer
01d2878c 02963c14 ASI.ParadigmPlus.AnswerList
01d28790 06c36798 ASI.ParadigmPlus.Answer
01d28794 02963c14 ASI.ParadigmPlus.AnswerList
01d28798 06c36510 ASI.ParadigmPlus.Answer
01d2879c 02963c14 ASI.ParadigmPlus.AnswerList
01d287a0 06c36648 ASI.ParadigmPlus.Answer
01d287a4 02963c14 ASI.ParadigmPlus.AnswerList
01d287ac 06c37a78 System.String Custom Paint
01d287b0 06c379cc ASI.ParadigmPlus.Answer
01d287b8 072eb468 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d287bc 02963c14 ASI.ParadigmPlus.AnswerList
01d289dc 029640b8 ASI.ParadigmPlus.Question
01d289e0 02963fac ASI.ParadigmPlus.QuestionList
01d28a38 029f13f4 System.String Venting Sidelite Locking System
01d28a3c 029f1390 ASI.ParadigmPlus.Answer
01d28a44 072f0568 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28a48 0296417c ASI.ParadigmPlus.AnswerList
01d28a60 06c356f4 ASI.ParadigmPlus.Answer
01d28a68 06c4a518 System.String S000:S000
01d28a6c 0295ffec ASI.ParadigmPlus.Question
01d28a70 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a7c 06c4a518 System.String S000:S000
01d28a80 0295ffec ASI.ParadigmPlus.Question
01d28a84 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a90 0295f768 System.String CustItemNumber
01d28a98 06c4b34c System.String FDIA:FDIA
01d28a9c 0295fd84 ASI.ParadigmPlus.Question
01d28aa0 0295fa80 ASI.ParadigmPlus.QuestionList
01d28aa4 029ecd64 ASI.ParadigmPlus.Answer
01d28aa8 0296417c ASI.ParadigmPlus.AnswerList
01d28aac 029e95ac ASI.ParadigmPlus.Answer
01d28ab0 0296417c ASI.ParadigmPlus.AnswerList
01d28ab8 029f13f4 System.String Venting Sidelite Locking System
01d28abc 029f1390 ASI.ParadigmPlus.Answer
01d28ac4 072ef574 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28ac8 0296417c ASI.ParadigmPlus.AnswerList
01d28acc 029f1230 ASI.ParadigmPlus.Answer
01d28ad0 0296417c ASI.ParadigmPlus.AnswerList
01d28f4c 02961798 ASI.ParadigmPlus.Question
01d28f50 0295fa80 ASI.ParadigmPlus.QuestionList
01d2903c 0296466c ASI.ParadigmPlus.Question
01d29040 02963fac ASI.ParadigmPlus.QuestionList
01d290cc 06c07914 System.String C:C
01d290d0 02964268 ASI.ParadigmPlus.Question
01d290d4 02963fac ASI.ParadigmPlus.QuestionList
01d29144 06c30604 ASI.ParadigmPlus.Answer
01d29148 02964730 ASI.ParadigmPlus.AnswerList
01d2914c 0296466c ASI.ParadigmPlus.Question
01d29150 02963fac ASI.ParadigmPlus.QuestionList
01d29154 06c0f9d8 ASI.ParadigmPlus.Answer
01d29158 0296450c ASI.ParadigmPlus.AnswerList
01d2915c 02964448 ASI.ParadigmPlus.Question
01d29160 02963fac ASI.ParadigmPlus.QuestionList
01d29164 02964268 ASI.ParadigmPlus.Question
01d29168 02963fac ASI.ParadigmPlus.QuestionList
01d2991c 029d6c7c System.String 021022
01d29928 029d6c7c System.String 021022
01d29934 029d6c7c System.String 021022
01d29938 029d5700 ASI.ParadigmPlus.Answer
01d2993c 0296450c ASI.ParadigmPlus.AnswerList
01d29940 029d6bdc ASI.ParadigmPlus.Answer
01d29944 0296450c ASI.ParadigmPlus.AnswerList
01d29948 02964448 ASI.ParadigmPlus.Question
01d2994c 02963fac ASI.ParadigmPlus.QuestionList
01d2f908 06c4b34c System.String FDIA:FDIA
01d2f90c 0295fd84 ASI.ParadigmPlus.Question
01d2f910 0295fa80 ASI.ParadigmPlus.QuestionList
01d2ffd0 02964c28 ASI.ParadigmPlus.Question
01d2ffd4 02963fac ASI.ParadigmPlus.QuestionList
01d2ffe4 06c32030 System.String SB:SB
01d2ffe8 02964a54 ASI.ParadigmPlus.Question
01d2ffec 02963fac ASI.ParadigmPlus.QuestionList
01d2fffc 06c3368c ASI.ParadigmPlus.Answer
01d30000 02964b18 ASI.ParadigmPlus.AnswerList
01d30004 02964a54 ASI.ParadigmPlus.Question
01d30008 02963fac ASI.ParadigmPlus.QuestionList
01d3000c 02964a54 ASI.ParadigmPlus.Question
01d30010 02963fac ASI.ParadigmPlus.QuestionList
01d30144 06c32030 System.String SB:SB
01d30148 02964a54 ASI.ParadigmPlus.Question
01d3014c 02963fac ASI.ParadigmPlus.QuestionList
01d30154 06c31f90 ASI.ParadigmPlus.Answer
01d3015c 06c344d8 System.String (COM) Lifetime Brass
01d30160 06c34418 ASI.ParadigmPlus.Answer
01d30168 072f16a0 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d3016c 02964b18 ASI.ParadigmPlus.AnswerList
01d30174 06c31f90 ASI.ParadigmPlus.Answer
01d30178 06c34294 ASI.ParadigmPlus.Answer
01d3017c 02964b18 ASI.ParadigmPlus.AnswerList
01d30180 06c33e48 ASI.ParadigmPlus.Answer
01d30184 02964b18 ASI.ParadigmPlus.AnswerList
01d30188 06c32e6c ASI.ParadigmPlus.Answer
01d3018c 02964b18 ASI.ParadigmPlus.AnswerList
01d30190 06c32b78 ASI.ParadigmPlus.Answer
01d30194 02964b18 ASI.ParadigmPlus.AnswerList
</code></pre>
<p>^^ I had to cut off some of the above to make this post fit, but imagine it keeps going like that ^^</p>
<p>Please ignore the details of our custom code. All this seems excessive to me, but I am no expert at the stack. Most of those stack objects listed above (there are 1500+) are not function paramteters, so I would think they do not belong there. Here is an example of the kind of code that is generating all those items on the stack (tons of code like this is run):</p>
<pre><code>gUnitType.Questions("French Door Style").CommonLogicValue = CommonLogicValues.AlwaysDisplay
gUnitType.Questions("French Door Style").ShowAllAnswers()
If Me.NumberOfUnits > 1 Then
Me.Dimensions("Call Size Height").Answers("6-8 Handicap sill").Visible = False
Me.Dimensions("Call Size Height").Answers("6-10 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("7-0 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("8-0 Handicap Sill").Visible = False
End If
</code></pre>
<p>I am also no expert on VB (this code is from a different part of our application I do not normally work with), but is it normal for code like this to be filling up the stack with stuff? If anyone has any insight, or could even just point me in the direction of some resources with info about this kind of stuff, it would be greatly appreciated. Thanks for looking!</p>
| [
{
"answer_id": 93367,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": "<p>You need some decent symbols for the CLR. Set <code>_NT_SYMBOL_PATH</code> (in WinDBG, use File/Symbol File Path) so that it includes:</p>\n\n<pre><code>SRV*C:\\WebSymbols*http://msdl.microsoft.com/download/symbols\n</code></pre>\n\n<p>That tells the debugger symbol engine that it can download symbols from Microsoft's online symbol server to C:\\WebSymbols. Pick another folder if you prefer them to be cached elsewhere.</p>\n\n<p>It looks like Question, QuestionList, Answer, etc are <code>struct</code>s - that is, value types - so they're allocated on the stack rather than on the heap. You may need to create your own <code>class</code> that wraps these types so they're on the heap instead.</p>\n"
},
{
"answer_id": 93391,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 0,
"selected": false,
"text": "<p>According to stack object dump \"ASI.ParadigmPlus.GrilleApp.GA1000\" is 96872 bytes. You might want to figure out what that object is all about. That's a pretty big chunk of your stack space right there.</p>\n"
},
{
"answer_id": 107682,
"author": "sachaa",
"author_id": 1152057,
"author_profile": "https://Stackoverflow.com/users/1152057",
"pm_score": 0,
"selected": false,
"text": "<p>Analyzing the callstack I clearly see that the method that is causing this exception is:</p>\n\n<pre><code>ASI.ParadigmPlus.LoadedWindows.WID904.QuestionChangeLogic\n</code></pre>\n\n<p>How come you have 315 variables in this method? Isn't that too much?</p>\n\n<p>\"!clrstack -a\" (after running \"!dso\") should give you much more information of each managed frame.</p>\n"
},
{
"answer_id": 175031,
"author": "David Hay",
"author_id": 17784,
"author_profile": "https://Stackoverflow.com/users/17784",
"pm_score": 4,
"selected": true,
"text": "<p>I thought I'd post back here with the resolution to this in case someone else runs into it. The replies above were all helpful, and pointed out why i might be overflowing the stack -- but the thing that I still couldn't come to grips with was why the exact same code ran fine in our winforms app. </p>\n\n<p>What I eventually discovered was that at some point microsoft changed the stack size of IIS threads from 1MB (like in the general .NET context) to 256k. This explained everything, including the especially frustrating fact that even the ASPX version ran fine under the visual studio dev server. I resolved the problem by working with this particular customer to drastically cut the ammount of code in the QuestionChangeLogic function mentioned above (when I looked up the source, the function had > 15,000 lines!).</p>\n\n<p>Thanks for the help guys.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17784/"
]
| So I have a nasty stack overflow I have been trying to track down / solve for the past 8 hours or so, and I'm at the point where i think i need advice.
The details:
Interestingly enough this code runs fine when called in the context of our regular winforms application -- but I am tasked with writing a web-based version of our software, and this same exact code causes the stack overflow when called out of an ASPX page running on IIS. The first thing I did was attach and attempt normal .NET debugging through visual studio. At the point of the exception the call stack seemed relatively shallow (about 11 frames deep, of our code), and I could find none of the usual suspects on a stack overflow (bad recursion, self-calling constructors, exception loops).
So I resigned myself to breaking out windbg and S.O.S. -- which i know can be useful for this sort of thing, although I had limited experience with it myself. After hours of monkeying around I think I have some useful data, but I need some help analyzing it.
First up is a !dumpstack I took while broken just before the stack overflow was about to come down.
```
0:015> !dumpstack
PDB symbol for mscorwks.dll not loaded
OS Thread Id: 0x1110 (15)
Current frame: ntdll!KiFastSystemCallRet
ChildEBP RetAddr Caller,Callee
01d265a8 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d265ac 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d2661c 79e789c6 mscorwks!LogHelp_NoGuiOnAssert+0x58ca
01d26660 79e7898f mscorwks!LogHelp_NoGuiOnAssert+0x5893, calling mscorwks!LogHelp_NoGuiOnAssert+0x589b
01d26680 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d26694 79fc1d6b mscorwks!CorExeMain+0x8724, calling kernel32!InterlockedDecrement
01d26698 79ef3892 mscorwks!GetCLRFunction+0x107de, calling mscorwks+0x17c0
01d266b0 79e78944 mscorwks!LogHelp_NoGuiOnAssert+0x5848, calling mscorwks!LogHelp_NoGuiOnAssert+0x584c
01d266c4 7a14de5d mscorwks!CorLaunchApplication+0x2f243, calling mscorwks!LogHelp_NoGuiOnAssert+0x5831
01d266ec 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d266f8 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d26714 7c8279bb ntdll!NtSetEvent+0xc
01d26718 77e62321 kernel32!SetEvent+0x10, calling ntdll!NtSetEvent
01d26748 7a14df79 mscorwks!CorLaunchApplication+0x2f35f, calling mscorwks!CorLaunchApplication+0x2f17c
01d2675c 7a022dde mscorwks!NGenCreateNGenWorker+0x4516b, calling mscorwks!CorLaunchApplication+0x2f347
01d26770 79fbc685 mscorwks!CorExeMain+0x303e, calling mscorwks+0x1bbe
01d26788 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d2678c 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d267a8 7a2d259e mscorwks!CreateHistoryReader+0xafd3
01d267b4 7a2e6292 mscorwks!CreateHistoryReader+0x1ecc7, calling mscorwks!CreateHistoryReader+0xaf9d
01d26814 7a064d52 mscorwks!NGenCreateNGenWorker+0x870df, calling mscorwks!CreateHistoryReader+0x1eb43
01d26854 79f91643 mscorwks!ClrCreateManagedInstance+0x46ff, calling mscorwks!ClrCreateManagedInstance+0x4720
01d2688c 79f915c4 mscorwks!ClrCreateManagedInstance+0x4680
01d268b4 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d268cc 79f04e98 mscorwks!GetCLRFunction+0x21de4, calling mscorwks!GetCLRFunction+0x21e4b
01d26900 79f0815e mscorwks!GetCLRFunction+0x250aa, calling mscorwks!GetCLRFunction+0x21d35
01d2691c 7c858135 ntdll!RtlIpv4StringToAddressExW+0x167b7, calling ntdll!RtlReleaseResource
01d2692c 79f080a7 mscorwks!GetCLRFunction+0x24ff3, calling mscorwks!GetCLRFunction+0x25052
01d26950 7c828752 ntdll!RtlRaiseStatus+0xe0
01d26974 7c828723 ntdll!RtlRaiseStatus+0xb1, calling ntdll!RtlRaiseStatus+0xba
01d26998 7c8315c2 ntdll!RtlSubtreePredecessor+0x208, calling ntdll!RtlRaiseStatus+0x7e
01d26a1c 7c82855e ntdll!KiUserExceptionDispatcher+0xe, calling ntdll!RtlSubtreePredecessor+0x17c
01d26d20 13380333 (MethodDesc 0x10936710 +0x243 ASI.ParadigmPlus.LoadedWindows.WID904.QuestionChangeLogic(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Question)) ====> Exception Code 0 cxr@1d26a54 exr@1d26000
01d26bd8 77e64590 kernel32!VirtualAllocEx+0x4b, calling kernel32!GetTickCount+0x73
01d26bec 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d26bf0 79e78d11 mscorwks!LogHelp_NoGuiOnAssert+0x5c15, calling ntdll!RtlFreeHeap
01d3e86c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e88c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e8b0 103b3e6b (MethodDesc 0xebb4b38 +0x23 ASI.CommonLibrary.ASIArrayList3.get_Item(Int32))
01d3e8d4 103b3d70 (MethodDesc 0xf304e98 +0x1b0 ASI.ParadigmPlus.Window.TrackQuestionChange())
01d3e910 0f90febf (MethodDesc 0xf30d250 +0x190f ASI.ParadigmPlus.Data.RemoteDataAccess.GetWindow(Int32))
01d3ec0c 10a2a572 (MethodDesc 0x10935aa0 +0x1f2 ASI.ParadigmPlus.LoadedWindowSets.WSID904.ApplyLayoutChanges()), calling 02259472
01d3ecec 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed0c 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed54 0f4d2388 (MethodDesc 0x22261a0 +0x5e8 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f264 0f4d1d7f (MethodDesc 0x2226180 +0x47 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs)), calling (MethodDesc 0x22261a0 +0 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f284 0e810a05 (MethodDesc 0x22260f8 +0x145 WebConfigurator.NewDefault.Page_Load(System.Object, System.EventArgs)), calling (MethodDesc 0x2226180 +0 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs))
01d3f2a8 793ae896 (MethodDesc 0x79256848 +0x52 System.MulticastDelegate.RemoveImpl(System.Delegate))
01d3f2ac 79e7bee8 mscorwks!LogHelp_TerminateOnAssert+0x2bd0, calling mscorwks!LogHelp_TerminateOnAssert+0x2b60
01d3f2c4 66f12980 (MethodDesc 0x66f1bcd0 +0x10 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2d0 6628efd2 (MethodDesc 0x66474328 +0x22 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(System.Object, System.EventArgs)), calling (MethodDesc 0x66f1bcd0 +0 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2e4 6613cb04 (MethodDesc 0x66468a58 +0x64 System.Web.UI.Control.OnLoad(System.EventArgs))
01d3f2f8 6613cb50 (MethodDesc 0x66468a60 +0x30 System.Web.UI.Control.LoadRecursive())
01d3f30c 6614e12d (MethodDesc 0x66467688 +0x59d System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f4e0 6614c717 (MethodDesc 0x66467430 +0x63 System.Web.UI.Page.AddWrappedFileDependencies(System.Object)), calling (MethodDesc 0x66478de8 +0 System.Web.ResponseDependencyList.AddDependencies(System.String[], System.String, Boolean, System.String))
01d3f504 6614d8c3 (MethodDesc 0x66467650 +0x67 System.Web.UI.Page.ProcessRequest(Boolean, Boolean)), calling (MethodDesc 0x66467688 +0 System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f528 79371311 (MethodDesc 0x7925ac80 +0x25 System.Globalization.CultureInfo.get_UserDefaultUICulture()), calling (JitHelp: CORINFO_HELP_GETSHARED_GCSTATIC_BASE)
01d3f53c 6614d80f (MethodDesc 0x66467648 +0x57 System.Web.UI.Page.ProcessRequest()), calling (MethodDesc 0x66467650 +0 System.Web.UI.Page.ProcessRequest(Boolean, Boolean))
01d3f560 6615055c (MethodDesc 0x664676f0 +0x184 System.Web.UI.Page.SetIntrinsics(System.Web.HttpContext, Boolean)), calling (MethodDesc 0x664726b0 +0 System.Web.UI.TemplateControl.HookUpAutomaticHandlers())
01d3f578 6614d72f (MethodDesc 0x66467630 +0x13 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext)), calling (MethodDesc 0x66467648 +0 System.Web.UI.Page.ProcessRequest())
01d3f580 6614d6c2 (MethodDesc 0x66467620 +0x32 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467630 +0 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext))
01d3f594 0e810206 (MethodDesc 0x22265a0 +0x1e ASP.newdefault_aspx.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467620 +0 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext))
01d3f5a0 65fe6bfb (MethodDesc 0x66470fc0 +0x167 System.Web.HttpApplication+CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()), calling 01dee5da
01d3f5d4 65fe3f51 (MethodDesc 0x6642f090 +0x41 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef)), calling 01de7d0a
01d3f610 65fe7733 (MethodDesc 0x66470cd0 +0x1b3 System.Web.HttpApplication+ApplicationStepManager.ResumeSteps(System.Exception)), calling (MethodDesc 0x6642f090 +0 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef))
01d3f64c 7939eef2 (MethodDesc 0x7925eda8 +0x26 System.Runtime.InteropServices.GCHandle.Alloc(System.Object)), calling mscorwks!InstallCustomModule+0x1e8d
01d3f664 65fccbfe (MethodDesc 0x6642ebb0 +0x8e System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext, System.AsyncCallback, System.Object))
01d3f678 65fd19c5 (MethodDesc 0x6642cde8 +0x1b5 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest)), calling 01de7cba
01d3f69c 7938111c (MethodDesc 0x79262df0 +0xc System.DateTime.get_UtcNow()), calling mscorwks!GetCLRFunction+0x109f9
01d3f6a4 01c32cbc 01c32cbc, calling 01daa248
01d3f6b4 65fd16b2 (MethodDesc 0x664619e0 +0x62 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest)), calling (MethodDesc 0x6642cde8 +0 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest))
01d3f6c0 65fcfa6d (MethodDesc 0x6642d4a0 +0xfd System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling (MethodDesc 0x664619e0 +0 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest))
01d3f6d8 65fcf9f4 (MethodDesc 0x6642d4a0 +0x84 System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling *** ERROR: Symbol file could not be found. Defaulted to export symbols for \\?\C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\webengine.dll -
webengine!GetEcb
01d3f710 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f720 01c32cbc 01c32cbc, calling 01daa248
01d3f730 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f75c 79f01621 mscorwks!GetCLRFunction+0x1e56d, calling mscorwks+0x1b86
01d3f770 79ef98cf mscorwks!GetCLRFunction+0x1681b, calling mscorwks!GetCLRFunction+0x1682f
01d3f7d0 79e74f98 mscorwks!LogHelp_NoGuiOnAssert+0x1e9c, calling mscorwks!LogHelp_NoGuiOnAssert+0x1ec1
01d3f7e8 79f0462c mscorwks!GetCLRFunction+0x21578, calling mscorwks!GetCLRFunction+0x215b0
01d3f7f8 01c32cbc 01c32cbc, calling 01daa248
01d3f844 79f044fa mscorwks!GetCLRFunction+0x21446, calling mscorwks!GetCLRFunction+0x21541
01d3f854 01c32cbc 01c32cbc, calling 01daa248
01d3f898 660167e9 (MethodDesc 0x6646f6b0 +0x5 System.Web.RequestQueue.TimerCompletionCallback(System.Object)), calling (MethodDesc 0x6646f698 +0 System.Web.RequestQueue.ScheduleMoreWorkIfNeeded())
01d3f89c 793af6c6 (MethodDesc 0x792672b0 +0x1a System.Threading._TimerCallback.TimerCallback_Context(System.Object))
01d3f8b4 793af647 (MethodDesc 0x7914fc18 +0x5b System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling (MethodDesc 0x7914e0d8 +0 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object))
01d3f8b8 793af654 (MethodDesc 0x7914fc18 +0x68 System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling mscorwks!LogHelp_TerminateOnAssert
01d3f8f8 79e74466 mscorwks!LogHelp_NoGuiOnAssert+0x136a, calling mscorwks+0x1813
01d3f8fc 79e7c709 mscorwks!LogHelp_TerminateOnAssert+0x33f1, calling mscorwks!LogHelp_NoGuiOnAssert+0x1360
01d3f964 7c829f3d ntdll!RtlFreeHeap+0x126, calling ntdll!RtlGetNtGlobalFlags+0x12
01d3f96c 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d3f9ac 6a2a9998 webengine!CSharelock::ChangeExclusiveLockToSharedLock+0x2d, calling kernel32!InterlockedCompareExchange
01d3f9b4 6a2ab03b webengine!EcbGetUnicodeServerVariables+0x3d5, calling kernel32!InterlockedIncrement
01d3f9f4 01c32cbc 01c32cbc, calling 01daa248
01d3fa28 01daa295 01daa295, calling mscorwks!GetCLRFunction+0x2119e
01d3fa50 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fa6c 01c32cbc 01c32cbc, calling 01daa248
01d3fa70 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fac8 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d3facc 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d3fad8 79f00c03 mscorwks!GetCLRFunction+0x1db4f, calling mscorwks!LogHelp_NoGuiOnAssert+0xf0
01d3fadc 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fae0 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb1c 79ef30c3 mscorwks!GetCLRFunction+0x1000f, calling mscorwks!GetCLRFunction+0x10040
01d3fb64 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb68 79f02a93 mscorwks!GetCLRFunction+0x1f9df, calling mscorwks!GetCLRFunction+0x1d8e5
01d3fb70 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fb74 79f02aa7 mscorwks!GetCLRFunction+0x1f9f3, calling mscorwks+0x1b86
01d3fb88 79f00e8d mscorwks!GetCLRFunction+0x1ddd9, calling mscorwks+0x18bb
01d3fb8c 79f00f03 mscorwks!GetCLRFunction+0x1de4f, calling mscorwks!GetCLRFunction+0x1dd84
01d3fbc0 79f02978 mscorwks!GetCLRFunction+0x1f8c4, calling mscorwks!GetCLRFunction+0x1de1a
01d3fbfc 79e73220 mscorwks!LogHelp_NoGuiOnAssert+0x124, calling (JitHelp: CORINFO_HELP_GET_THREAD)
01d3fc08 79ef2884 mscorwks!GetCLRFunction+0xf7d0, calling mscorwks!LogHelp_NoGuiOnAssert+0x118
01d3fc0c 79ef28ab mscorwks!GetCLRFunction+0xf7f7, calling mscorwks+0x17c0
01d3fc24 79e7904f mscorwks!LogHelp_NoGuiOnAssert+0x5f53, calling mscorwks+0x1b95
01d3fc38 79ef31ca mscorwks!GetCLRFunction+0x10116, calling mscorwks!LogHelp_NoGuiOnAssert+0x5f3d
01d3fc3c 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fc40 79ef31d9 mscorwks!GetCLRFunction+0x10125, calling mscorwks+0x1b86
01d3fc90 7c829fb5 ntdll!RtlGetNtGlobalFlags+0x38, calling ntdll!ExpInterlockedPopEntrySListEnd+0x11
01d3fc94 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d3fc98 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d3fca4 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d3fdb4 6a2aa748 webengine!CookieAuthConstructTicket+0x33b, calling webengine!CookieAuthConstructTicket+0x11d
01d3fdc4 6a2aa715 webengine!CookieAuthConstructTicket+0x308
01d3fddc 79f024cf mscorwks!GetCLRFunction+0x1f41b
01d3fdf4 79ef3a3f mscorwks!GetCLRFunction+0x1098b, calling mscorwks+0x17c0
01d3fe28 79f0202a mscorwks!GetCLRFunction+0x1ef76
01d3fe3c 79f021a0 mscorwks!GetCLRFunction+0x1f0ec, calling mscorwks!GetCLRFunction+0x1eef9
01d3fe94 79fc9840 mscorwks!CorExeMain+0x101f9
01d3ffa4 79fc982e mscorwks!CorExeMain+0x101e7, calling mscorwks!LogHelp_NoGuiOnAssert+0x61c0
01d3ffb8 77e64829 kernel32!GetModuleHandleA+0xdf
```
Lot of stuff there, but nothing that in my (admittedly limited) stack analyzing knowledge indicates looping. I think this next section might have some value however. This is a !dumpstackobjects I got at the same breakpoint:
```
0:000> ~16e !dumpstackobjects
OS Thread Id: 0x172c (16)
ESP/REG Object Name
01d0ee30 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef68 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef6c 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef74 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0f280 0295f810 ASI.ParadigmPlus.Question
01d0f284 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cec 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cf0 0295f674 ASI.ParadigmPlus.QuestionList
01d26cf4 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cf8 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cfc 0295f810 ASI.ParadigmPlus.Question
01d26d00 0295f810 ASI.ParadigmPlus.Question
01d26d08 0295f810 ASI.ParadigmPlus.Question
01d26d30 06c3a958 System.String SP1:SP1
01d26d40 029c232c System.String TNE:TNE
01d26d50 06c3a958 System.String SP1:SP1
01d26d54 029c232c System.String TNE:TNE
01d26d60 029c232c System.String TNE:TNE
01d26d78 06c3a958 System.String SP1:SP1
01d26d7c 06c3a958 System.String SP1:SP1
01d26d84 06c3a958 System.String SP1:SP1
01d26da4 06c357a0 System.String SB1:SB1
01d26da8 06c357a0 System.String SB1:SB1
01d26db0 06c3a958 System.String SP1:SP1
01d26db4 06ba3d08 System.String WHT:WHT
01d26db8 06b987c8 System.String WHT:WHT
01d26dbc 06b8aa10 System.String WF:WF
01d26dc0 029fab00 System.String L:L
01d26dc4 06c3a958 System.String SP1:SP1
01d26dc8 06c4a518 System.String S000:S000
01d26dd4 06c4a518 System.String S000:S000
01d26dd8 0296b404 ASI.ParadigmPlus.Question
01d26ddc 0296a00c ASI.ParadigmPlus.Question
01d26de0 02968a90 ASI.ParadigmPlus.Question
01d26de4 02966af8 ASI.ParadigmPlus.Question
01d26de8 06be6e1c ASI.ParadigmPlus.Answer
01d26dec 06c357a0 System.String SB1:SB1
01d26df0 029fab00 System.String L:L
01d26df4 0295fa54 ASI.ParadigmPlus.QuestionGroup
01d26df8 02963f80 ASI.ParadigmPlus.QuestionGroup
01d26dfc 029662fc ASI.ParadigmPlus.QuestionGroup
01d26e00 02961cb4 ASI.ParadigmPlus.QuestionGroup
01d26e0c 0295f810 ASI.ParadigmPlus.Question
01d26e10 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d270d4 06c38ddc ASI.ParadigmPlus.Answer
01d270dc 06c4bc0c ASI.ParadigmPlus.Dimension
01d270e0 06c4b99c ASI.ParadigmPlus.DimensionList
01d27104 029607f8 ASI.ParadigmPlus.Question
01d27108 0295fa80 ASI.ParadigmPlus.QuestionList
01d27118 06c38e74 System.String 5:5
01d2711c 02960564 ASI.ParadigmPlus.Question
01d27120 0295fa80 ASI.ParadigmPlus.QuestionList
01d2781c 029fac84 ASI.ParadigmPlus.Answer
01d27820 02960464 ASI.ParadigmPlus.AnswerList
01d27824 029fcbd8 ASI.ParadigmPlus.Answer
01d27828 02960464 ASI.ParadigmPlus.AnswerList
01d2782c 029fca28 ASI.ParadigmPlus.Answer
01d27830 02960464 ASI.ParadigmPlus.AnswerList
01d27844 029faa84 ASI.ParadigmPlus.Answer
01d2784c 06c38e74 System.String 5:5
01d27850 02960564 ASI.ParadigmPlus.Question
01d27854 0295fa80 ASI.ParadigmPlus.QuestionList
01d27860 06c38e74 System.String 5:5
01d27864 02960564 ASI.ParadigmPlus.Question
01d27868 0295fa80 ASI.ParadigmPlus.QuestionList
01d27870 06c38e74 System.String 5:5
01d27874 02960564 ASI.ParadigmPlus.Question
01d27878 0295fa80 ASI.ParadigmPlus.QuestionList
01d2787c 029faa84 ASI.ParadigmPlus.Answer
01d27880 02960464 ASI.ParadigmPlus.AnswerList
01d27884 029fab84 ASI.ParadigmPlus.Answer
01d27888 02960464 ASI.ParadigmPlus.AnswerList
01d27974 02960e80 ASI.ParadigmPlus.Question
01d27978 0295fa80 ASI.ParadigmPlus.QuestionList
01d27bd0 06c3a8dc ASI.ParadigmPlus.Answer
01d27c08 06c3b924 ASI.ParadigmPlus.Answer
01d27c0c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c10 06c3b860 ASI.ParadigmPlus.Answer
01d27c14 02960f44 ASI.ParadigmPlus.AnswerList
01d27c18 06c3ac90 ASI.ParadigmPlus.Answer
01d27c1c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c20 06c3abcc ASI.ParadigmPlus.Answer
01d27c24 02960f44 ASI.ParadigmPlus.AnswerList
01d27c28 06c3ab08 ASI.ParadigmPlus.Answer
01d27c2c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c30 06c3aa44 ASI.ParadigmPlus.Answer
01d27c34 02960f44 ASI.ParadigmPlus.AnswerList
01d27c38 06c3b4dc ASI.ParadigmPlus.Answer
01d27c3c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c40 06c3a990 ASI.ParadigmPlus.Answer
01d27c44 02960f44 ASI.ParadigmPlus.AnswerList
01d27c48 06c3a8dc ASI.ParadigmPlus.Answer
01d27c4c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c6c 02960e80 ASI.ParadigmPlus.Question
01d27c70 0295fa80 ASI.ParadigmPlus.QuestionList
01d27e04 029628d0 ASI.ParadigmPlus.Question
01d27e08 02961ce0 ASI.ParadigmPlus.QuestionList
01d27e28 029628d0 ASI.ParadigmPlus.Question
01d27e2c 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f14 06b89804 ASI.ParadigmPlus.Answer
01d27f18 02962994 ASI.ParadigmPlus.AnswerList
01d27f1c 029628d0 ASI.ParadigmPlus.Question
01d27f20 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f38 06c38e74 System.String 5:5
01d27f3c 02960564 ASI.ParadigmPlus.Question
01d27f40 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f4c 06c38e74 System.String 5:5
01d27f50 02960564 ASI.ParadigmPlus.Question
01d27f54 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f60 06c38e74 System.String 5:5
01d27f64 02960564 ASI.ParadigmPlus.Question
01d27f68 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f88 06b89964 ASI.ParadigmPlus.Answer
01d27f8c 029628d0 ASI.ParadigmPlus.Question
01d27f90 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fa8 06c4b34c System.String FDIA:FDIA
01d27fac 0295fd84 ASI.ParadigmPlus.Question
01d27fb0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fb4 06b896dc ASI.ParadigmPlus.Answer
01d27fb8 02962994 ASI.ParadigmPlus.AnswerList
01d27fbc 029628d0 ASI.ParadigmPlus.Question
01d27fc0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fc8 029fab00 System.String L:L
01d27fcc 029603a0 ASI.ParadigmPlus.Question
01d27fd0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fd4 06b89964 ASI.ParadigmPlus.Answer
01d27fd8 02962994 ASI.ParadigmPlus.AnswerList
01d27fdc 029628d0 ASI.ParadigmPlus.Question
01d27fe0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fe4 029628d0 ASI.ParadigmPlus.Question
01d27fe8 02961ce0 ASI.ParadigmPlus.QuestionList
01d28610 06b987c8 System.String WHT:WHT
01d28614 02961dd8 ASI.ParadigmPlus.Question
01d28618 02961ce0 ASI.ParadigmPlus.QuestionList
01d2872c 06ba3d08 System.String WHT:WHT
01d28730 029621f0 ASI.ParadigmPlus.Question
01d28734 02961ce0 ASI.ParadigmPlus.QuestionList
01d28778 029f1d94 ASI.ParadigmPlus.Answer
01d2877c 02963c14 ASI.ParadigmPlus.AnswerList
01d28780 06c37884 ASI.ParadigmPlus.Answer
01d28784 02963c14 ASI.ParadigmPlus.AnswerList
01d28788 06c379cc ASI.ParadigmPlus.Answer
01d2878c 02963c14 ASI.ParadigmPlus.AnswerList
01d28790 06c36798 ASI.ParadigmPlus.Answer
01d28794 02963c14 ASI.ParadigmPlus.AnswerList
01d28798 06c36510 ASI.ParadigmPlus.Answer
01d2879c 02963c14 ASI.ParadigmPlus.AnswerList
01d287a0 06c36648 ASI.ParadigmPlus.Answer
01d287a4 02963c14 ASI.ParadigmPlus.AnswerList
01d287ac 06c37a78 System.String Custom Paint
01d287b0 06c379cc ASI.ParadigmPlus.Answer
01d287b8 072eb468 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d287bc 02963c14 ASI.ParadigmPlus.AnswerList
01d289dc 029640b8 ASI.ParadigmPlus.Question
01d289e0 02963fac ASI.ParadigmPlus.QuestionList
01d28a38 029f13f4 System.String Venting Sidelite Locking System
01d28a3c 029f1390 ASI.ParadigmPlus.Answer
01d28a44 072f0568 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28a48 0296417c ASI.ParadigmPlus.AnswerList
01d28a60 06c356f4 ASI.ParadigmPlus.Answer
01d28a68 06c4a518 System.String S000:S000
01d28a6c 0295ffec ASI.ParadigmPlus.Question
01d28a70 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a7c 06c4a518 System.String S000:S000
01d28a80 0295ffec ASI.ParadigmPlus.Question
01d28a84 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a90 0295f768 System.String CustItemNumber
01d28a98 06c4b34c System.String FDIA:FDIA
01d28a9c 0295fd84 ASI.ParadigmPlus.Question
01d28aa0 0295fa80 ASI.ParadigmPlus.QuestionList
01d28aa4 029ecd64 ASI.ParadigmPlus.Answer
01d28aa8 0296417c ASI.ParadigmPlus.AnswerList
01d28aac 029e95ac ASI.ParadigmPlus.Answer
01d28ab0 0296417c ASI.ParadigmPlus.AnswerList
01d28ab8 029f13f4 System.String Venting Sidelite Locking System
01d28abc 029f1390 ASI.ParadigmPlus.Answer
01d28ac4 072ef574 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28ac8 0296417c ASI.ParadigmPlus.AnswerList
01d28acc 029f1230 ASI.ParadigmPlus.Answer
01d28ad0 0296417c ASI.ParadigmPlus.AnswerList
01d28f4c 02961798 ASI.ParadigmPlus.Question
01d28f50 0295fa80 ASI.ParadigmPlus.QuestionList
01d2903c 0296466c ASI.ParadigmPlus.Question
01d29040 02963fac ASI.ParadigmPlus.QuestionList
01d290cc 06c07914 System.String C:C
01d290d0 02964268 ASI.ParadigmPlus.Question
01d290d4 02963fac ASI.ParadigmPlus.QuestionList
01d29144 06c30604 ASI.ParadigmPlus.Answer
01d29148 02964730 ASI.ParadigmPlus.AnswerList
01d2914c 0296466c ASI.ParadigmPlus.Question
01d29150 02963fac ASI.ParadigmPlus.QuestionList
01d29154 06c0f9d8 ASI.ParadigmPlus.Answer
01d29158 0296450c ASI.ParadigmPlus.AnswerList
01d2915c 02964448 ASI.ParadigmPlus.Question
01d29160 02963fac ASI.ParadigmPlus.QuestionList
01d29164 02964268 ASI.ParadigmPlus.Question
01d29168 02963fac ASI.ParadigmPlus.QuestionList
01d2991c 029d6c7c System.String 021022
01d29928 029d6c7c System.String 021022
01d29934 029d6c7c System.String 021022
01d29938 029d5700 ASI.ParadigmPlus.Answer
01d2993c 0296450c ASI.ParadigmPlus.AnswerList
01d29940 029d6bdc ASI.ParadigmPlus.Answer
01d29944 0296450c ASI.ParadigmPlus.AnswerList
01d29948 02964448 ASI.ParadigmPlus.Question
01d2994c 02963fac ASI.ParadigmPlus.QuestionList
01d2f908 06c4b34c System.String FDIA:FDIA
01d2f90c 0295fd84 ASI.ParadigmPlus.Question
01d2f910 0295fa80 ASI.ParadigmPlus.QuestionList
01d2ffd0 02964c28 ASI.ParadigmPlus.Question
01d2ffd4 02963fac ASI.ParadigmPlus.QuestionList
01d2ffe4 06c32030 System.String SB:SB
01d2ffe8 02964a54 ASI.ParadigmPlus.Question
01d2ffec 02963fac ASI.ParadigmPlus.QuestionList
01d2fffc 06c3368c ASI.ParadigmPlus.Answer
01d30000 02964b18 ASI.ParadigmPlus.AnswerList
01d30004 02964a54 ASI.ParadigmPlus.Question
01d30008 02963fac ASI.ParadigmPlus.QuestionList
01d3000c 02964a54 ASI.ParadigmPlus.Question
01d30010 02963fac ASI.ParadigmPlus.QuestionList
01d30144 06c32030 System.String SB:SB
01d30148 02964a54 ASI.ParadigmPlus.Question
01d3014c 02963fac ASI.ParadigmPlus.QuestionList
01d30154 06c31f90 ASI.ParadigmPlus.Answer
01d3015c 06c344d8 System.String (COM) Lifetime Brass
01d30160 06c34418 ASI.ParadigmPlus.Answer
01d30168 072f16a0 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d3016c 02964b18 ASI.ParadigmPlus.AnswerList
01d30174 06c31f90 ASI.ParadigmPlus.Answer
01d30178 06c34294 ASI.ParadigmPlus.Answer
01d3017c 02964b18 ASI.ParadigmPlus.AnswerList
01d30180 06c33e48 ASI.ParadigmPlus.Answer
01d30184 02964b18 ASI.ParadigmPlus.AnswerList
01d30188 06c32e6c ASI.ParadigmPlus.Answer
01d3018c 02964b18 ASI.ParadigmPlus.AnswerList
01d30190 06c32b78 ASI.ParadigmPlus.Answer
01d30194 02964b18 ASI.ParadigmPlus.AnswerList
```
^^ I had to cut off some of the above to make this post fit, but imagine it keeps going like that ^^
Please ignore the details of our custom code. All this seems excessive to me, but I am no expert at the stack. Most of those stack objects listed above (there are 1500+) are not function paramteters, so I would think they do not belong there. Here is an example of the kind of code that is generating all those items on the stack (tons of code like this is run):
```
gUnitType.Questions("French Door Style").CommonLogicValue = CommonLogicValues.AlwaysDisplay
gUnitType.Questions("French Door Style").ShowAllAnswers()
If Me.NumberOfUnits > 1 Then
Me.Dimensions("Call Size Height").Answers("6-8 Handicap sill").Visible = False
Me.Dimensions("Call Size Height").Answers("6-10 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("7-0 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("8-0 Handicap Sill").Visible = False
End If
```
I am also no expert on VB (this code is from a different part of our application I do not normally work with), but is it normal for code like this to be filling up the stack with stuff? If anyone has any insight, or could even just point me in the direction of some resources with info about this kind of stuff, it would be greatly appreciated. Thanks for looking! | I thought I'd post back here with the resolution to this in case someone else runs into it. The replies above were all helpful, and pointed out why i might be overflowing the stack -- but the thing that I still couldn't come to grips with was why the exact same code ran fine in our winforms app.
What I eventually discovered was that at some point microsoft changed the stack size of IIS threads from 1MB (like in the general .NET context) to 256k. This explained everything, including the especially frustrating fact that even the ASPX version ran fine under the visual studio dev server. I resolved the problem by working with this particular customer to drastically cut the ammount of code in the QuestionChangeLogic function mentioned above (when I looked up the source, the function had > 15,000 lines!).
Thanks for the help guys. |
93,335 | <p>Does anyone know of a good tool to generate the WSDL for a service contract written in C# (i.e. set of methods that are tagged as "[OperationContract]" using WCF)? All the tools I've found work the other way around: create code stubs from a WSDL. I don't want to have to hand-jam a WSDL file. I've found tools for php and J2EE, but not C#. Thanks!</p>
| [
{
"answer_id": 93368,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa702581.aspx\" rel=\"nofollow noreferrer\">svcutil</a> or just host it quickly and hit the MEX point :)</p>\n"
},
{
"answer_id": 97199,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Easiest thing to do is host the service with a base address setup, and then just hit it from a browser with \"?wsdl\" appended to the end. </p>\n\n<p>Here's an example of a service configuration with a base address specified. Note this goes in the <code><configuration><services></code> element in your config:</p>\n\n<pre><code> <service name=\"MyServiceName\" behaviorConfiguration=\"MyServiceBehavior\">\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:9000/MyService\"/>\n </baseAddresses>\n </host>\n <endpoint address=\"net.tcp://localhost:9001/MyService\"\n binding=\"netTcpBinding\"\n contract=\"IMyService\"\n bindingConfiguration=\"MyServiceBinding\"/>\n </service>\n</code></pre>\n\n<p>Once you get it hosted, just go to <code>http://localhost:9000/MyService?wsdl</code> to see the WSDL definition.</p>\n"
},
{
"answer_id": 44128038,
"author": "Gul Ershad",
"author_id": 3540865,
"author_profile": "https://Stackoverflow.com/users/3540865",
"pm_score": 0,
"selected": false,
"text": "<p>Two ways:</p>\n\n<p>a) <strong>Download wsdl file and do below steps</strong>:</p>\n\n<p>i) Open visual studio command prompt as an administrator.</p>\n\n<p>ii) Type below command:</p>\n\n<p>wsdl.exe [path To Your WSDL File]</p>\n\n<p>b) <strong>With endpoint</strong>:</p>\n\n<p>i) Open Visual studio command prompt as an administrator.</p>\n\n<p>ii) type below command:\n wsdl.exe <a href=\"http://localhost:9000/MyService\" rel=\"nofollow noreferrer\">http://localhost:9000/MyService</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59910/"
]
| Does anyone know of a good tool to generate the WSDL for a service contract written in C# (i.e. set of methods that are tagged as "[OperationContract]" using WCF)? All the tools I've found work the other way around: create code stubs from a WSDL. I don't want to have to hand-jam a WSDL file. I've found tools for php and J2EE, but not C#. Thanks! | Easiest thing to do is host the service with a base address setup, and then just hit it from a browser with "?wsdl" appended to the end.
Here's an example of a service configuration with a base address specified. Note this goes in the `<configuration><services>` element in your config:
```
<service name="MyServiceName" behaviorConfiguration="MyServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9000/MyService"/>
</baseAddresses>
</host>
<endpoint address="net.tcp://localhost:9001/MyService"
binding="netTcpBinding"
contract="IMyService"
bindingConfiguration="MyServiceBinding"/>
</service>
```
Once you get it hosted, just go to `http://localhost:9000/MyService?wsdl` to see the WSDL definition. |
93,353 | <p>I need to make a random list of permutations. The elements can be anything but assume that they are the integers 0 through x-1. I want to make y lists, each containing z elements. The rules are that no list may contain the same element twice and that over all the lists, the number of times each elements is used is the same (or as close as possible). For instance, if my elements are 0,1,2,3, y is 6, and z is 2, then one possible solution is:</p>
<pre>
0,3
1,2
3,0
2,1
0,1
2,3
</pre>
<p>Each row has only unique elements and no element has been used more than 3 times. If y were 7, then 2 elements would be used 4 times, the rest 3.</p>
| [
{
"answer_id": 93465,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, one way to approximate that:</p>\n\n<p>1 - shuffle your list</p>\n\n<p>2 - take the y first elements to form the next row</p>\n\n<p>4 - repeat (2) as long as you have numbers in the list</p>\n\n<p>5 - if you don't have enough numbers to finish the list, reshuffle the original list and take the missing elements, making sure you don't retake numbers.</p>\n\n<p>6 - Start over at step (2) as long as you need rows</p>\n\n<p>I think this should be as random as you can make it and will for sure follow your criteria. Plus, you have very little tests for duplicate elements.</p>\n"
},
{
"answer_id": 93515,
"author": "devinmoore",
"author_id": 15950,
"author_profile": "https://Stackoverflow.com/users/15950",
"pm_score": 0,
"selected": false,
"text": "<p>First, you can always randomly sort the list in the end, so let's not worry about making \"random permutations\" (hard); and just worry about 1) making permutations (easy) and 2) randomizing them (easy).</p>\n\n<p>If you want \"truly\" random groups, you have to accept that randomization by nature doesn't really allow for the constraint of \"even distribution\" of results -- you may get that or you may get a run of similar-looking ones. If you really want even distribution, first make the sets evenly distributed, and then randomize them as a group.</p>\n\n<p>Do you have to use each element in the set x evenly? It's not clear from the rules that I couldn't just make the following interpretation: </p>\n\n<p>Note the following: \"over all the lists, the number of times each elements is used is the same (or as close as possible)\"</p>\n\n<p>Based on this criteria, and the rule that z < x*, I postulate that you can simply enumerate all the items over all the lists. So you automatically make y list of the items enumerated to position z. Your example doesn't fulfill the rule above as closely as my version will. Using your example of x={0,1,2,3} y=6 and z=2, I get:\n0,1 0,1 0,1 0,1 0,1 0,1 </p>\n\n<p>Now I didn't use 2 or 3, but you didn't say I had to use them all. If I had to use them all and I don't care to be able to prove that I am \"as close as possible\" to even usage, I would just enumerate across all the items through the lists, like this:\n0,1 2,3 0,1 2,3 0,1 2,3</p>\n\n<p>Finally, suppose I really do have to use all the elements. To calculate how many times each element can repeat, I just take (y*z)/(count of x). That way, I don't have to sit and worry about how to divide up the items in the list. If there is a remainder, or the result is less than 1, then I know that I will not get an exact number of repeats, so in those cases, it doesn't much matter to try to waste computational energy to make it perfect. I contend that the fastest result is still to just enumerate as above, and use the calculation here to show why either a perfect result was or wasn't achieved. A fancy algorithm to extract from this calculation how many positions will be duplicates could be achieved, but \"it's too long to fit here in the margin\".</p>\n\n<p>*Each list has the same z number of elements, so it will be impossible to make lists where z is greater than x and still fulfill the rule that no list may contain the same element twice. Therefore, this rule demands that z cannot be greater than x.</p>\n"
},
{
"answer_id": 94111,
"author": "devinmoore",
"author_id": 15950,
"author_profile": "https://Stackoverflow.com/users/15950",
"pm_score": 0,
"selected": false,
"text": "<p>Based on new details in the comments, the solution may simply be an implementation of a standard random permutation generation algorithm. There is a lengthy discussion of random permutation generation algorithms here:</p>\n\n<p><a href=\"http://www.techuser.net/randpermgen.html\" rel=\"nofollow noreferrer\">http://www.techuser.net/randpermgen.html</a></p>\n\n<p>(From Google search: random permutation generation)</p>\n"
},
{
"answer_id": 95138,
"author": "Terhorst",
"author_id": 8062,
"author_profile": "https://Stackoverflow.com/users/8062",
"pm_score": 3,
"selected": true,
"text": "<p>This could be improved, but it seems to do the job (Python):</p>\n\n<pre><code>import math, random\n\n\ndef get_pool(items, y, z):\n slots = y*z\n\n use_each_times = slots/len(items)\n exceptions = slots - use_each_times*len(items)\n\n\n if (use_each_times > y or\n exceptions > 0 and use_each_times+1 > y):\n raise Exception(\"Impossible.\")\n\n\n pool = {}\n for n in items:\n pool[n] = use_each_times\n\n for n in random.sample(items, exceptions):\n pool[n] += 1\n\n return pool\n\ndef rebalance(ret, pool, z):\n max_item = None\n max_times = None\n\n for item, times in pool.items():\n if times > max_times:\n max_item = item\n max_times = times\n\n\n next, times = max_item, max_times\n\n candidates = []\n for i in range(len(ret)):\n item = ret[i]\n\n if next not in item:\n candidates.append( (item, i) )\n\n\n swap, swap_index = random.choice(candidates)\n\n swapi = []\n for i in range(len(swap)):\n if swap[i] not in pool:\n swapi.append( (swap[i], i) )\n\n\n which, i = random.choice(swapi)\n\n pool[next] -= 1\n pool[swap[i]] = 1\n swap[i] = next\n\n ret[swap_index] = swap\n\ndef plist(items, y, z):\n pool = get_pool(items, y, z)\n\n ret = []\n while len(pool.keys()) > 0:\n while len(pool.keys()) < z:\n rebalance(ret, pool, z)\n\n selections = random.sample(pool.keys(), z)\n\n for i in selections:\n pool[i] -= 1\n if pool[i] == 0:\n del pool[i]\n\n ret.append( selections )\n\n return ret\n\n\nprint plist([0,1,2,3], 6, 2)\n</code></pre>\n"
},
{
"answer_id": 1923768,
"author": "Trevoke",
"author_id": 234025,
"author_profile": "https://Stackoverflow.com/users/234025",
"pm_score": 0,
"selected": false,
"text": "<p>This works in Ruby:</p>\n\n<pre><code># list is the elements to be permuted\n# y is the number of results desired\n# z is the number of elements per result\n# equalizer keeps track of who got used how many times\ndef constrained_permutations list, y, z\n list.uniq! # Never trust the user. We want no repetitions.\n equalizer = {}\n list.each { |element| equalizer[element] = 0 }\n\n results = []\n # Do this until we get as many results as desired\n while results.size < y\n pool = []\n puts pool\n least_used = equalizer.each_value.min\n # Find how used the least used element was\n while pool.size < z\n # Do this until we have enough elements in this resultset\n element = nil\n while element.nil?\n # If we run out of \"least used elements\", then we need to increment\n # our definition of \"least used\" by 1 and keep going.\n element = list.shuffle.find do |x|\n !pool.include?(x) && equalizer[x] == least_used\n end\n least_used += 1 if element.nil?\n end\n equalizer[element] += 1\n # This element has now been used one more time.\n pool << element\n end\n results << pool\n end\n return results\nend\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>constrained_permutations [0,1,2,3,4,5,6], 6, 2\n=> [[4, 0], [1, 3], [2, 5], [6, 0], [2, 5], [3, 6]]\nconstrained_permutations [0,1,2,3,4,5,6], 6, 2\n=> [[4, 5], [6, 3], [0, 2], [1, 6], [5, 4], [3, 0]]\nenter code here\n</code></pre>\n"
},
{
"answer_id": 2752071,
"author": "abalter",
"author_id": 188963,
"author_profile": "https://Stackoverflow.com/users/188963",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Fisher-Yates_shuffle</a></p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454/"
]
| I need to make a random list of permutations. The elements can be anything but assume that they are the integers 0 through x-1. I want to make y lists, each containing z elements. The rules are that no list may contain the same element twice and that over all the lists, the number of times each elements is used is the same (or as close as possible). For instance, if my elements are 0,1,2,3, y is 6, and z is 2, then one possible solution is:
```
0,3
1,2
3,0
2,1
0,1
2,3
```
Each row has only unique elements and no element has been used more than 3 times. If y were 7, then 2 elements would be used 4 times, the rest 3. | This could be improved, but it seems to do the job (Python):
```
import math, random
def get_pool(items, y, z):
slots = y*z
use_each_times = slots/len(items)
exceptions = slots - use_each_times*len(items)
if (use_each_times > y or
exceptions > 0 and use_each_times+1 > y):
raise Exception("Impossible.")
pool = {}
for n in items:
pool[n] = use_each_times
for n in random.sample(items, exceptions):
pool[n] += 1
return pool
def rebalance(ret, pool, z):
max_item = None
max_times = None
for item, times in pool.items():
if times > max_times:
max_item = item
max_times = times
next, times = max_item, max_times
candidates = []
for i in range(len(ret)):
item = ret[i]
if next not in item:
candidates.append( (item, i) )
swap, swap_index = random.choice(candidates)
swapi = []
for i in range(len(swap)):
if swap[i] not in pool:
swapi.append( (swap[i], i) )
which, i = random.choice(swapi)
pool[next] -= 1
pool[swap[i]] = 1
swap[i] = next
ret[swap_index] = swap
def plist(items, y, z):
pool = get_pool(items, y, z)
ret = []
while len(pool.keys()) > 0:
while len(pool.keys()) < z:
rebalance(ret, pool, z)
selections = random.sample(pool.keys(), z)
for i in selections:
pool[i] -= 1
if pool[i] == 0:
del pool[i]
ret.append( selections )
return ret
print plist([0,1,2,3], 6, 2)
``` |
93,357 | <p><strong>I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...</strong></p>
<pre><code>URL theURL = new URL(url);
URLConnection urlConn = theURL.openConnection();
urlConn.setDoOutput(true);
BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
</code></pre>
<p><strong>...and then begun the loop to read the contents...</strong></p>
<pre><code>do
{
buf = urlReader.readLine();
if (buf != null)
{
resultBuffer.append(buf);
resultBuffer.append("\n");
}
}
while (buf != null);
</code></pre>
<p><strong>...but if the read hangs then the application hangs.</strong></p>
<p><strong>Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?</strong></p>
| [
{
"answer_id": 93418,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 5,
"selected": true,
"text": "<p>I think URLConnection.setReadTimeout is what you are looking for.</p>\n"
},
{
"answer_id": 93452,
"author": "Peter",
"author_id": 17123,
"author_profile": "https://Stackoverflow.com/users/17123",
"pm_score": 2,
"selected": false,
"text": "<p>Since Java 1.5, it is possible to set the read timeout in milliseconds on the underlying socket via the 'setReadTimeout(int timeout)' method on the URLConnection class. </p>\n\n<p>Note that there is also the 'setConnectTimeout(int timeout)' which will do the same thing for the initial connection to the remote server, so it is important to set that as well.</p>\n"
},
{
"answer_id": 93589,
"author": "Javaxpert",
"author_id": 15241,
"author_profile": "https://Stackoverflow.com/users/15241",
"pm_score": 2,
"selected": false,
"text": "<p>If you have java 1.4:</p>\n\n<p>I assume the connection timeout (<code>URLConnection.setConnectTimeout(int timeout)</code> ) is of no use because you are doing some kind of streaming.</p>\n\n<p>---<strong>Do not kill the thread</strong>--- It may cause unknown problems, open descriptors, etc.</p>\n\n<p>Spawn a java.util.TimerTask where you will check if you have finished the process, otherwise, close the BufferedReader and the OutputStream of the URLConnection</p>\n\n<p>Insert a boolean flag <code>isFinished</code> and set it to true at the end of your loop and to false before the loop</p>\n\n<pre><code>TimerTask ft = new TimerTask(){\n public void run(){\n if (!isFinished){\n urlConn.getInputStream().close();\n urlConn.getOutputStream().close();\n }\n }\n};\n\n(new Timer()).schedule(ft, timeout);\n</code></pre>\n\n<p>This will probably cause an ioexception, so you have to catch it. The exception is not a bad thing in itself.\nI'm omitting some declarations (i.e. finals) so the anonymous class can access your variables. If not, then create a POJO that maintains a reference and pass that to the timertask</p>\n"
},
{
"answer_id": 155352,
"author": "Chris Markle",
"author_id": 1505846,
"author_profile": "https://Stackoverflow.com/users/1505846",
"pm_score": 1,
"selected": false,
"text": "<p>I have been working on this issue in a JVM 1.4 environment just recently. The stock answer is to use the system properties sun.net.client.defaultReadTimeout (read timeout) and/or sun.net.client.defaultConnectTimeout. These are documented at <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html\" rel=\"nofollow noreferrer\">Networking Properties</a> and can be set via the -D argument on the Java command line or via a System.setProperty method call.</p>\n\n<p>Supposedly these are cached by the implementation so you can't change them from one thing to another so one they are used once, the values are retained.</p>\n\n<p>Also they don't really work for SSL connections ala HttpsURLConnection. There are other ways to deal with that using a custom SSLSocketFactory.</p>\n\n<p>Again, all this applies to JVM 1.4.x. At 1.5 and above you have more methods available to you in the API (as noted by the other responders above).</p>\n"
},
{
"answer_id": 13559981,
"author": "phychem",
"author_id": 697027,
"author_profile": "https://Stackoverflow.com/users/697027",
"pm_score": 1,
"selected": false,
"text": "<p>For Java 1.4, you may use SimpleHttpConnectionManager.getConnectionWithTimeout(hostConf,CONNECTION_TIMEOUT) from Apache</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
]
| **I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...**
```
URL theURL = new URL(url);
URLConnection urlConn = theURL.openConnection();
urlConn.setDoOutput(true);
BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
```
**...and then begun the loop to read the contents...**
```
do
{
buf = urlReader.readLine();
if (buf != null)
{
resultBuffer.append(buf);
resultBuffer.append("\n");
}
}
while (buf != null);
```
**...but if the read hangs then the application hangs.**
**Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?** | I think URLConnection.setReadTimeout is what you are looking for. |
93,408 | <p>I saw some code like the following in a JSP</p>
<pre><code><c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>">
<li>user</li>
</c:if>
</code></pre>
<p>My confusion is over the "=" that appears in the value of the <code>test</code> attribute. My understanding was that anything included within <code><%= %></code> is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work?</p>
<p>For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead.</p>
<p>Cheers,
Don</p>
| [
{
"answer_id": 93469,
"author": "Sindri Traustason",
"author_id": 1113,
"author_profile": "https://Stackoverflow.com/users/1113",
"pm_score": 2,
"selected": false,
"text": "<p>Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.</p>\n\n<p>If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. <a href=\"http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html\" rel=\"nofollow noreferrer\">http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html</a></p>\n"
},
{
"answer_id": 93659,
"author": "Javaxpert",
"author_id": 15241,
"author_profile": "https://Stackoverflow.com/users/15241",
"pm_score": 0,
"selected": false,
"text": "<p><%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string</p>\n"
},
{
"answer_id": 93669,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 2,
"selected": false,
"text": "<p>The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:</p>\n\n<pre><code><c:if test=\"true\">\n <li>user</li>\n</c:if>\n</code></pre>\n\n<p>and then the c:if tag would be executed.</p>\n"
},
{
"answer_id": 93717,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 5,
"selected": true,
"text": "<p>All that the <code>test</code> attribute looks for to determine if something is true is the string \"true\" (case in-sensitive). For example, the following code will print \"Hello world!\"</p>\n\n<pre><code><c:if test=\"true\">Hello world!</c:if>\n</code></pre>\n\n<p>The code within the <code><%= %></code> returns a boolean, so it will either print the string \"true\" or \"false\", which is exactly what the <code><c:if></code> tag looks for.</p>\n"
},
{
"answer_id": 342552,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use something like </p>\n\n<pre><code><c:if test=\"${ testObject.testPropert == \"testValue\" }\">...</c:if>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| I saw some code like the following in a JSP
```
<c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>">
<li>user</li>
</c:if>
```
My confusion is over the "=" that appears in the value of the `test` attribute. My understanding was that anything included within `<%= %>` is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work?
For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead.
Cheers,
Don | All that the `test` attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
```
<c:if test="true">Hello world!</c:if>
```
The code within the `<%= %>` returns a boolean, so it will either print the string "true" or "false", which is exactly what the `<c:if>` tag looks for. |
93,415 | <p>I use <a href="http://files.emacsblog.org/ryan/elisp/maxframe.el" rel="noreferrer">maxframe.el</a> to maximize my Emacs frames.</p>
<p>It works great on all three major platforms, except on my dual-head Mac setup (Macbook Pro 15-inch laptop with 23-inch monitor). </p>
<p>When maximizing an Emacs frame, the frame expands to fill the width of <em>both</em> monitors and the height of the larger monitor. </p>
<p>Obviously, I would like the frame to maximize to fill only the monitor it's on. How can I detect the resolutions of the two individual monitors using elisp? </p>
<p>Thanks,
Jacob</p>
<p>EDIT: As Denis points out, setting mf-max-width is a reasonable workaround. But (as I should have mentioned) I was hoping for a solution that works on both monitors and with any resolution. Maybe something OSX-specific in the style of the Windows-specific w32-send-sys-command. </p>
| [
{
"answer_id": 93428,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 2,
"selected": false,
"text": "<p>Does customising `mf-max-width' work? Its documentation:</p>\n\n<pre><code>\"*The maximum display width to support. This helps better support the true\nnature of display-pixel-width. Since multiple monitors will result in a\nvery large display pixel width, this value is used to set the stop point for\nmaximizing the frame. This could also be used to set a fixed frame size\nwithout going over the display dimensions.\"\n</code></pre>\n"
},
{
"answer_id": 102256,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 4,
"selected": true,
"text": "<p>I quickly scanned the reference that you provided to <code>maxframe.el</code> and <em>I don't think</em> that you're using the same technique that I use. Does the following code snippet help you?</p>\n\n<pre><code>\n(defun toggle-fullscreen ()\n \"toggles whether the currently selected frame consumes the entire display or is decorated with a window border\"\n (interactive)\n (let ((f (selected-frame)))\n (modify-frame-parameters f `((fullscreen . ,(if (eq nil (frame-parameter f 'fullscreen)) 'fullboth nil))))))\n</code></pre>\n"
},
{
"answer_id": 1068334,
"author": "jrockway",
"author_id": 8457,
"author_profile": "https://Stackoverflow.com/users/8457",
"pm_score": -1,
"selected": false,
"text": "<p>This sort of thing is the job of your window manager, not the job of emacs. (For example, Xmonad handles full-screen emacs just fine.)</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13747/"
]
| I use [maxframe.el](http://files.emacsblog.org/ryan/elisp/maxframe.el) to maximize my Emacs frames.
It works great on all three major platforms, except on my dual-head Mac setup (Macbook Pro 15-inch laptop with 23-inch monitor).
When maximizing an Emacs frame, the frame expands to fill the width of *both* monitors and the height of the larger monitor.
Obviously, I would like the frame to maximize to fill only the monitor it's on. How can I detect the resolutions of the two individual monitors using elisp?
Thanks,
Jacob
EDIT: As Denis points out, setting mf-max-width is a reasonable workaround. But (as I should have mentioned) I was hoping for a solution that works on both monitors and with any resolution. Maybe something OSX-specific in the style of the Windows-specific w32-send-sys-command. | I quickly scanned the reference that you provided to `maxframe.el` and *I don't think* that you're using the same technique that I use. Does the following code snippet help you?
```
(defun toggle-fullscreen ()
"toggles whether the currently selected frame consumes the entire display or is decorated with a window border"
(interactive)
(let ((f (selected-frame)))
(modify-frame-parameters f `((fullscreen . ,(if (eq nil (frame-parameter f 'fullscreen)) 'fullboth nil))))))
``` |
93,423 | <p>I have the following code:</p>
<pre><code> String inputFile = "somefile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
for ( int i = 0; i < rd/2; i++ ) {
/* print each character */
System.out.print(buf.getChar());
}
buf.clear();
}
</code></pre>
<p>But the characters get displayed at ?'s. Does this have something to do with Java using Unicode characters? How do I correct this?</p>
| [
{
"answer_id": 93521,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it is Unicode.</p>\n\n<p>If you have 14 Chars in your File, you only get 7 '?'.</p>\n\n<p>Solution pending. Still thinking.</p>\n"
},
{
"answer_id": 93528,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a particular reason why you are reading the file in the way that you do?</p>\n\n<p>If you're reading in an ASCII file you should really be using a Reader.</p>\n\n<p>I would do it something like:</p>\n\n<pre><code>File inputFile = new File(\"somefile.txt\");\nBufferedReader reader = new BufferedReader(new FileReader(inputFile));\n</code></pre>\n\n<p>And then use either <code>readLine</code> or similar to actually read in the data!</p>\n"
},
{
"answer_id": 93574,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 2,
"selected": false,
"text": "<p>Changing your print statement to:</p>\n\n<pre><code>System.out.print((char)buf.get());\n</code></pre>\n\n<p>Seems to help.</p>\n"
},
{
"answer_id": 93575,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 2,
"selected": false,
"text": "<p>buf.getChar() is expecting 2 bytes per character but you are only storing 1. Use:</p>\n\n<pre><code> System.out.print((char) buf.get());\n</code></pre>\n"
},
{
"answer_id": 93628,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the encoding of somefile.txt, a character may not actually be composed of two bytes. <a href=\"http://java.sun.com/docs/books/tutorial/i18n/text/stream.html\" rel=\"nofollow noreferrer\">This page</a> gives more information about how to read streams with the proper encoding.</p>\n\n<p>The bummer is, the file system doesn't tell you the encoding of the file, because it doesn't know. As far as it's concerned, it's just a bunch of bytes. You must either find some way to communicate the encoding to the program, detect it somehow, or (if possible) always ensure that the encoding is the same (such as UTF-8).</p>\n"
},
{
"answer_id": 93685,
"author": "jliszka",
"author_id": 9767,
"author_profile": "https://Stackoverflow.com/users/9767",
"pm_score": 4,
"selected": true,
"text": "<p>You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII:</p>\n\n<pre><code>import java.util.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.nio.channels.*;\nimport java.nio.charset.*;\n\npublic class Buffer\n{\n public static void main(String args[]) throws Exception\n {\n String inputFile = \"somefile\";\n FileInputStream in = new FileInputStream(inputFile);\n FileChannel ch = in.getChannel();\n ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256\n\n Charset cs = Charset.forName(\"ASCII\"); // Or whatever encoding you want\n\n /* read the file into a buffer, 256 bytes at a time */\n int rd;\n while ( (rd = ch.read( buf )) != -1 ) {\n buf.rewind();\n CharBuffer chbuf = cs.decode(buf);\n for ( int i = 0; i < chbuf.length(); i++ ) {\n /* print each character */\n System.out.print(chbuf.get());\n }\n buf.clear();\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
]
| I have the following code:
```
String inputFile = "somefile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
for ( int i = 0; i < rd/2; i++ ) {
/* print each character */
System.out.print(buf.getChar());
}
buf.clear();
}
```
But the characters get displayed at ?'s. Does this have something to do with Java using Unicode characters? How do I correct this? | You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII:
```
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Buffer
{
public static void main(String args[]) throws Exception
{
String inputFile = "somefile";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
Charset cs = Charset.forName("ASCII"); // Or whatever encoding you want
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for ( int i = 0; i < chbuf.length(); i++ ) {
/* print each character */
System.out.print(chbuf.get());
}
buf.clear();
}
}
}
``` |
93,439 | <p>Is there any website/service which will enable me to add RSS subscription to any website?</p>
<p>This is for my company I work. We have a website which displays company related news. These news are supplied by an external agency and they gets updated to our database automatically. Our website picks up random/new news and displays them. We are looking at adding a "Subscribe via RSS" button to our website.</p>
| [
{
"answer_id": 93459,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": false,
"text": "<p>Your question is a little difficult to understand. Are you trying to generate the RSS for others to consume, or are you trying to consume someone else's RSS?</p>\n\n<p>If you are trying to generate your RSS feed for others to consume you will need to read the spec:</p>\n\n<p><a href=\"http://cyber.law.harvard.edu/rss/rss.html\" rel=\"nofollow noreferrer\">http://cyber.law.harvard.edu/rss/rss.html</a></p>\n\n<p>If you are trying to consume it, that link will also help. Then you'll need to look into an XML / RSS parser.</p>\n\n<p>If you can provide more details I can update my answer.</p>\n"
},
{
"answer_id": 93464,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 0,
"selected": false,
"text": "<p>Write a webhandler that exposes the content of the database as an RSS feed.</p>\n"
},
{
"answer_id": 93477,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "<p>If you have the data in your database, creating one yourself is fairly straight forward - there's a simple tutorial <a href=\"http://www.downes.ca/cgi-bin/page.cgi?post=56\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Once you've set up a feed, in the <head> of your page, you put text like:</p>\n\n<pre><code><link rel=\"alternate\" title=\"RSS Feed\" \n href=\"http://www.example.com/rss-feed/latest/\" type=\"application/rss+xml\" />\n</code></pre>\n\n<p>This allows the feed to be \"auto-discovered\" by your user's browser (e.g. the RSS icon appears in the address bar in FF).</p>\n"
},
{
"answer_id": 93487,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 1,
"selected": false,
"text": "<p>If you are not in a position to add an RSS feed to the existing site, see <a href=\"http://page2rss.com/\" rel=\"nofollow noreferrer\">Page2Rss</a> as an intermediate solution.</p>\n"
},
{
"answer_id": 93492,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 1,
"selected": false,
"text": "<p>Might <a href=\"http://www.dapper.net/\" rel=\"nofollow noreferrer\">Dapper</a> be of some use? You just need to set up which bits of your news feed to scour and voila, instant rss without having to touch any code...</p>\n"
},
{
"answer_id": 93494,
"author": "Scott Gowell",
"author_id": 6943,
"author_profile": "https://Stackoverflow.com/users/6943",
"pm_score": 0,
"selected": false,
"text": "<p>You either need to roll your own, or get a service that is a screen scraper.</p>\n\n<p>After you have created your feed, you can use something like <a href=\"http://www.feedburner.com/fb/a/home\" rel=\"nofollow noreferrer\">Feedburner</a> to disseminate it.</p>\n"
},
{
"answer_id": 93510,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an article that discusses various webscrapers that will generate feeds: <a href=\"http://www.masternewmedia.org/news/2006/03/09/how_to_create_a_rss.htm\" rel=\"nofollow noreferrer\">http://www.masternewmedia.org/news/2006/03/09/how_to_create_a_rss.htm</a></p>\n\n<p>If you don't care to click through, here are the services the author discusses:</p>\n\n<ul>\n<li><a href=\"http://www.feedyes.com/\" rel=\"nofollow noreferrer\">http://www.feedyes.com/</a></li>\n<li><a href=\"http://www.feed43.com/\" rel=\"nofollow noreferrer\">http://www.feed43.com/</a></li>\n<li><a href=\"http://www.feedfire.com/site/index.html\" rel=\"nofollow noreferrer\">http://www.feedfire.com/site/index.html</a></li>\n</ul>\n\n<p>Other webscrapers suggested in the other answers:</p>\n\n<ul>\n<li><a href=\"http://page2rss.com/\" rel=\"nofollow noreferrer\">http://page2rss.com/</a></li>\n<li><a href=\"http://www.dapper.net/\" rel=\"nofollow noreferrer\">http://www.dapper.net/</a></li>\n</ul>\n\n<p>However, you're probably better off generating the feeds yourself from the info in the DB.</p>\n"
},
{
"answer_id": 93691,
"author": "LockeCJ",
"author_id": 13583,
"author_profile": "https://Stackoverflow.com/users/13583",
"pm_score": 0,
"selected": false,
"text": "<p>If you happen to be using ASP.NET, you might want to check out the <a href=\"http://www.codeplex.com/ASPNETRSSToolkit\" rel=\"nofollow noreferrer\">ASP.NET RSS Toolkit</a>. It's useful for both generating and consuming feeds.</p>\n"
},
{
"answer_id": 160899,
"author": "Kent Brewster",
"author_id": 1151280,
"author_profile": "https://Stackoverflow.com/users/1151280",
"pm_score": 1,
"selected": false,
"text": "<p>Actually this is very doable with Yahoo! Pipes. Assuming that 1) your page is under 200k, 2) your robots.txt file does not disallow Pipes, and 3) your news feed has a unique ID, like so: </p>\n\n<pre><code><ul id=\"newsfeed\">\n</code></pre>\n\n<p>... you could use the Fetch Page module, trim it to just the items inside the news feed, loop though each list item, and use an Item Builder module to mangle the relevant bits as a proper RSS feed. Then, in the head of your document, you'd put in an RSS link, like so:</p>\n\n<pre><code><link rel=\"alternate\" type=\"application/atom+xml\" title=\"News Feed\" href=\"http://pipes.yahoo.com/your_pipe_id\" />\n</code></pre>\n\n<p>This is of course completely ass-backwards, but would work for a quick fix, or in situations where you had no control over the body of the page.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
]
| Is there any website/service which will enable me to add RSS subscription to any website?
This is for my company I work. We have a website which displays company related news. These news are supplied by an external agency and they gets updated to our database automatically. Our website picks up random/new news and displays them. We are looking at adding a "Subscribe via RSS" button to our website. | If you have the data in your database, creating one yourself is fairly straight forward - there's a simple tutorial [here](http://www.downes.ca/cgi-bin/page.cgi?post=56).
Once you've set up a feed, in the <head> of your page, you put text like:
```
<link rel="alternate" title="RSS Feed"
href="http://www.example.com/rss-feed/latest/" type="application/rss+xml" />
```
This allows the feed to be "auto-discovered" by your user's browser (e.g. the RSS icon appears in the address bar in FF). |
93,462 | <p>when an SQL Server Express DB is 'in recovery', you are unable to connect using SQL Authentication. </p>
<p>Is there a simple way of determining the stat of the DB prior to connecting to it?
(Using .Net)</p>
| [
{
"answer_id": 93594,
"author": "Andy Irving",
"author_id": 8553,
"author_profile": "https://Stackoverflow.com/users/8553",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT DATABASEPROPERTYEX ('master', 'STATUS') AS 'Status';\n</code></pre>\n\n<p>Replace 'master' with your database name</p>\n"
},
{
"answer_id": 989728,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 1,
"selected": false,
"text": "<p>That's kind of a trick question. Instead of connecting to that particular database, you still need to connect to the server itself, but specify a different database. When connecting, your default database might be the one that's in recovery. In that case, you'll need to specify a different database upon connecting, and THEN issue a query to check the database's extended properties.</p>\n\n<p>Unfortunately, this means your SQL login will need permissions to that other database you'll be connecting to, AND it'll need permissions to query the database's extended properties.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| when an SQL Server Express DB is 'in recovery', you are unable to connect using SQL Authentication.
Is there a simple way of determining the stat of the DB prior to connecting to it?
(Using .Net) | ```
SELECT DATABASEPROPERTYEX ('master', 'STATUS') AS 'Status';
```
Replace 'master' with your database name |
93,472 | <p>Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually?</p>
| [
{
"answer_id": 93606,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 6,
"selected": false,
"text": "<p>Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP. <br></p>\n\n<p>To use the DateTimePicker for times, set the Format property to either Time\nor Custom (Use Custom if you want to control the format of the time using\nthe CustomFormat property). Then set the ShowUpDown property to true.</p>\n\n<p>Although a user may set the date and time together manually, they cannot use the GUI to set both.</p>\n"
},
{
"answer_id": 93614,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 9,
"selected": true,
"text": "<p>Set the Format to Custom and then specify the format:</p>\n\n<pre><code>dateTimePicker1.Format = DateTimePickerFormat.Custom;\ndateTimePicker1.CustomFormat = \"MM/dd/yyyy hh:mm:ss\"; \n</code></pre>\n\n<p>or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)</p>\n\n<p>Don't know about the picker for date and time together. Sounds like a custom control to me.</p>\n"
},
{
"answer_id": 93635,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>You can get it to display <a href=\"http://msdn.microsoft.com/en-us/library/ms229631.aspx\" rel=\"nofollow noreferrer\">time</a>. From that you will probably have to have two controls (one date, one time) the accomplish what you want.</p>\n"
},
{
"answer_id": 93641,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.</p>\n\n<p>For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.</p>\n"
},
{
"answer_id": 1305145,
"author": "Danish",
"author_id": 159910,
"author_profile": "https://Stackoverflow.com/users/159910",
"pm_score": 5,
"selected": false,
"text": "<p>DateTime Picker can be used to pick both date and time that is why it is called 'Date and Time Picker'. You can set the \"<strong>Format</strong>\" property to \"<strong>Custom</strong>\" and set combination of different format specifiers to represent/pick date/time in different formats in the \"<strong>Custom Format</strong>\" property. However if you want to change Date, then the pop-up calendar can be used whereas in case of Time selection (in the same control you are bound to use up/down keys to change values. </p>\n\n<p>For example a custom format \" <strong>ddddd, MMMM dd, yyyy hh:mm:ss tt</strong> \" will give you a result like this : \"<strong>Thursday, August 20, 2009 02:55:23 PM</strong>\". </p>\n\n<p>You can play around with different combinations for format specifiers to suit your need e.g <strong>MMMM</strong> will give \"<strong>August</strong>\" whereas <strong>MM</strong> will give \"<strong>Aug</strong>\"</p>\n"
},
{
"answer_id": 30259683,
"author": "Vectoria",
"author_id": 3793099,
"author_profile": "https://Stackoverflow.com/users/3793099",
"pm_score": 6,
"selected": false,
"text": "<p>It is best to use two DateTimePickers for the Job\nOne will be the default for the date section and the second DateTimePicker is for the time portion. Format the second DateTimePicker as follows.</p>\n\n<pre><code> timePortionDateTimePicker.Format = DateTimePickerFormat.Time;\n timePortionDateTimePicker.ShowUpDown = true;\n</code></pre>\n\n<p>The Two should look like this after you capture them</p>\n\n<p><img src=\"https://i.stack.imgur.com/x94Oa.jpg\" alt=\"Two Date Time Pickers\"></p>\n\n<p>To get the DateTime from both these controls use the following code </p>\n\n<pre><code>DateTime myDate = datePortionDateTimePicker.Value.Date + \n timePortionDateTimePicker.Value.TimeOfDay; \n</code></pre>\n\n<p>To assign the DateTime to both these controls use the following code </p>\n\n<pre><code>datePortionDateTimePicker.Value = myDate.Date; \ntimePortionDateTimePicker.Value = myDate.TimeOfDay; \n</code></pre>\n"
},
{
"answer_id": 41579613,
"author": "Serge Voloshenko",
"author_id": 5771669,
"author_profile": "https://Stackoverflow.com/users/5771669",
"pm_score": 4,
"selected": false,
"text": "<p>Go to the <code>Properties</code> of your <code>dateTimePicker</code>in Visual Studio and set <code>Format</code> to <code>Custom</code>. Under <code>CustomFormat</code> enter your format. In my case I used <code>MMMMdd, yyyy | hh:mm</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/hRxNy.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hRxNy.jpg\" alt=\"enter image description here\"></a><br>\n<a href=\"https://i.stack.imgur.com/3ATE4.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3ATE4.jpg\" alt=\"dateTimePickerProperties\"></a></p>\n"
},
{
"answer_id": 71828637,
"author": "ahmetsarikaya",
"author_id": 18330549,
"author_profile": "https://Stackoverflow.com/users/18330549",
"pm_score": 0,
"selected": false,
"text": "<p>If you need (24 hours) military time. You should use "HH" instead of "hh".</p>\n<p>"MM/dd/yyyy HH:mm"</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
]
| Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually? | Set the Format to Custom and then specify the format:
```
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";
```
or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)
Don't know about the picker for date and time together. Sounds like a custom control to me. |
93,511 | <p>How to get a counter inside xsl:for-each loop that would reflect the number of current element processed.<br>
For example my source XML is</p>
<pre><code><books>
<book>
<title>The Unbearable Lightness of Being </title>
</book>
<book>
<title>Narcissus and Goldmund</title>
</book>
<book>
<title>Choke</title>
</book>
</books>
</code></pre>
<p>What I want to get is:</p>
<pre><code><newBooks>
<newBook>
<countNo>1</countNo>
<title>The Unbearable Lightness of Being </title>
</newBook>
<newBook>
<countNo>2</countNo>
<title>Narcissus and Goldmund</title>
</newBook>
<newBook>
<countNo>3</countNo>
<title>Choke</title>
</newBook>
</newBooks>
</code></pre>
<p>The XSLT to modify:</p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo>???</countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>So the question is what to put in place of ???. Is there any standard keyword or do I simply must declare a variable and increment it inside the loop?</p>
<p>As the question is pretty long I should probably expect one line or one word answer :)</p>
| [
{
"answer_id": 93553,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 8,
"selected": true,
"text": "<p><code>position()</code>. E.G.:</p>\n\n<pre><code><countNo><xsl:value-of select=\"position()\" /></countNo>\n</code></pre>\n"
},
{
"answer_id": 93562,
"author": "Santiago Cepas",
"author_id": 6547,
"author_profile": "https://Stackoverflow.com/users/6547",
"pm_score": 3,
"selected": false,
"text": "<pre><code> <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/>\n <xsl:template match=\"/\">\n <newBooks>\n <xsl:for-each select=\"books/book\">\n <newBook>\n <countNo><xsl:value-of select=\"position()\"/></countNo>\n <title>\n <xsl:value-of select=\"title\"/>\n </title>\n </newBook>\n </xsl:for-each>\n </newBooks>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
},
{
"answer_id": 93563,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 4,
"selected": false,
"text": "<p>Try inserting <code><xsl:number format=\"1. \"/><xsl:value-of select=\".\"/><xsl:text></code> in the place of ???.</p>\n\n<p>Note the \"1. \" - this is the number format. More info: <a href=\"http://www.xml.com/pub/a/2002/11/06/tr.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 93580,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code><xsl:value-of select=\"count(preceding-sibling::*) + 1\" />\n</code></pre>\n\n<p><strong>Edit</strong> - had a brain freeze there, position() is more straightforward!</p>\n"
},
{
"answer_id": 4230670,
"author": "Arun Arangil",
"author_id": 514152,
"author_profile": "https://Stackoverflow.com/users/514152",
"pm_score": 3,
"selected": false,
"text": "<p>You can also run conditional statements on the Postion() which can be really helpful in many scenarios.</p>\n\n<p>for eg.</p>\n\n<pre><code> <xsl:if test=\"(position( )) = 1\">\n //Show header only once\n </xsl:if>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241/"
]
| How to get a counter inside xsl:for-each loop that would reflect the number of current element processed.
For example my source XML is
```
<books>
<book>
<title>The Unbearable Lightness of Being </title>
</book>
<book>
<title>Narcissus and Goldmund</title>
</book>
<book>
<title>Choke</title>
</book>
</books>
```
What I want to get is:
```
<newBooks>
<newBook>
<countNo>1</countNo>
<title>The Unbearable Lightness of Being </title>
</newBook>
<newBook>
<countNo>2</countNo>
<title>Narcissus and Goldmund</title>
</newBook>
<newBook>
<countNo>3</countNo>
<title>Choke</title>
</newBook>
</newBooks>
```
The XSLT to modify:
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo>???</countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
```
So the question is what to put in place of ???. Is there any standard keyword or do I simply must declare a variable and increment it inside the loop?
As the question is pretty long I should probably expect one line or one word answer :) | `position()`. E.G.:
```
<countNo><xsl:value-of select="position()" /></countNo>
``` |
93,541 | <p>I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.</p>
| [
{
"answer_id": 95013,
"author": "BenR",
"author_id": 18039,
"author_profile": "https://Stackoverflow.com/users/18039",
"pm_score": 2,
"selected": false,
"text": "<p>You're on the right track. You will need to override the SnapLines property in your designr and do something like this:</p>\n\n<pre><code>Public Overrides ReadOnly Property SnapLines() As System.Collections.IList\n Get\n Dim snapLinesList As ArrayList = TryCast(MyBase.SnapLines, ArrayList)\n\n Dim offset As Integer\n Dim ctrl As MyControl = TryCast(Me.Control, MyControl)\n If ctrl IsNot Nothing AndAlso ctrl.TextBox1 IsNot Nothing Then\n offset = ctrl.TextBox1.Bottom - 5\n End If\n\n snapLinesList.Add(New SnapLine(SnapLineType.Baseline, offset, SnapLinePriority.Medium))\n\n Return snapLinesList\n\n End Get\nEnd Property\n</code></pre>\n\n<p>In this example the usercontrol contains a textbox. The code adds a new snapline that represents the baseline for the textbox. The important thing is to calculate the offset correctly.</p>\n"
},
{
"answer_id": 402419,
"author": "Miral",
"author_id": 43534,
"author_profile": "https://Stackoverflow.com/users/43534",
"pm_score": 6,
"selected": true,
"text": "<p>I just had a similar need, and I solved it like this:</p>\n\n<pre><code> public override IList SnapLines\n{\n get\n {\n IList snapLines = base.SnapLines;\n\n MyControl control = Control as MyControl;\n if (control == null) { return snapLines; }\n\n IDesigner designer = TypeDescriptor.CreateDesigner(\n control.textBoxValue, typeof(IDesigner));\n if (designer == null) { return snapLines; }\n designer.Initialize(control.textBoxValue);\n\n using (designer)\n {\n ControlDesigner boxDesigner = designer as ControlDesigner;\n if (boxDesigner == null) { return snapLines; }\n\n foreach (SnapLine line in boxDesigner.SnapLines)\n {\n if (line.SnapLineType == SnapLineType.Baseline)\n {\n snapLines.Add(new SnapLine(SnapLineType.Baseline,\n line.Offset + control.textBoxValue.Top,\n line.Filter, line.Priority));\n break;\n }\n }\n }\n\n return snapLines;\n }\n}\n</code></pre>\n\n<p>This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the \"real\" baseline snapline is.</p>\n\n<p>This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.</p>\n\n<p>This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.</p>\n"
},
{
"answer_id": 945486,
"author": "Matthew M.",
"author_id": 27472,
"author_profile": "https://Stackoverflow.com/users/27472",
"pm_score": 5,
"selected": false,
"text": "<p>As an update to the Miral's answer.. here are a few of the \"missing steps\", for someone new that's looking how to do this. :) The C# code above is almost 'drop-in' ready, with the exception of changing a few of the values to reference the UserControl that will be modified.</p>\n\n<p>Possible References Needed:<br/>\n System.Design (@robyaw)</p>\n\n<p>Usings needed:</p>\n\n<pre><code>using System.Windows.Forms.Design;\nusing System.Windows.Forms.Design.Behavior;\nusing System.ComponentModel;\nusing System.ComponentModel.Design;\nusing System.Collections;\n</code></pre>\n\n<p>On your UserControl you need the following Attribute:</p>\n\n<pre><code>[Designer(typeof(MyCustomDesigner))]\n</code></pre>\n\n<p>Then you need a \"designer\" class that will have the SnapLines override:</p>\n\n<pre><code>private class MyCustomerDesigner : ControlDesigner {\n public override IList SnapLines {\n get {\n /* Code from above */\n IList snapLines = base.SnapLines;\n\n // *** This will need to be modified to match your user control\n MyControl control = Control as MyControl;\n if (control == null) { return snapLines; }\n\n // *** This will need to be modified to match the item in your user control\n // This is the control in your UC that you want SnapLines for the entire UC\n IDesigner designer = TypeDescriptor.CreateDesigner(\n control.textBoxValue, typeof(IDesigner));\n if (designer == null) { return snapLines; }\n\n // *** This will need to be modified to match the item in your user control\n designer.Initialize(control.textBoxValue);\n\n using (designer)\n {\n ControlDesigner boxDesigner = designer as ControlDesigner;\n if (boxDesigner == null) { return snapLines; }\n\n foreach (SnapLine line in boxDesigner.SnapLines)\n {\n if (line.SnapLineType == SnapLineType.Baseline)\n {\n // *** This will need to be modified to match the item in your user control\n snapLines.Add(new SnapLine(SnapLineType.Baseline,\n line.Offset + control.textBoxValue.Top,\n line.Filter, line.Priority));\n break;\n }\n }\n }\n\n return snapLines;\n}\n\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1744204,
"author": "Jonh Clark",
"author_id": 212320,
"author_profile": "https://Stackoverflow.com/users/212320",
"pm_score": 3,
"selected": false,
"text": "<p>VB.Net Version:<br>\nNote: you have to change the <code>txtDescription</code> to the Textbox or another internal control name that you use. and <code>ctlUserControl</code> to your <code>usercontrol</code> name</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code><Designer(GetType(ctlUserControl.MyCustomDesigner))> _\nPartial Public Class ctlUserControl\n '... \n 'Your Usercontrol class specific code\n '... \n Class MyCustomDesigner\n Inherits ControlDesigner\n Public Overloads Overrides ReadOnly Property SnapLines() As IList\n Get\n ' Code from above \n\n Dim lines As IList = MyBase.SnapLines\n\n ' *** This will need to be modified to match your user control\n Dim control__1 As ctlUserControl = TryCast(Me.Control, ctlUserControl)\n If control__1 Is Nothing Then Return lines\n\n ' *** This will need to be modified to match the item in your user control\n ' This is the control in your UC that you want SnapLines for the entire UC\n Dim designer As IDesigner = TypeDescriptor.CreateDesigner(control__1.txtDescription, GetType(IDesigner))\n If designer Is Nothing Then\n Return lines\n End If\n\n ' *** This will need to be modified to match the item in your user control\n designer.Initialize(control__1.txtDescription)\n\n Using designer\n Dim boxDesigner As ControlDesigner = TryCast(designer, ControlDesigner)\n If boxDesigner Is Nothing Then\n Return lines\n End If\n\n For Each line As SnapLine In boxDesigner.SnapLines\n If line.SnapLineType = SnapLineType.Baseline Then\n ' *** This will need to be modified to match the item in your user control\n lines.Add(New SnapLine(SnapLineType.Baseline, line.Offset + control__1.txtDescription.Top, line.Filter, line.Priority))\n Exit For\n End If\n Next\n End Using\n\n Return lines\n End Get\n End Property\n End Class\n\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 3451311,
"author": "Robert H.",
"author_id": 108958,
"author_profile": "https://Stackoverflow.com/users/108958",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to all those for the help. This was a tough one to swallow. The thought having a private sub-class in every UserControl wasn't very palatable.</p>\n\n<p>I came up with this base class to help out..</p>\n\n<pre><code>[Designer(typeof(UserControlSnapLineDesigner))]\npublic class UserControlBase : UserControl\n{\n protected virtual Control SnapLineControl { get { return null; } }\n\n private class UserControlSnapLineDesigner : ControlDesigner\n {\n public override IList SnapLines\n {\n get\n {\n IList snapLines = base.SnapLines;\n\n Control targetControl = (this.Control as UserControlBase).SnapLineControl;\n\n if (targetControl == null)\n return snapLines;\n\n using (ControlDesigner controlDesigner = TypeDescriptor.CreateDesigner(targetControl,\n typeof(IDesigner)) as ControlDesigner)\n {\n if (controlDesigner == null)\n return snapLines;\n\n controlDesigner.Initialize(targetControl);\n\n foreach (SnapLine line in controlDesigner.SnapLines)\n {\n if (line.SnapLineType == SnapLineType.Baseline)\n {\n snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset + targetControl.Top,\n line.Filter, line.Priority));\n break;\n }\n }\n }\n return snapLines;\n }\n }\n }\n}\n</code></pre>\n\n<p>Next, derive your UserControl from this base:</p>\n\n<pre><code>public partial class MyControl : UserControlBase\n{\n protected override Control SnapLineControl\n {\n get\n {\n return txtTextBox;\n }\n }\n\n ...\n\n}\n</code></pre>\n\n<p>Thanks again for posting this.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848/"
]
| I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control. | I just had a similar need, and I solved it like this:
```
public override IList SnapLines
{
get
{
IList snapLines = base.SnapLines;
MyControl control = Control as MyControl;
if (control == null) { return snapLines; }
IDesigner designer = TypeDescriptor.CreateDesigner(
control.textBoxValue, typeof(IDesigner));
if (designer == null) { return snapLines; }
designer.Initialize(control.textBoxValue);
using (designer)
{
ControlDesigner boxDesigner = designer as ControlDesigner;
if (boxDesigner == null) { return snapLines; }
foreach (SnapLine line in boxDesigner.SnapLines)
{
if (line.SnapLineType == SnapLineType.Baseline)
{
snapLines.Add(new SnapLine(SnapLineType.Baseline,
line.Offset + control.textBoxValue.Top,
line.Filter, line.Priority));
break;
}
}
}
return snapLines;
}
}
```
This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is.
This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.
This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated. |
93,569 | <p>For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior?</p>
<p>some more info:</p>
<p>a. It is possible to explicitely create a misaligned integer (*bar):</p>
<blockquote>
<p>char foo[5]</p>
<p>int * bar = (int *)(&foo[1]);</p>
</blockquote>
<p>b. Apparently, #pragma pack() only affects structures, classes, and unions.</p>
<p>c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know)</p>
| [
{
"answer_id": 93585,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, all types are always aligned to at least their alignment requirements.</p>\n\n<p>How could it be otherwise?</p>\n\n<p>But note that the sizeof() a type is not the same as it's alignment.</p>\n\n<p>You can use the following macro to determine the alignment requirements of a type:</p>\n\n<pre><code>#define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test )\n</code></pre>\n"
},
{
"answer_id": 93600,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>By default, yes. However, it can be changed via the pack() #pragma.</p>\n\n<p>I don't believe the C++ Standard make any requirement in this regard, and leaves it up to the implementation.</p>\n"
},
{
"answer_id": 93627,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 0,
"selected": false,
"text": "<p>Depends on the compiler, the pragmas and the optimisation level. With modern compilers you can also choose time or space optimisation, which could change the alignment of types as well.</p>\n"
},
{
"answer_id": 93666,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "<p>Generally it will be because reading/writing to it is faster that way. But almost every compiler has a switch to turn this off. In gcc its -malign-???. With aggregates they are generally aligned and sized based on the alignment requirements of each element within.</p>\n"
},
{
"answer_id": 93797,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 4,
"selected": true,
"text": "<p>As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors.</p>\n\n<p>Microsoft VC implements what is basically called natural alignment up to the size specified by the #pragma pack directive or the /Zp command line option. This means that, for example, any POD type with a size smaller or equal to 8 bytes will be aligned based on its size. Anything larger will be aligned on an 8 byte boundary.</p>\n\n<p>If it is important that you control alignment for different processors and different compilers, then you can use a packing size of 1 and pad your structures.</p>\n\n<pre><code>#pragma pack(push)\n#pragma pack(1) \nstruct Example\n{\n short data1; // offset 0\n short padding1; // offset 2\n long data2; // offset 4\n};\n#pragma pack(pop)\n</code></pre>\n\n<p>In this code, the <code>padding1</code> variable exists only to make sure that data2 is naturally aligned.</p>\n\n<p>Answer to a:</p>\n\n<p>Yes, that can easily cause misaligned data. On an x86 processor, this doesn't really hurt much at all. On other processors, this can result in a crash or a very slow execution. For example, the Alpha processor would throw a processor exception which would be caught by the OS. The OS would then inspect the instruction and then do the work needed to handle the misaligned data. Then execution continues. The <code>__unaligned</code> keyword can be used in VC to mark unaligned access for non-x86 programs (i.e. for CE).</p>\n"
},
{
"answer_id": 94146,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>C and C++ don't mandate any kind of alignment. But natural alignment is strongly preferred by x86 and is <em>required</em> by most other CPU architectures, and compilers generally do their utmost to keep CPUs happy. So in practice you won't see a compiler generate misaligned data unless you really twist it's arm.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
]
| For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior?
some more info:
a. It is possible to explicitely create a misaligned integer (\*bar):
>
> char foo[5]
>
>
> int \* bar = (int \*)(&foo[1]);
>
>
>
b. Apparently, #pragma pack() only affects structures, classes, and unions.
c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know) | As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors.
Microsoft VC implements what is basically called natural alignment up to the size specified by the #pragma pack directive or the /Zp command line option. This means that, for example, any POD type with a size smaller or equal to 8 bytes will be aligned based on its size. Anything larger will be aligned on an 8 byte boundary.
If it is important that you control alignment for different processors and different compilers, then you can use a packing size of 1 and pad your structures.
```
#pragma pack(push)
#pragma pack(1)
struct Example
{
short data1; // offset 0
short padding1; // offset 2
long data2; // offset 4
};
#pragma pack(pop)
```
In this code, the `padding1` variable exists only to make sure that data2 is naturally aligned.
Answer to a:
Yes, that can easily cause misaligned data. On an x86 processor, this doesn't really hurt much at all. On other processors, this can result in a crash or a very slow execution. For example, the Alpha processor would throw a processor exception which would be caught by the OS. The OS would then inspect the instruction and then do the work needed to handle the misaligned data. Then execution continues. The `__unaligned` keyword can be used in VC to mark unaligned access for non-x86 programs (i.e. for CE). |
93,578 | <p>I cannot use the Resource File API from within a file system plugin due to a PlatSec issue:</p>
<pre><code>*PlatSec* ERROR - Capability check failed - Can't load filesystemplugin.PXT because it links to bafl.dll which has the following capabilities missing: TCB
</code></pre>
<p>My understanding of the issue is that:</p>
<p>File system plugins are dlls which are executed within the context of the file system process. Therefore all file system plugins must have the <code>TCB</code> PlatSec privilege which in turn means they cannot link against a dll that is not in the <code>TCB</code>.</p>
<p>Is there a way around this (without resorting to a text file or an intermediate server)? I suspect not - but it would be good to get a definitive answer.</p>
| [
{
"answer_id": 94169,
"author": "MathewI",
"author_id": 17938,
"author_profile": "https://Stackoverflow.com/users/17938",
"pm_score": 3,
"selected": true,
"text": "<p>The Symbian file server has the following capabilities:</p>\n\n<pre><code>TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD\n</code></pre>\n\n<p>So any DLL being loaded into the file server process must have at least these capabilities. There is no way around this, short of writing a new proxy process as you allude to.</p>\n\n<p>However, there is a more fundamental reason why you shouldn't be using <code>bafl.dll</code> from within a fileserver plugin: this DLL provides utility functions which interface to the file servers client API. Attempting to use it from within the filer server will not work; at best, it will lead to the file server deadlocking as it attempts to connect to itself.</p>\n\n<p>I'd suggest rethinking that you're trying to do, and investigating an internal file-server API to achieve it instead.</p>\n"
},
{
"answer_id": 94219,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 1,
"selected": false,
"text": "<p>Using RFs/RFile/RDir APIs from within a file server plugin is not safe and can potentially lead to deadlock if you're not very careful.</p>\n\n<p>Symbian 9.5 will introduce new APIs (RFilePlugin, RFsPlugin and RDirPlugin) which should be used instead.</p>\n"
},
{
"answer_id": 94525,
"author": "michael aubert",
"author_id": 17867,
"author_profile": "https://Stackoverflow.com/users/17867",
"pm_score": -1,
"selected": false,
"text": "<p>Tell us what kind of data you are storing in the resource file.</p>\n\n<p>Things that usually go into resource files have no place in a file server plugin, even that means hardcoding a few values.</p>\n\n<p>Technically, you can send data to a file server plugin using RFile.Write() but that's not a great solution (intercept RFile.Open(\"invalid file name that only your plugin understands\") in the plugin).\nEDIT: Someone indicated that using an invalid file name will not let you send data to the plugin. hey, I didn't like that solution either. for the sake of completness, I should clarify. make up a filename that looks OK enough to go through to your plugin. like using a drive letter that doesn't have a real drive attached to it (but will still be considered correct by filename-parsing code).</p>\n\n<p>Writing code to parse the resource file binary in the plugin, while theoratically possible, isn't a great solution either.</p>\n"
},
{
"answer_id": 100630,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 0,
"selected": false,
"text": "<p>Theres a proper mechanism for communicating with plugins, RPlugin.</p>\n\n<p>Do not use RFile. I'm not even sure that it would work as the path is checked in Initialise of RFile functions which is called before the plugin stack.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8565/"
]
| I cannot use the Resource File API from within a file system plugin due to a PlatSec issue:
```
*PlatSec* ERROR - Capability check failed - Can't load filesystemplugin.PXT because it links to bafl.dll which has the following capabilities missing: TCB
```
My understanding of the issue is that:
File system plugins are dlls which are executed within the context of the file system process. Therefore all file system plugins must have the `TCB` PlatSec privilege which in turn means they cannot link against a dll that is not in the `TCB`.
Is there a way around this (without resorting to a text file or an intermediate server)? I suspect not - but it would be good to get a definitive answer. | The Symbian file server has the following capabilities:
```
TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD
```
So any DLL being loaded into the file server process must have at least these capabilities. There is no way around this, short of writing a new proxy process as you allude to.
However, there is a more fundamental reason why you shouldn't be using `bafl.dll` from within a fileserver plugin: this DLL provides utility functions which interface to the file servers client API. Attempting to use it from within the filer server will not work; at best, it will lead to the file server deadlocking as it attempts to connect to itself.
I'd suggest rethinking that you're trying to do, and investigating an internal file-server API to achieve it instead. |
93,583 | <p>In a asp.net web application, I want to write to a file. This function will first get data from the database, and then write out the flat file.</p>
<p>What can I do to make sure only 1 write occurs, and once the write occurrs, the other threads that maybe want to write to the file don't since the write took place.</p>
<p>I want to have this write done ONLY if it hasn't been done in say 15 minutes.</p>
<p>I know there is a lock keyword, so should I wrap everything in a lock, then check if it has been updated in 15 minutes or more, or visa versa?</p>
<p><b>Update</b></p>
<p>Workflow:</p>
<p>Since this is a web application, the multiple instances will be people viewing a particular web page. I could use the build in cache system, but if asp.net recycles it will be expensive to rebuild the cache so I just want to write it out to a flat file. My other option would be just to create a windows service, but that is more work to manage that I want.</p>
| [
{
"answer_id": 93597,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>Synchronize your writing code to lock on a shared object so that only one thread gets inside the block. Others wait till the current one exits.</p>\n\n<pre><code>lock(this)\n{\n // perform the write.\n}\n</code></pre>\n\n<p>Update: I assumed that you have a shared object. If these are different processes on the same machine, you'd need something like a Named Mutex. <a href=\"http://msdn.microsoft.com/en-us/library/aa332344(VS.71).aspx\" rel=\"nofollow noreferrer\">Looky here for an example</a> </p>\n"
},
{
"answer_id": 93636,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 1,
"selected": false,
"text": "<p>is it not better to lock an object variable rather than the whole instance?</p>\n"
},
{
"answer_id": 93639,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not convinced that .NET's locking is applicable to different processes. Moreover, lock(this) will only exclude other threads that are running the method on the same instance of \"this\" - so other threads even in the same process could run at once on different instances.</p>\n\n<p>Assuming all your processes are running on the same machine, file locking should do it though.</p>\n\n<p>If you're on different machines, your mileage may vary- win32 claims to have file locking which works over a network, but historically applications which rely on it (Think MSAccess) have problems with file corruption anyway.</p>\n"
},
{
"answer_id": 93674,
"author": "Oliver Mellet",
"author_id": 12001,
"author_profile": "https://Stackoverflow.com/users/12001",
"pm_score": 0,
"selected": false,
"text": "<pre><code> // try enter will return false if another thread owns the lock\n if (Monitor.TryEnter(lockObj))\n {\n try\n {\n // check last write time here, return if too soon; otherwise, write\n }\n finally\n {\n Monitor.Exit(lockobj);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 93883,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": 1,
"selected": false,
"text": "<p>File I/O operations that write to the file will automatically lock the file. Check if the file is locked (by trying the write) and if it is do not write. Before doing any writes, check the timestamp on the file and see if its more than 15 minutes.</p>\n\n<p>afaik you can not write to a file without it being locked by Windows/whatever.</p>\n\n<p>Now all that's left for you is to look up how to do the above using msdn (sorry, I can't be bothered to look it all up and I don't remember the C# classes very well). :)</p>\n"
},
{
"answer_id": 170571,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Use file-system locks</strong></p>\n\n<p>Like others suggested, .NET locks will be of limited use in this situation.\nHere is the code:</p>\n\n<pre><code>FileInfo fi = new FileInfo(path);\nif (fi.Exists\n && (DateTime.UtcNow - fi.LastWriteTimeUtc < TimeSpan.FromMinutes(15)) {\n // file is fresh\n return;\n}\n\nFileStream fs;\ntry {\n fs = new FileStream(\n path, FileMode.Create, FileAccess.Write, FileShare.Read);\n} catch (IOException) {\n // file is locked\n return;\n}\n\nusing (fs) {\n // write to file\n}\n</code></pre>\n\n<p>This will work across threads <em>and</em> processes.</p>\n"
},
{
"answer_id": 5431120,
"author": "A-Dubb",
"author_id": 389103,
"author_profile": "https://Stackoverflow.com/users/389103",
"pm_score": 0,
"selected": false,
"text": "<p>You guys should consider a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx\" rel=\"nofollow\">Mutex</a>. It can synchronize between multiple threads and processes.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
| In a asp.net web application, I want to write to a file. This function will first get data from the database, and then write out the flat file.
What can I do to make sure only 1 write occurs, and once the write occurrs, the other threads that maybe want to write to the file don't since the write took place.
I want to have this write done ONLY if it hasn't been done in say 15 minutes.
I know there is a lock keyword, so should I wrap everything in a lock, then check if it has been updated in 15 minutes or more, or visa versa?
**Update**
Workflow:
Since this is a web application, the multiple instances will be people viewing a particular web page. I could use the build in cache system, but if asp.net recycles it will be expensive to rebuild the cache so I just want to write it out to a flat file. My other option would be just to create a windows service, but that is more work to manage that I want. | Synchronize your writing code to lock on a shared object so that only one thread gets inside the block. Others wait till the current one exits.
```
lock(this)
{
// perform the write.
}
```
Update: I assumed that you have a shared object. If these are different processes on the same machine, you'd need something like a Named Mutex. [Looky here for an example](http://msdn.microsoft.com/en-us/library/aa332344(VS.71).aspx) |
93,590 | <p>I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is.</p>
<pre><code>Dim provider1 As New MD5CryptoServiceProvider
Dim stream1 As FileStream
stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
provider1.ComputeHash(stream1)
</code></pre>
<p>Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it?</p>
<p>I see significant performance problems on my web host when using the <code>ComputeHash</code> method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access.</p>
| [
{
"answer_id": 93644,
"author": "MichaelT",
"author_id": 288629,
"author_profile": "https://Stackoverflow.com/users/288629",
"pm_score": 0,
"selected": false,
"text": "<p>Yes content of the file will be read then you run ComputeHash method and not when you just open a FileStream.</p>\n\n<p>The best way to test where the performance problem is , it is to read data from file to memory stream hash it and measure performance of each of this steps. You can use System.Diagnostics.Stopwatch class for this. </p>\n"
},
{
"answer_id": 93661,
"author": "Dario Solera",
"author_id": 16026,
"author_profile": "https://Stackoverflow.com/users/16026",
"pm_score": 0,
"selected": false,
"text": "<p>Bytes from disk should be read when the caller requests them by invoking Read or similar methods. At any rate, both the hard disk and the operating system perform some read-ahead to improve sequential read operations, but this is surely hard to predict.</p>\n\n<p>You could also try to play with the buffer size parameter that some constructor overloads provide for FileStream.</p>\n"
},
{
"answer_id": 93694,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 3,
"selected": true,
"text": "<p>FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM). </p>\n\n<p>The performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself.</p>\n\n<p>But one of the first things you might try is:</p>\n\n<pre><code>provider1.ComputeHash(stream1.ToArray());\n</code></pre>\n\n<p>This should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3059/"
]
| I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is.
```
Dim provider1 As New MD5CryptoServiceProvider
Dim stream1 As FileStream
stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
provider1.ComputeHash(stream1)
```
Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it?
I see significant performance problems on my web host when using the `ComputeHash` method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access. | FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM).
The performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself.
But one of the first things you might try is:
```
provider1.ComputeHash(stream1.ToArray());
```
This should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call. |
93,625 | <p>I have a list with two <code><div></code>s in every <code><li></code> and I want to float them one next to the other and I want the <code><li></code> to take the whole availabe space. How do I do it?</p>
<pre><code><html>
<head>
<title></title>
<style type="text/css">
body {
}
ul {
}
li {
}
.a {
}
.b {
}
</style>
</head>
<body>
<ul>
<li>
<div class="a">
content
</div>
<div class="b">
content
</div>
</li>
</ul>
</body>
</html>
</code></pre>
| [
{
"answer_id": 93646,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": -1,
"selected": false,
"text": "<pre><code>li{width:100%;}\n.a{}\n.b{float: left;}\n</code></pre>\n\n<p>That should do as required from my knowledge of CSS</p>\n"
},
{
"answer_id": 93647,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 0,
"selected": false,
"text": "<p>Without checking to make sure, this should work</p>\n\n<pre><code>\nLI { width: 100%; }\n.a { float: left; }\n.b { float: right; }\n</code></pre>\n"
},
{
"answer_id": 93649,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": true,
"text": "<pre class=\"lang-css prettyprint-override\"><code> *{ margin: 0; padding: 0;}\n li{ width: 100%: display: block; } \n li:after{ clear: both; } \n div.a{ width: 49%; float: left; }\n div.b{ width: 49%; float: left; } \n</code></pre>\n\n<p>Should do the trick. </p>\n"
},
{
"answer_id": 93671,
"author": "AdamB",
"author_id": 2176,
"author_profile": "https://Stackoverflow.com/users/2176",
"pm_score": 2,
"selected": false,
"text": "<p>For the divs, you just need to float left and the li, you want to do a clear. So:</p>\n\n<pre><code>li\n{\n clear: left;\n}\n.a\n{\n float: left;\n}\n.b\n{\n float: left;\n}\n</code></pre>\n"
},
{
"answer_id": 93681,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-css prettyprint-override\"><code>li { width: 100%;}\n.a { float: left;}\n.b { float: left;}\n</code></pre>\n"
},
{
"answer_id": 94052,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I assume by take the whole space you mean a width of 100%. I would also assume that you do not want styling applied to the list, which is why I have removed it in this example. This is also hack-free. You need not clear anything, so long as your list item has a width and the overflow: hidden property/value pair.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>ul,\nli {\n width: 100%;\n list-style-type: none;\n margin: 0;\n padding: 0;\n}\nli {\n overflow: hidden;\n}\nli div.a,\nli div.b {\n float: left;\n}\n</code></pre>\n"
},
{
"answer_id": 14507673,
"author": "Labanino",
"author_id": 1839767,
"author_profile": "https://Stackoverflow.com/users/1839767",
"pm_score": 1,
"selected": false,
"text": "<p>I see this is an old post but if someone runs into the same issue think about this: </p>\n\n<pre><code><div>A block-level section in a document</div>\n<span>An inline section in a document</span>\n</code></pre>\n\n<p>You can use <strong>span</strong> instead of <strong>div</strong></p>\n\n<p>To get a <strong>div</strong> besides the other or horizontally you have to apply brute force with .<strong>css</strong> but if you use <strong>span</strong> it will naturally. Copy and paste the following code in a <strong>html</strong> and see what I'm talking about:</p>\n\n<pre><code><ul>\n <li>\n <div style=\"background-color:red\">red</div>\n <div style=\"background-color:blue\">blue</div>\n </li>\n <li>\n <span style=\"background-color:red\">red</span>\n <span style=\"background-color:blue\">blue</span>\n </li>\n</ul>\n</code></pre>\n\n<p>Also, at least for Microsoft <code><li><div></div></li></code> won't validate.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17781/"
]
| I have a list with two `<div>`s in every `<li>` and I want to float them one next to the other and I want the `<li>` to take the whole availabe space. How do I do it?
```
<html>
<head>
<title></title>
<style type="text/css">
body {
}
ul {
}
li {
}
.a {
}
.b {
}
</style>
</head>
<body>
<ul>
<li>
<div class="a">
content
</div>
<div class="b">
content
</div>
</li>
</ul>
</body>
</html>
``` | ```css
*{ margin: 0; padding: 0;}
li{ width: 100%: display: block; }
li:after{ clear: both; }
div.a{ width: 49%; float: left; }
div.b{ width: 49%; float: left; }
```
Should do the trick. |
93,638 | <p>I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.</p>
<p>At the window level is there a way to get the current selected item for the currently in focus list based control? I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?</p>
<p>Something like Window.CurrentSelectedDataItem would be great. I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item.</p>
| [
{
"answer_id": 95031,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:</p>\n\n<pre><code>EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,\n new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));\n</code></pre>\n\n<p>This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it.</p>\n"
},
{
"answer_id": 153784,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tried this, but you could try using a MultiBinding with a converter to get to the correct item:</p>\n\n<pre><code><MultiBinding Converter=\"{StaticResource coalesce}\">\n <MultiBinding.Bindings>\n <MultiBinding Converter=\"{StaticResource nullIfFalse}\">\n <MultiBinding.Bindings>\n <Binding ElementName=\"List1\" Path=\"HasFocus\" />\n <Binding ElementName=\"List1\" Path=\"SelectedItem\" />\n</code></pre>\n\n<p><code>nullIfFalse</code> returns the second parameter, if the first is true, null otherwise. <code>coalesce</code> returns the first non-null element.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.
At the window level is there a way to get the current selected item for the currently in focus list based control? I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?
Something like Window.CurrentSelectedDataItem would be great. I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item. | I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:
```
EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,
new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));
```
This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it. |
93,650 | <p>How do you apply stroke (outline around text) to a textblock in xaml in WPF?</p>
| [
{
"answer_id": 94235,
"author": "Tim Erickson",
"author_id": 8787,
"author_profile": "https://Stackoverflow.com/users/8787",
"pm_score": 1,
"selected": false,
"text": "<p>In Blend you could convert the TextBlock to a Path, and then use the normal Stroke properties. But I'm assuming you wanted something that you could make dynamic...</p>\n\n<p>Otherwise I would think it would have to be some sort of bitmap effect or special brush.</p>\n"
},
{
"answer_id": 94264,
"author": "kaiz.net",
"author_id": 3714,
"author_profile": "https://Stackoverflow.com/users/3714",
"pm_score": 0,
"selected": false,
"text": "<p><TextBlock> has no decorative attributes itself. I would put it on a <Canvas> with a <Rectangle> and apply the stroke there.</p>\n"
},
{
"answer_id": 94801,
"author": "SmartyP",
"author_id": 18005,
"author_profile": "https://Stackoverflow.com/users/18005",
"pm_score": 3,
"selected": false,
"text": "<p>you should wrap the TextBlock with a Border.. something like this:</p>\n\n<pre><code> <Border BorderBrush=\"Purple\" BorderThickness=\"2\">\n <TextBlock>My fancy TextBlock</TextBlock>\n </Border>\n</code></pre>\n\n<p>in the off chance you are asking how to put a stroke around the actual letters (and not the whole TextBlock) you may want to look at using a BitmapEffect of Glow and setting the parameters on the Glow to be the stroke color you want, etc. Otherwise you may have to create something custom.</p>\n"
},
{
"answer_id": 97728,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 5,
"selected": false,
"text": "<p>Found It. Not so easy to do apparently, there is no built in Stroke text in WPF (kind of a big missing feature if you ask me). First create the custom class:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Windows.Media;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Markup;\n\nnamespace CustomXaml\n{\n\npublic class OutlinedText : FrameworkElement, IAddChild\n{\n #region Private Fields\n\n private Geometry _textGeometry;\n\n #endregion\n\n #region Private Methods\n\n /// <summary>\n /// Invoked when a dependency property has changed. Generate a new FormattedText object to display.\n /// </summary>\n /// <param name=\"d\">OutlineText object whose property was updated.</param>\n /// <param name=\"e\">Event arguments for the dependency property.</param>\n private static void OnOutlineTextInvalidated(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n ((OutlinedText)d).CreateText();\n }\n\n #endregion\n\n\n #region FrameworkElement Overrides\n\n /// <summary>\n /// OnRender override draws the geometry of the text and optional highlight.\n /// </summary>\n /// <param name=\"drawingContext\">Drawing context of the OutlineText control.</param>\n protected override void OnRender(DrawingContext drawingContext)\n {\n CreateText();\n // Draw the outline based on the properties that are set.\n drawingContext.DrawGeometry(Fill, new Pen(Stroke, StrokeThickness), _textGeometry);\n\n }\n\n /// <summary>\n /// Create the outline geometry based on the formatted text.\n /// </summary>\n public void CreateText()\n {\n FontStyle fontStyle = FontStyles.Normal;\n FontWeight fontWeight = FontWeights.Medium;\n\n if (Bold == true) fontWeight = FontWeights.Bold;\n if (Italic == true) fontStyle = FontStyles.Italic;\n\n // Create the formatted text based on the properties set.\n FormattedText formattedText = new FormattedText(\n Text,\n CultureInfo.GetCultureInfo(\"en-us\"), \n FlowDirection.LeftToRight,\n new Typeface(Font, fontStyle, fontWeight, FontStretches.Normal), \n FontSize,\n Brushes.Black // This brush does not matter since we use the geometry of the text. \n );\n\n // Build the geometry object that represents the text.\n _textGeometry = formattedText.BuildGeometry(new Point(0, 0));\n\n\n\n\n //set the size of the custome control based on the size of the text\n this.MinWidth = formattedText.Width;\n this.MinHeight = formattedText.Height;\n\n }\n\n #endregion\n\n #region DependencyProperties\n\n /// <summary>\n /// Specifies whether the font should display Bold font weight.\n /// </summary>\n public bool Bold\n {\n get\n {\n return (bool)GetValue(BoldProperty);\n }\n\n set\n {\n SetValue(BoldProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Bold dependency property.\n /// </summary>\n public static readonly DependencyProperty BoldProperty = DependencyProperty.Register(\n \"Bold\",\n typeof(bool),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n false,\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// Specifies the brush to use for the fill of the formatted text.\n /// </summary>\n public Brush Fill\n {\n get\n {\n return (Brush)GetValue(FillProperty);\n }\n\n set\n {\n SetValue(FillProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Fill dependency property.\n /// </summary>\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n \"Fill\",\n typeof(Brush),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n new SolidColorBrush(Colors.LightSteelBlue),\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// The font to use for the displayed formatted text.\n /// </summary>\n public FontFamily Font\n {\n get\n {\n return (FontFamily)GetValue(FontProperty);\n }\n\n set\n {\n SetValue(FontProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Font dependency property.\n /// </summary>\n public static readonly DependencyProperty FontProperty = DependencyProperty.Register(\n \"Font\",\n typeof(FontFamily),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n new FontFamily(\"Arial\"),\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// The current font size.\n /// </summary>\n public double FontSize\n {\n get\n {\n return (double)GetValue(FontSizeProperty);\n }\n\n set\n {\n SetValue(FontSizeProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the FontSize dependency property.\n /// </summary>\n public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register(\n \"FontSize\",\n typeof(double),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n (double)48.0,\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n\n /// <summary>\n /// Specifies whether the font should display Italic font style.\n /// </summary>\n public bool Italic\n {\n get\n {\n return (bool)GetValue(ItalicProperty);\n }\n\n set\n {\n SetValue(ItalicProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Italic dependency property.\n /// </summary>\n public static readonly DependencyProperty ItalicProperty = DependencyProperty.Register(\n \"Italic\",\n typeof(bool),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n false,\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// Specifies the brush to use for the stroke and optional hightlight of the formatted text.\n /// </summary>\n public Brush Stroke\n {\n get\n {\n return (Brush)GetValue(StrokeProperty);\n }\n\n set\n {\n SetValue(StrokeProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Stroke dependency property.\n /// </summary>\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n \"Stroke\",\n typeof(Brush),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n new SolidColorBrush(Colors.Teal),\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// The stroke thickness of the font.\n /// </summary>\n public ushort StrokeThickness\n {\n get\n {\n return (ushort)GetValue(StrokeThicknessProperty);\n }\n\n set\n {\n SetValue(StrokeThicknessProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the StrokeThickness dependency property.\n /// </summary>\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n \"StrokeThickness\",\n typeof(ushort),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n (ushort)0,\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n /// <summary>\n /// Specifies the text string to display.\n /// </summary>\n public string Text\n {\n get\n {\n return (string)GetValue(TextProperty);\n }\n\n set\n {\n SetValue(TextProperty, value);\n }\n }\n\n /// <summary>\n /// Identifies the Text dependency property.\n /// </summary>\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n \"Text\",\n typeof(string),\n typeof(OutlinedText),\n new FrameworkPropertyMetadata(\n \"\",\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnOutlineTextInvalidated),\n null\n )\n );\n\n public void AddChild(Object value)\n {\n\n }\n\n public void AddText(string value)\n {\n Text = value;\n }\n\n #endregion\n}\n}\n</code></pre>\n\n<p>The you can reference it in your xaml.</p>\n\n<pre><code><Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:customControls=\"clr-namespace:CustomXaml;assembly=CustomXaml\">\n <Grid>\n <customControls:OutlinedText x:Name=\"TextContent\" Fill=\"#ffffffff\" FontSize=\"28\" \nBold=\"True\" Stroke=\"Black\" StrokeThickness=\"1\" Text=\"Back\" Margin=\"10,0,10,0\" \nHorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" Height=\"Auto\" Width=\"Auto\" />\n </Grid>\n</Page>\n</code></pre>\n"
},
{
"answer_id": 447587,
"author": "Ifeanyi Echeruo",
"author_id": 47702,
"author_profile": "https://Stackoverflow.com/users/47702",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/ms745816.aspx\" rel=\"noreferrer\">"How to: Create Outlined Text" on MSDN</a> has all the information you need.</p>\n"
},
{
"answer_id": 4910507,
"author": "JBrooks",
"author_id": 136059,
"author_profile": "https://Stackoverflow.com/users/136059",
"pm_score": 0,
"selected": false,
"text": "<p>Could just use a Label instead. It has more properties that you can play with. Example:</p>\n\n<pre><code> <Style x:Key=\"LeftBorderLabel\" TargetType=\"{x:Type Label}\">\n <Setter Property=\"Margin\" Value=\"0\" />\n <Setter Property=\"BorderThickness\" Value=\"1,0,0,0\" />\n <Setter Property=\"BorderBrush\" Value=\"Blue\" />\n </Style>\n</code></pre>\n"
},
{
"answer_id": 6795547,
"author": "diceguyd30",
"author_id": 464094,
"author_profile": "https://Stackoverflow.com/users/464094",
"pm_score": 0,
"selected": false,
"text": "<p>This helped me out tremendously! Just in case anyone needs it in the future, here's the VB version (made StrokeThickness a double and added an Underline property):</p>\n\n<pre><code>Imports System\nImports System.Windows.Media\nImports System.Globalization\nImports System.Windows\nImports System.Windows.Markup\n\nNamespace CustomXaml\n\n Public Class OutlinedText\n Inherits FrameworkElement\n Implements IAddChild\n\n Private _textGeometry As Geometry\n\n Private Shared Sub OnOutlineTextInvalidated(d As DependencyObject, e As DependencyPropertyChangedEventArgs)\n DirectCast(d, OutlinedText).CreateText()\n End Sub\n\n Protected Overrides Sub OnRender(drawingContext As System.Windows.Media.DrawingContext)\n CreateText()\n drawingContext.DrawGeometry(Fill, New Pen(Stroke, StrokeThickness), _textGeometry)\n End Sub\n\n Public Sub CreateText()\n Dim fontStyle = FontStyles.Normal\n Dim fontWeight = FontWeights.Medium\n Dim fontDecoration = New TextDecorationCollection()\n\n If Bold Then fontWeight = FontWeights.Bold\n If Italic Then fontStyle = FontStyles.Italic\n If Underline Then fontDecoration.Add(TextDecorations.Underline)\n\n Dim formattedText = New FormattedText( _\n Text, _\n CultureInfo.GetCultureInfo(\"en-us\"), _\n FlowDirection.LeftToRight, _\n New Typeface(Font, fontStyle, fontWeight, FontStretches.Normal), _\n FontSize, _\n Brushes.Black _\n )\n formattedText.SetTextDecorations(fontDecoration)\n\n _textGeometry = formattedText.BuildGeometry(New Point(0, 0))\n\n Me.MinWidth = formattedText.Width\n Me.MinHeight = formattedText.Height\n End Sub\n\n Public Property Bold As Boolean\n Get\n Return CType(GetValue(BoldProperty), Boolean)\n End Get\n Set(value As Boolean)\n SetValue(BoldProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly BoldProperty As DependencyProperty = DependencyProperty.Register( _\n \"Bold\", _\n GetType(Boolean), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n False, _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Underline As Boolean\n Get\n Return CType(GetValue(UnderlineProperty), Boolean)\n End Get\n Set(value As Boolean)\n SetValue(UnderlineProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly UnderlineProperty As DependencyProperty = DependencyProperty.Register( _\n \"Underline\", _\n GetType(Boolean), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n False, _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Fill As Brush\n Get\n Return CType(GetValue(FillProperty), Brush)\n End Get\n Set(value As Brush)\n SetValue(FillProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly FillProperty As DependencyProperty = DependencyProperty.Register( _\n \"Fill\", _\n GetType(Brush), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n New SolidColorBrush(Colors.LightSteelBlue), _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Font As FontFamily\n Get\n Return CType(GetValue(FontProperty), FontFamily)\n End Get\n Set(value As FontFamily)\n SetValue(FontProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly FontProperty As DependencyProperty = DependencyProperty.Register( _\n \"Font\", _\n GetType(FontFamily), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n New FontFamily(\"Arial\"), _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property FontSize As Double\n Get\n Return CType(GetValue(FontSizeProperty), Double)\n End Get\n Set(value As Double)\n SetValue(FontSizeProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly FontSizeProperty As DependencyProperty = DependencyProperty.Register( _\n \"FontSize\", _\n GetType(Double), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n CDbl(48.0), _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Italic As Boolean\n Get\n Return CType(GetValue(ItalicProperty), Boolean)\n End Get\n Set(value As Boolean)\n SetValue(ItalicProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly ItalicProperty As DependencyProperty = DependencyProperty.Register( _\n \"Italic\", _\n GetType(Boolean), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n False, _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Stroke As Brush\n Get\n Return CType(GetValue(StrokeProperty), Brush)\n End Get\n Set(value As Brush)\n SetValue(StrokeProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly StrokeProperty As DependencyProperty = DependencyProperty.Register( _\n \"Stroke\", _\n GetType(Brush), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n New SolidColorBrush(Colors.Teal), _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property StrokeThickness As Double\n Get\n Return CType(GetValue(StrokeThicknessProperty), Double)\n End Get\n Set(value As Double)\n SetValue(StrokeThicknessProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly StrokeThicknessProperty As DependencyProperty = DependencyProperty.Register( _\n \"StrokeThickness\", _\n GetType(Double), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n CDbl(0), _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Property Text As String\n Get\n Return CType(GetValue(TextProperty), String)\n End Get\n Set(value As String)\n SetValue(TextProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly TextProperty As DependencyProperty = DependencyProperty.Register( _\n \"Text\", _\n GetType(String), _\n GetType(OutlinedText), _\n New FrameworkPropertyMetadata( _\n \"\", _\n FrameworkPropertyMetadataOptions.AffectsRender, _\n New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _\n Nothing _\n ) _\n )\n\n Public Sub AddChild(value As Object) Implements System.Windows.Markup.IAddChild.AddChild\n\n End Sub\n\n Public Sub AddText(text As String) Implements System.Windows.Markup.IAddChild.AddText\n Me.Text = text\n End Sub\n End Class\nEnd Namespace\n</code></pre>\n"
},
{
"answer_id": 9887123,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 8,
"selected": true,
"text": "<p>Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including:</p>\n\n<ul>\n<li>all font related properties including stretch and style</li>\n<li>text alignment (left, right, center, justify)</li>\n<li>text wrapping</li>\n<li>text trimming</li>\n<li>text decorations (underline, strike through etcetera)</li>\n</ul>\n\n<p>Here's a simple example of what can be achieved with it:</p>\n\n<pre><code><local:OutlinedTextBlock FontFamily=\"Verdana\" FontSize=\"20pt\" FontWeight=\"ExtraBold\" TextWrapping=\"Wrap\" StrokeThickness=\"1\" Stroke=\"{StaticResource TextStroke}\" Fill=\"{StaticResource TextFill}\">\n Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit\n</local:OutlinedTextBlock>\n</code></pre>\n\n<p>Which results in:</p>\n\n<p><img src=\"https://i.stack.imgur.com/gyDYX.png\" alt=\"enter image description here\"></p>\n\n<p>Here's the code for the control:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\n[ContentProperty(\"Text\")]\npublic class OutlinedTextBlock : FrameworkElement\n{\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n \"Fill\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n \"Stroke\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n \"StrokeThickness\",\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n \"Text\",\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n \"TextAlignment\",\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n \"TextDecorations\",\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n \"TextTrimming\",\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n \"TextWrapping\",\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText formattedText;\n private Geometry textGeometry;\n\n public OutlinedTextBlock()\n {\n this.TextDecorations = new TextDecorationCollection();\n }\n\n public Brush Fill\n {\n get { return (Brush)GetValue(FillProperty); }\n set { SetValue(FillProperty, value); }\n }\n\n public FontFamily FontFamily\n {\n get { return (FontFamily)GetValue(FontFamilyProperty); }\n set { SetValue(FontFamilyProperty, value); }\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get { return (double)GetValue(FontSizeProperty); }\n set { SetValue(FontSizeProperty, value); }\n }\n\n public FontStretch FontStretch\n {\n get { return (FontStretch)GetValue(FontStretchProperty); }\n set { SetValue(FontStretchProperty, value); }\n }\n\n public FontStyle FontStyle\n {\n get { return (FontStyle)GetValue(FontStyleProperty); }\n set { SetValue(FontStyleProperty, value); }\n }\n\n public FontWeight FontWeight\n {\n get { return (FontWeight)GetValue(FontWeightProperty); }\n set { SetValue(FontWeightProperty, value); }\n }\n\n public Brush Stroke\n {\n get { return (Brush)GetValue(StrokeProperty); }\n set { SetValue(StrokeProperty, value); }\n }\n\n public double StrokeThickness\n {\n get { return (double)GetValue(StrokeThicknessProperty); }\n set { SetValue(StrokeThicknessProperty, value); }\n }\n\n public string Text\n {\n get { return (string)GetValue(TextProperty); }\n set { SetValue(TextProperty, value); }\n }\n\n public TextAlignment TextAlignment\n {\n get { return (TextAlignment)GetValue(TextAlignmentProperty); }\n set { SetValue(TextAlignmentProperty, value); }\n }\n\n public TextDecorationCollection TextDecorations\n {\n get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); }\n set { this.SetValue(TextDecorationsProperty, value); }\n }\n\n public TextTrimming TextTrimming\n {\n get { return (TextTrimming)GetValue(TextTrimmingProperty); }\n set { SetValue(TextTrimmingProperty, value); }\n }\n\n public TextWrapping TextWrapping\n {\n get { return (TextWrapping)GetValue(TextWrappingProperty); }\n set { SetValue(TextWrappingProperty, value); }\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n this.EnsureGeometry();\n\n drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);\n }\n\n protected override Size MeasureOverride(Size availableSize)\n {\n this.EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);\n this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height);\n\n // return the desired size\n return new Size(this.formattedText.Width, this.formattedText.Height);\n }\n\n protected override Size ArrangeOverride(Size finalSize)\n {\n this.EnsureFormattedText();\n\n // update the formatted text with the final size\n this.formattedText.MaxTextWidth = finalSize.Width;\n this.formattedText.MaxTextHeight = finalSize.Height;\n\n // need to re-generate the geometry now that the dimensions have changed\n this.textGeometry = null;\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock.formattedText = null;\n outlinedTextBlock.textGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock.textGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText()\n {\n if (this.formattedText != null || this.Text == null)\n {\n return;\n }\n\n this.formattedText = new FormattedText(\n this.Text,\n CultureInfo.CurrentUICulture,\n this.FlowDirection,\n new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),\n this.FontSize,\n Brushes.Black);\n\n this.UpdateFormattedText();\n }\n\n private void UpdateFormattedText()\n {\n if (this.formattedText == null)\n {\n return;\n }\n\n this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n this.formattedText.TextAlignment = this.TextAlignment;\n this.formattedText.Trimming = this.TextTrimming;\n\n this.formattedText.SetFontSize(this.FontSize);\n this.formattedText.SetFontStyle(this.FontStyle);\n this.formattedText.SetFontWeight(this.FontWeight);\n this.formattedText.SetFontFamily(this.FontFamily);\n this.formattedText.SetFontStretch(this.FontStretch);\n this.formattedText.SetTextDecorations(this.TextDecorations);\n }\n\n private void EnsureGeometry()\n {\n if (this.textGeometry != null)\n {\n return;\n }\n\n this.EnsureFormattedText();\n this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10858323,
"author": "Paul Duffy",
"author_id": 1431737,
"author_profile": "https://Stackoverflow.com/users/1431737",
"pm_score": 1,
"selected": false,
"text": "<p>Slight modification to Kent Boogaart's code which, while awesome, is missing a small detail. This is probably a little inaccurate in that it will only measure the fill and not the stroke but adding a couple of lines to <code>OnRender()</code> <code>Viewbox</code> will be able to get a handle on what to do with it (although, as with <code>TextBox</code>, not in preview).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected override void OnRender(DrawingContext drawingContext)\n{\n this.EnsureGeometry();\n\n this.Width = this.formattedText.Width;\n this.Height = this.formattedText.Height;\n\n drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);\n}\n</code></pre>\n\n<p>I'm using this with two layers of text so the stroke appears to only be around the outside as follows. This will obviously not work straight away as it refers to specific images and fonts.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><Viewbox Stretch=\"UniformToFill\" Margin=\"0\" Grid.Column=\"1\">\n <bd:OutlinedText x:Name=\"LevelTitleStroke\" Text=\"Level\" FontSize=\"80pt\" FontFamily=\"/fonts/papercuts-2.ttf#Paper Cuts 2\" Grid.Row=\"1\" TextAlignment=\"Center\" IsHitTestVisible=\"False\" StrokeThickness=\"15\">\n <bd:OutlinedText.Stroke>\n <ImageBrush ImageSource=\"/WpfApplication1;component/GrungeMaps/03DarkBlue.jpg\" Stretch=\"None\" />\n </bd:OutlinedText.Stroke>\n </bd:OutlinedText>\n</Viewbox>\n<Viewbox Stretch=\"UniformToFill\" Margin=\"0\" Grid.Column=\"1\">\n <bd:OutlinedText x:Name=\"LevelTitleFill\" Text=\"Level\" FontSize=\"80pt\" FontFamily=\"/fonts/papercuts-2.ttf#Paper Cuts 2\" Grid.Row=\"1\" TextAlignment=\"Center\" IsHitTestVisible=\"False\">\n <bd:OutlinedText.Fill>\n <ImageBrush ImageSource=\"/WpfApplication1;component/GrungeMaps/03Red.jpg\" Stretch=\"None\" />\n </bd:OutlinedText.Fill>\n </bd:OutlinedText>\n</Viewbox>\n</code></pre>\n"
},
{
"answer_id": 11547043,
"author": "Chris Klepeis",
"author_id": 71904,
"author_profile": "https://Stackoverflow.com/users/71904",
"pm_score": 0,
"selected": false,
"text": "<p>I was using Kent's solution in my custom control. It resulted in a null exception when using templatebinding against the text property.</p>\n\n<p>I had to modify the MeasureOverride function like so:</p>\n\n<pre><code> protected override Size MeasureOverride(Size availableSize)\n {\n this.EnsureFormattedText();\n\n if (this.formattedText == null)\n {\n this.formattedText = new FormattedText(\n (this.Text == null) ? \"\" : this.Text,\n CultureInfo.CurrentUICulture,\n this.FlowDirection,\n new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),\n this.FontSize,\n Brushes.Black);\n }\n\n // constrain the formatted text according to the available size\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);\n this.formattedText.MaxTextHeight = availableSize.Height;\n\n // return the desired size\n return new Size(this.formattedText.Width, this.formattedText.Height);\n }\n</code></pre>\n\n<p>It should be noted that I did not thoroughly test this.</p>\n"
},
{
"answer_id": 22998692,
"author": "Steph M",
"author_id": 2453011,
"author_profile": "https://Stackoverflow.com/users/2453011",
"pm_score": 1,
"selected": false,
"text": "<p>I was trying to achieve something similar to this as well. The classes mentioned here were great, but weren't exactly what I was looking for, because it only really looked right if the text was large enough. The text I was trying to display was around 10 - 11 font size, and the stroke was so large the letters sort of blended together. </p>\n\n<p>Just to clarify, this text was supposed to be overlaid on a user-defined picture, which could have varying colors, and I wanted to ensure this text would show up.</p>\n\n<p>I don't know if this is best practice or not, but this at least achieved the look I wanted (based on <a href=\"http://msdn.microsoft.com/en-us/library/ms748273%28v=vs.110%29.aspx%29%3a\" rel=\"nofollow\">this article</a>):</p>\n\n<pre><code><Style x:Key=\"OutlinedTextBlockOuter\" TargetType=\"TextBlock\">\n <Setter Property=\"Foreground\" Value=\"Black\" />\n <Setter Property=\"FontSize\" Value=\"10\"/>\n <Setter Property=\"Effect\">\n <Setter.Value>\n <BlurEffect Radius=\"3.0\"/>\n </Setter.Value>\n </Setter>\n</Style>\n<Style x:Key=\"OutlinedTextBlockInner\" TargetType=\"TextBlock\">\n <Setter Property=\"Foreground\" Value=\"White\" />\n <Setter Property=\"FontSize\" Value=\"10\"/>\n</Style>\n</code></pre>\n\n<p>Then for the actual TextBlocks, I combined two Outer styled TextBlocks because one was too light, and one Inner styled TextBlock:</p>\n\n<pre><code><Grid Margin=\"5\">\n <TextBlock Style=\"{StaticResource OutlinedTextBlockOuter}\" Text=\"This is outlined text using BlurEffect\"/>\n <TextBlock Style=\"{StaticResource OutlinedTextBlockOuter}\" Text=\"This is outlined text using BlurEffect\"/>\n <TextBlock Style=\"{StaticResource OutlinedTextBlockInner}\" Text=\"This is outlined text using BlurEffect\"/>\n</Grid>\n</code></pre>\n\n<p>Alternatively, you could use the DropShadowEffect, which looked okay with using only two textboxes (although adding more DropShadowEffects with varying directions and lowered opacity may look even better):</p>\n\n<pre><code><Grid Margin=\"5\">\n <TextBlock Text=\"This is my outlined text using the DropShadowEffect\" FontSize=\"10\" Foreground=\"White\">\n <TextBlock.Effect>\n <DropShadowEffect ShadowDepth=\"1\" BlurRadius=\"2\" Opacity=\"0.75\" Direction=\"315\"/>\n </TextBlock.Effect>\n </TextBlock>\n <TextBlock Text=\"This is my outlined text using the DropShadowEffect\" FontSize=\"10\" Foreground=\"White\">\n <TextBlock.Effect>\n <DropShadowEffect ShadowDepth=\"1\" BlurRadius=\"2\" Opacity=\"0.75\" Direction=\"135\"/>\n </TextBlock.Effect>\n </TextBlock>\n</Grid>\n</code></pre>\n"
},
{
"answer_id": 25739593,
"author": "Eyal Kofman Cagan",
"author_id": 4021994,
"author_profile": "https://Stackoverflow.com/users/4021994",
"pm_score": 2,
"selected": false,
"text": "<p>If applied for anyone, here a simple solution using ONLY XAML. I am not sure if it performs better or worse, but in my opinion, it looks better then any other solution above.\nI wrap it in a <code>ContentControl</code> Style (and Template), following this Old School example :)\n<a href=\"http://oldschooldotnet.blogspot.co.il/2009/02/fancy-fonts-in-xaml-silverlight-and-wpf.html\" rel=\"nofollow noreferrer\">http://oldschooldotnet.blogspot.co.il/2009/02/fancy-fonts-in-xaml-silverlight-and-wpf.html</a></p>\n\n<pre><code><Style x:Key=\"OutlinedText\" TargetType=\"{x:Type ContentControl}\">\n <!-- Some Style Setters -->\n <Setter Property=\"Content\" Value=\"Outlined Text\"/>\n <Setter Property=\"Padding\" Value=\"0\"/>\n <!-- Border Brush Must be equal '0' because TextBlock that emulate the stroke will using the BorderBrush as to define 'Stroke' color-->\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <!-- Border Brush define 'Stroke' Color-->\n <Setter Property=\"BorderBrush\" Value=\"White\"/>\n <Setter Property=\"Foreground\" Value=\"Black\"/>\n <Setter Property=\"FontSize\" Value=\"24\"/>\n <Setter Property=\"FontFamily\" Value=\"Seoge UI Bold\"/>\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Center\"/>\n <Setter Property=\"VerticalContentAlignment\" Value=\"Center\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ContentControl}\">\n <Canvas Width=\"{Binding ActualWidth, ElementName=FillText}\" Height=\"{Binding ActualHeight, ElementName=FillText}\">\n <Canvas.Resources>\n <!-- Style to ease the duplication of Text Blocks that emulate the stroke: Binding to one element (or to template) is the first part of the Trick -->\n <Style x:Key=\"OutlinedTextStrokeTextBlock_Style\" TargetType=\"{x:Type TextBlock}\">\n <Setter Property=\"Text\" Value=\"{Binding Text, ElementName=FillText}\"/>\n <Setter Property=\"FontSize\" Value=\"{Binding FontSize, ElementName=FillText}\"/>\n <Setter Property=\"FontFamily\" Value=\"{Binding FontFamily, ElementName=FillText}\"/>\n <Setter Property=\"FontStyle\" Value=\"{Binding FontStyle, ElementName=FillText}\"/>\n <Setter Property=\"FontWeight\" Value=\"{Binding FontWeight, ElementName=FillText}\"/>\n <Setter Property=\"Padding\" Value=\"{Binding TextAlignment, ElementName=Padding}\"/>\n <Setter Property=\"TextAlignment\" Value=\"{Binding TextAlignment, ElementName=FillText}\"/>\n <Setter Property=\"VerticalAlignment\" Value=\"{Binding VerticalAlignment, ElementName=FillText}\"/>\n </Style>\n </Canvas.Resources>\n <!-- Offseting the Text block will create the outline, the margin is the Stroke Width-->\n <TextBlock Foreground=\"{TemplateBinding BorderBrush}\" Margin=\"-1,0,0,0\" Style=\"{DynamicResource OutlinedTextStrokeTextBlock_Style}\"/>\n <TextBlock Foreground=\"{TemplateBinding BorderBrush}\" Margin=\"0,-1,0,0\" Style=\"{DynamicResource OutlinedTextStrokeTextBlock_Style}\"/>\n <TextBlock Foreground=\"{TemplateBinding BorderBrush}\" Margin=\"0,0,-1,0\" Style=\"{DynamicResource OutlinedTextStrokeTextBlock_Style}\"/>\n <TextBlock Foreground=\"{TemplateBinding BorderBrush}\" Margin=\"0,0,0,-1\" Style=\"{DynamicResource OutlinedTextStrokeTextBlock_Style}\"/>\n <!-- Base TextBlock Will be the Fill -->\n <TextBlock x:Name=\"FillText\" Text=\"{TemplateBinding Content}\" FontSize=\"{TemplateBinding FontSize}\" FontFamily=\"{TemplateBinding FontFamily}\"\n FontStyle=\"{TemplateBinding FontStyle}\" FontWeight=\"{TemplateBinding FontWeight}\" Padding=\"0\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" \n TextAlignment=\"{TemplateBinding HorizontalContentAlignment}\"\n Style=\"{DynamicResource TbMediaOverlay_Style}\"/>\n </Canvas>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 35261866,
"author": "Javier G.",
"author_id": 4814450,
"author_profile": "https://Stackoverflow.com/users/4814450",
"pm_score": 1,
"selected": false,
"text": "<p>I had to add this to MeasureOverride so it would show single lines of text while using layout rounding. It worked fine when the text was wrapping though.</p>\n\n<pre><code>// return the desired size\nreturn new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n</code></pre>\n"
},
{
"answer_id": 35262509,
"author": "Javier G.",
"author_id": 4814450,
"author_profile": "https://Stackoverflow.com/users/4814450",
"pm_score": 6,
"selected": false,
"text": "<p>I modified the most voted answer with several fixes, including:</p>\n\n<ul>\n<li><p>Fix so texts with a single line would show when using\nUseLayoutRounding.</p></li>\n<li><p>Outlines would show outside the text instead of in the middle of the \nborder. </p></li>\n<li><p>The pen is created only once instead of on each render.</p></li>\n<li><p>Fix so it won't crash when the text is set to null.</p></li>\n<li><p>Fix so outline uses proper round caps.</p></li>\n</ul>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\n[ContentProperty(\"Text\")]\npublic class OutlinedTextBlock : FrameworkElement\n{\n private void UpdatePen() {\n _Pen = new Pen(Stroke, StrokeThickness) {\n DashCap = PenLineCap.Round,\n EndLineCap = PenLineCap.Round,\n LineJoin = PenLineJoin.Round,\n StartLineCap = PenLineCap.Round\n };\n\n InvalidateVisual();\n }\n\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n \"Fill\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n \"Stroke\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender, StrokePropertyChangedCallback));\n\n private static void StrokePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) {\n (dependencyObject as OutlinedTextBlock)?.UpdatePen();\n }\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n \"StrokeThickness\",\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender, StrokePropertyChangedCallback));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n \"Text\",\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n \"TextAlignment\",\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n \"TextDecorations\",\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n \"TextTrimming\",\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n \"TextWrapping\",\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText _FormattedText;\n private Geometry _TextGeometry;\n private Pen _Pen;\n\n public Brush Fill\n {\n get { return (Brush)GetValue(FillProperty); }\n set { SetValue(FillProperty, value); }\n }\n\n public FontFamily FontFamily\n {\n get { return (FontFamily)GetValue(FontFamilyProperty); }\n set { SetValue(FontFamilyProperty, value); }\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get { return (double)GetValue(FontSizeProperty); }\n set { SetValue(FontSizeProperty, value); }\n }\n\n public FontStretch FontStretch\n {\n get { return (FontStretch)GetValue(FontStretchProperty); }\n set { SetValue(FontStretchProperty, value); }\n }\n\n public FontStyle FontStyle\n {\n get { return (FontStyle)GetValue(FontStyleProperty); }\n set { SetValue(FontStyleProperty, value); }\n }\n\n public FontWeight FontWeight\n {\n get { return (FontWeight)GetValue(FontWeightProperty); }\n set { SetValue(FontWeightProperty, value); }\n }\n\n public Brush Stroke\n {\n get { return (Brush)GetValue(StrokeProperty); }\n set { SetValue(StrokeProperty, value); }\n }\n\n public double StrokeThickness\n {\n get { return (double)GetValue(StrokeThicknessProperty); }\n set { SetValue(StrokeThicknessProperty, value); }\n }\n\n public string Text\n {\n get { return (string)GetValue(TextProperty); }\n set { SetValue(TextProperty, value); }\n }\n\n public TextAlignment TextAlignment\n {\n get { return (TextAlignment)GetValue(TextAlignmentProperty); }\n set { SetValue(TextAlignmentProperty, value); }\n }\n\n public TextDecorationCollection TextDecorations\n {\n get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }\n set { SetValue(TextDecorationsProperty, value); }\n }\n\n public TextTrimming TextTrimming\n {\n get { return (TextTrimming)GetValue(TextTrimmingProperty); }\n set { SetValue(TextTrimmingProperty, value); }\n }\n\n public TextWrapping TextWrapping\n {\n get { return (TextWrapping)GetValue(TextWrappingProperty); }\n set { SetValue(TextWrappingProperty, value); }\n }\n\n public OutlinedTextBlock() {\n UpdatePen();\n TextDecorations = new TextDecorationCollection();\n }\n\n protected override void OnRender(DrawingContext drawingContext) {\n EnsureGeometry();\n\n drawingContext.DrawGeometry(null, _Pen, _TextGeometry);\n drawingContext.DrawGeometry(Fill, null, _TextGeometry);\n }\n\n protected override Size MeasureOverride(Size availableSize) {\n EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n\n double w = availableSize.Width;\n double h = availableSize.Height;\n\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n _FormattedText.MaxTextWidth = Math.Min(3579139, w);\n _FormattedText.MaxTextHeight = Math.Max(0.0001d, h);\n\n // return the desired size\n return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n }\n\n protected override Size ArrangeOverride(Size finalSize) {\n EnsureFormattedText();\n\n // update the formatted text with the final size\n _FormattedText.MaxTextWidth = finalSize.Width;\n _FormattedText.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);\n\n // need to re-generate the geometry now that the dimensions have changed\n _TextGeometry = null;\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,\n DependencyPropertyChangedEventArgs e) {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock._FormattedText = null;\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText() {\n if (_FormattedText != null) {\n return;\n }\n\n _FormattedText = new FormattedText(\n Text ?? \"\",\n CultureInfo.CurrentUICulture,\n FlowDirection,\n new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),\n FontSize,\n Brushes.Black);\n\n UpdateFormattedText();\n }\n\n private void UpdateFormattedText() {\n if (_FormattedText == null) {\n return;\n }\n\n _FormattedText.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n _FormattedText.TextAlignment = TextAlignment;\n _FormattedText.Trimming = TextTrimming;\n\n _FormattedText.SetFontSize(FontSize);\n _FormattedText.SetFontStyle(FontStyle);\n _FormattedText.SetFontWeight(FontWeight);\n _FormattedText.SetFontFamily(FontFamily);\n _FormattedText.SetFontStretch(FontStretch);\n _FormattedText.SetTextDecorations(TextDecorations);\n }\n\n private void EnsureGeometry() {\n if (_TextGeometry != null) {\n return;\n }\n\n EnsureFormattedText();\n _TextGeometry = _FormattedText.BuildGeometry(new Point(0, 0));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49636033,
"author": "codeDom",
"author_id": 5306861,
"author_profile": "https://Stackoverflow.com/users/5306861",
"pm_score": 4,
"selected": false,
"text": "<p>I modified <a href=\"https://stackoverflow.com/a/35262509/5508373\">@Javier G. answer</a></p>\n\n<ul>\n<li><p>Stroke position can be: center, outside or Inside, the default\nis outside.</p></li>\n<li><p>Fill can be transparent.</p></li>\n</ul>\n\n<p>Center:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gdROq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gdROq.png\" alt=\"enter image description here\"></a></p>\n\n<p>Outside:</p>\n\n<p><a href=\"https://i.stack.imgur.com/q9mrL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/q9mrL.png\" alt=\"enter image description here\"></a></p>\n\n<p>Inside:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7zJfq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7zJfq.png\" alt=\"enter image description here\"></a></p>\n\n<p>Code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Documents;\nusing System.Windows.Markup;\nusing System.Windows.Media;\n\nnamespace WpfApp2\n{\n public enum StrokePosition\n {\n Center,\n Outside,\n Inside\n }\n\n [ContentProperty(\"Text\")]\n public class OutlinedTextBlock : FrameworkElement\n {\n private void UpdatePen()\n {\n _Pen = new Pen(Stroke, StrokeThickness)\n {\n DashCap = PenLineCap.Round,\n EndLineCap = PenLineCap.Round,\n LineJoin = PenLineJoin.Round,\n StartLineCap = PenLineCap.Round\n };\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n {\n _Pen.Thickness = StrokeThickness * 2;\n }\n\n InvalidateVisual();\n }\n\n public StrokePosition StrokePosition\n {\n get { return (StrokePosition)GetValue(StrokePositionProperty); }\n set { SetValue(StrokePositionProperty, value); }\n }\n\n public static readonly DependencyProperty StrokePositionProperty =\n DependencyProperty.Register(\"StrokePosition\", \n typeof(StrokePosition),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(StrokePosition.Outside, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FillProperty = DependencyProperty.Register(\n \"Fill\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(\n \"Stroke\",\n typeof(Brush),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(\n \"StrokeThickness\",\n typeof(double),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));\n\n public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextProperty = DependencyProperty.Register(\n \"Text\",\n typeof(string),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextInvalidated));\n\n public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(\n \"TextAlignment\",\n typeof(TextAlignment),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(\n \"TextDecorations\",\n typeof(TextDecorationCollection),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(\n \"TextTrimming\",\n typeof(TextTrimming),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(OnFormattedTextUpdated));\n\n public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(\n \"TextWrapping\",\n typeof(TextWrapping),\n typeof(OutlinedTextBlock),\n new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));\n\n private FormattedText _FormattedText;\n private Geometry _TextGeometry;\n private Pen _Pen;\n private PathGeometry _clipGeometry;\n\n public Brush Fill\n {\n get { return (Brush)GetValue(FillProperty); }\n set { SetValue(FillProperty, value); }\n }\n\n public FontFamily FontFamily\n {\n get { return (FontFamily)GetValue(FontFamilyProperty); }\n set { SetValue(FontFamilyProperty, value); }\n }\n\n [TypeConverter(typeof(FontSizeConverter))]\n public double FontSize\n {\n get { return (double)GetValue(FontSizeProperty); }\n set { SetValue(FontSizeProperty, value); }\n }\n\n public FontStretch FontStretch\n {\n get { return (FontStretch)GetValue(FontStretchProperty); }\n set { SetValue(FontStretchProperty, value); }\n }\n\n public FontStyle FontStyle\n {\n get { return (FontStyle)GetValue(FontStyleProperty); }\n set { SetValue(FontStyleProperty, value); }\n }\n\n public FontWeight FontWeight\n {\n get { return (FontWeight)GetValue(FontWeightProperty); }\n set { SetValue(FontWeightProperty, value); }\n }\n\n public Brush Stroke\n {\n get { return (Brush)GetValue(StrokeProperty); }\n set { SetValue(StrokeProperty, value); }\n }\n\n public double StrokeThickness\n {\n get { return (double)GetValue(StrokeThicknessProperty); }\n set { SetValue(StrokeThicknessProperty, value); }\n }\n\n public string Text\n {\n get { return (string)GetValue(TextProperty); }\n set { SetValue(TextProperty, value); }\n }\n\n public TextAlignment TextAlignment\n {\n get { return (TextAlignment)GetValue(TextAlignmentProperty); }\n set { SetValue(TextAlignmentProperty, value); }\n }\n\n public TextDecorationCollection TextDecorations\n {\n get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }\n set { SetValue(TextDecorationsProperty, value); }\n }\n\n public TextTrimming TextTrimming\n {\n get { return (TextTrimming)GetValue(TextTrimmingProperty); }\n set { SetValue(TextTrimmingProperty, value); }\n }\n\n public TextWrapping TextWrapping\n {\n get { return (TextWrapping)GetValue(TextWrappingProperty); }\n set { SetValue(TextWrappingProperty, value); }\n }\n\n public OutlinedTextBlock()\n {\n UpdatePen();\n TextDecorations = new TextDecorationCollection();\n }\n\n protected override void OnRender(DrawingContext drawingContext)\n {\n EnsureGeometry();\n\n drawingContext.DrawGeometry(Fill, null, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside)\n {\n drawingContext.PushClip(_clipGeometry);\n }\n else if (StrokePosition == StrokePosition.Inside)\n {\n drawingContext.PushClip(_TextGeometry);\n }\n\n drawingContext.DrawGeometry(null, _Pen, _TextGeometry);\n\n if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)\n {\n drawingContext.Pop();\n }\n }\n\n protected override Size MeasureOverride(Size availableSize)\n {\n EnsureFormattedText();\n\n // constrain the formatted text according to the available size\n\n double w = availableSize.Width;\n double h = availableSize.Height;\n\n // the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions\n // the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw\n _FormattedText.MaxTextWidth = Math.Min(3579139, w);\n _FormattedText.MaxTextHeight = Math.Max(0.0001d, h);\n\n // return the desired size\n return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));\n }\n\n protected override Size ArrangeOverride(Size finalSize)\n {\n EnsureFormattedText();\n\n // update the formatted text with the final size\n _FormattedText.MaxTextWidth = finalSize.Width;\n _FormattedText.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);\n\n // need to re-generate the geometry now that the dimensions have changed\n _TextGeometry = null;\n UpdatePen();\n\n return finalSize;\n }\n\n private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,\n DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock._FormattedText = null;\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n {\n var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;\n outlinedTextBlock.UpdateFormattedText();\n outlinedTextBlock._TextGeometry = null;\n\n outlinedTextBlock.InvalidateMeasure();\n outlinedTextBlock.InvalidateVisual();\n }\n\n private void EnsureFormattedText()\n {\n if (_FormattedText != null)\n {\n return;\n }\n\n _FormattedText = new FormattedText(\n Text ?? \"\",\n CultureInfo.CurrentUICulture,\n FlowDirection,\n new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),\n FontSize,\n Brushes.Black);\n\n UpdateFormattedText();\n }\n\n private void UpdateFormattedText()\n {\n if (_FormattedText == null)\n {\n return;\n }\n\n _FormattedText.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;\n _FormattedText.TextAlignment = TextAlignment;\n _FormattedText.Trimming = TextTrimming;\n\n _FormattedText.SetFontSize(FontSize);\n _FormattedText.SetFontStyle(FontStyle);\n _FormattedText.SetFontWeight(FontWeight);\n _FormattedText.SetFontFamily(FontFamily);\n _FormattedText.SetFontStretch(FontStretch);\n _FormattedText.SetTextDecorations(TextDecorations);\n }\n\n private void EnsureGeometry()\n {\n if (_TextGeometry != null)\n {\n return;\n }\n\n EnsureFormattedText();\n _TextGeometry = _FormattedText.BuildGeometry(new Point(0, 0));\n\n if (StrokePosition == StrokePosition.Outside)\n {\n var boundsGeo = new RectangleGeometry(new Rect(0, 0, ActualWidth, ActualHeight));\n _clipGeometry = Geometry.Combine(boundsGeo, _TextGeometry, GeometryCombineMode.Exclude, null);\n } \n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><Grid Margin=\"12\" Background=\"Bisque\">\n <local:OutlinedTextBlock Stroke=\"Red\" \n ClipToBounds=\"False\"\n FontSize=\"56\" \n Fill=\"Transparent\"\n StrokePosition=\"Inside\"\n StrokeThickness=\"1\" Text=\" abc\">\n </local:OutlinedTextBlock>\n</Grid>\n</code></pre>\n"
},
{
"answer_id": 51172253,
"author": "user00101010",
"author_id": 10031539,
"author_profile": "https://Stackoverflow.com/users/10031539",
"pm_score": 2,
"selected": false,
"text": "<p>as already mentioned, convert text to path</p>\n\n<pre><code>FormattedText t = new FormattedText\n(\n \"abcxyz\",\n CultureInfo.GetCultureInfo(\"en-us\"),\n FlowDirection.LeftToRight,\n new Typeface(\n new FontFamily(\"Arial\"),\n new FontStyle(),\n new FontWeight(),\n new FontStretch()),\n 20,\n Brushes.Transparent\n);\n\nGeometry g = t.BuildGeometry(new System.Windows.Point(0, 0));\n\nPath p = new Path();\np.Fill = Brushes.White;\np.Stroke = Brushes.Black;\np.StrokeThickness = 1;\np.Data = g;\n</code></pre>\n"
},
{
"answer_id": 56854629,
"author": "bwall",
"author_id": 5617177,
"author_profile": "https://Stackoverflow.com/users/5617177",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to use a regular Textblock, but apply a custom effect to it.</p>\n\n<p>Combining this <a href=\"https://www.codeproject.com/Articles/994276/Shader-Effects-in-WPF-The-basics\" rel=\"nofollow noreferrer\">Shader tutorial</a> and the <a href=\"https://en.wikipedia.org/wiki/Prewitt_operator\" rel=\"nofollow noreferrer\">Prewitt Edge Detection Filter</a> I managed to get a decent outline effect around text. While it has the advantage of rendering using the GPU, and <strong>applying to ANY UIElement</strong>, I'd say that @Kent Boogaart's answer looks a little better, and the EdgeResponse is finicky - I had to play with it a lot to get a nice outline.</p>\n\n<p>The end result in XAML:</p>\n\n<pre><code><Grid>\n <Grid.Resources>\n <local:EdgeDetectionEffect x:Key=\"OutlineEffect\"\n x:Shared=\"false\"\n EdgeResponse=\".44\"\n ActualHeight=\"{Binding RelativeSource={RelativeSource AncestorType=TextBlock}, Path=ActualHeight}\"\n ActualWidth=\"{Binding RelativeSource={RelativeSource AncestorType=TextBlock}, Path=ActualWidth}\"/>\n </Grid.Resources>\n <TextBlock Text=\"The Crazy Brown Fox Jumped Over the Lazy Dog.\"\n FontWeight=\"Bold\"\n FontSize=\"25\"\n Foreground=\"Yellow\"\n Effect=\"{StaticResource OutlineEffect}\"/>\n</Grid>\n</code></pre>\n\n<p>In order to create the custom effect, I first created the EdgeDetectionColorEffect.fx (hdld) file - this is the code the GPU uses to filter the image. I compiled it in Visual Studio Command Prompt with the command:</p>\n\n<p>fxc /T ps_2_0 /E main /Focc.ps EdgeDetectionColorEffect.fx</p>\n\n<pre><code>sampler2D Input : register(s0);\nfloat ActualWidth : register(c0);\nfloat ActualHeight : register(c1);\nfloat4 OutlineColor : register(c2);\nfloat EdgeDetectionResponse : register(c3);\n\nfloat4 GetNeighborPixel(float2 pixelPoint, float xOffset, float yOffset)\n{\n float2 NeighborPoint = {pixelPoint.x + xOffset, pixelPoint.y + yOffset};\n return tex2D(Input, NeighborPoint);\n}\n\n// pixel locations:\n// 00 01 02\n// 10 11 12\n// 20 21 22\nfloat main(float2 pixelPoint : TEXCOORD) : COLOR\n{\n\n float wo = 1 / ActualWidth; //WidthOffset\n float ho = 1 / ActualHeight; //HeightOffset\n\n float4 c00 = GetNeighborPixel(pixelPoint, -wo, -ho); // color of the pixel up and to the left of me.\n float4 c01 = GetNeighborPixel(pixelPoint, 00, -ho); \n float4 c02 = GetNeighborPixel(pixelPoint, wo, -ho);\n float4 c10 = GetNeighborPixel(pixelPoint, -wo, 0);\n float4 c11 = tex2D(Input, pixelPoint); // this is the current pixel\n float4 c12 = GetNeighborPixel(pixelPoint, wo, 0);\n float4 c20 = GetNeighborPixel(pixelPoint, -wo, ho);\n float4 c21 = GetNeighborPixel(pixelPoint, 0, ho);\n float4 c22 = GetNeighborPixel(pixelPoint, wo, ho);\n\n float t00 = c00.r + c00.g + c00.b; //total of color channels\n float t01 = c01.r + c01.g + c01.b;\n float t02 = c02.r + c02.g + c02.b;\n float t10 = c10.r + c10.g + c10.b;\n float t11 = c11.r + c11.g + c11.b;\n float t12 = c12.r + c12.g + c12.b;\n float t20 = c20.r + c20.g + c20.b;\n float t21 = c21.r + c21.g + c21.b;\n float t22 = c22.r + c22.g + c22.b;\n\n //Prewitt - convolve the 9 pixels with:\n // 01 01 01 01 00 -1\n // Gy = 00 00 00 Gx = 01 00 -1\n // -1 -1 -1 01 00 -1\n\n float gy = 0.0; float gx = 0.0;\n gy += t00; gx += t00;\n gy += t01; gx += t10;\n gy += t02; gx += t20;\n gy -= t20; gx -= t02;\n gy -= t21; gx -= t12;\n gy -= t22; gx -= t22;\n\n if((gy*gy + gx*gx) > EdgeDetectionResponse)\n {\n return OutlineColor;\n }\n\n return c11;\n}\n</code></pre>\n\n<p>Here's the wpf effect class:</p>\n\n<pre><code>public class EdgeDetectionEffect : ShaderEffect\n{\n private static PixelShader _shader = new PixelShader { UriSource = new Uri(\"path to your compiled shader probably called cc.ps\", UriKind.Absolute) };\n\npublic EdgeDetectionEffect()\n{\n PixelShader = _shader;\n UpdateShaderValue(InputProperty);\n UpdateShaderValue(ActualHeightProperty);\n UpdateShaderValue(ActualWidthProperty);\n UpdateShaderValue(OutlineColorProperty);\n UpdateShaderValue(EdgeResponseProperty);\n}\n\npublic Brush Input\n{\n get => (Brush)GetValue(InputProperty);\n set => SetValue(InputProperty, value);\n}\npublic static readonly DependencyProperty InputProperty = \n ShaderEffect.RegisterPixelShaderSamplerProperty(nameof(Input), \n typeof(EdgeDetectionEffect), 0);\n\npublic double ActualWidth\n{\n get => (double)GetValue(ActualWidthProperty);\n set => SetValue(ActualWidthProperty, value);\n}\npublic static readonly DependencyProperty ActualWidthProperty =\n DependencyProperty.Register(nameof(ActualWidth), typeof(double), typeof(EdgeDetectionEffect),\n new UIPropertyMetadata(1.0, PixelShaderConstantCallback(0)));\n\npublic double ActualHeight\n{\n get => (double)GetValue(ActualHeightProperty);\n set => SetValue(ActualHeightProperty, value);\n}\npublic static readonly DependencyProperty ActualHeightProperty =\n DependencyProperty.Register(nameof(ActualHeight), typeof(double), typeof(EdgeDetectionEffect),\n new UIPropertyMetadata(1.0, PixelShaderConstantCallback(1)));\n\npublic Color OutlineColor\n{\n get => (Color)GetValue(OutlineColorProperty);\n set => SetValue(OutlineColorProperty, value);\n}\npublic static readonly DependencyProperty OutlineColorProperty=\n DependencyProperty.Register(nameof(OutlineColor), typeof(Color), typeof(EdgeDetectionEffect),\n new UIPropertyMetadata(Colors.Black, PixelShaderConstantCallback(2)));\n\npublic double EdgeResponse\n{\n get => (double)GetValue(EdgeResponseProperty);\n set => SetValue(EdgeResponseProperty, value);\n}\npublic static readonly DependencyProperty EdgeResponseProperty =\n DependencyProperty.Register(nameof(EdgeResponse), typeof(double), typeof(EdgeDetectionEffect),\n new UIPropertyMetadata(4.0, PixelShaderConstantCallback(3)));\n}\n</code></pre>\n"
},
{
"answer_id": 69330921,
"author": "TRex",
"author_id": 13668671,
"author_profile": "https://Stackoverflow.com/users/13668671",
"pm_score": 0,
"selected": false,
"text": "<p>Since I have another answer, I'll post it for the record.\nI think it is a less elegant one, without using <code>Geometry</code>, <code>Path</code> and <code>FormattedText</code>, though simpler, and (if you know I'd like to know) might be faster to render ??\nIt basically had the same text 8 times, but shifted on all cardinal direction.</p>\n<p>here is the code of my UserControl :</p>\n<pre><code>/// <summary>\n/// User Control to display a Text with an outline\n/// </summary>\npublic partial class OutlinedText : UserControl, INotifyPropertyChanged\n{\n\n #region DependencyProperties\n\n /// <summary>\n /// The Text to render\n /// </summary>\n public string Text\n {\n get { return (string)GetValue(TextProperty); }\n set { SetValue(TextProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty TextProperty =\n DependencyProperty.Register("Text", typeof(string), typeof(OutlinedText), new PropertyMetadata(""));\n\n /// <summary>\n /// The size (thickness) of the Stroke\n /// </summary>\n public int StrokeSize\n {\n get { return (int)GetValue(StrokeSizeProperty); }\n set { SetValue(StrokeSizeProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for StrokeSize. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty StrokeSizeProperty =\n DependencyProperty.Register("StrokeSize", typeof(int), typeof(OutlinedText), new PropertyMetadata(1));\n\n /// <summary>\n /// The Color of the Stroke\n /// </summary>\n public Brush StrokeColor\n {\n get { return (Brush)GetValue(StrokeColorProperty); }\n set { SetValue(StrokeColorProperty, value); }\n }\n\n // Using a DependencyProperty as the backing store for StrokeColor. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty StrokeColorProperty =\n DependencyProperty.Register("StrokeColor", typeof(Brush), typeof(OutlinedText), new PropertyMetadata(Brushes.Black));\n\n #endregion\n\n #region ctor\n public OutlinedText()\n {\n InitializeComponent();\n this.DataContext = this;\n } \n #endregion\n\n public event PropertyChangedEventHandler PropertyChanged;\n protected virtual void OnPropertyChanged(string propertyName)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n}\n</code></pre>\n<p>and on XAML side :</p>\n<pre><code><UserControl x:Class="NAMESPACE.OutlinedText"\n xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" \n xmlns:d="http://schemas.microsoft.com/expression/blend/2008" \n xmlns:local="clr-namespace:NAMESPACE"\n mc:Ignorable="d" \n d:DesignHeight="450" d:DesignWidth="800">\n<UserControl.Resources>\n <ResourceDictionary>\n <local:IntegerInverterConverter x:Key="IntegerInverterConverterKey"/>\n </ResourceDictionary>\n</UserControl.Resources>\n<Grid>\n <!--Bottom Right ⬊ -->\n <TextBlock Foreground="{Binding StrokeColor}"\n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize}" Y="{Binding StrokeSize}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Top Left ⬉ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Bottom Left ⬋ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="{Binding StrokeSize}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Top Right ⬈ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize}" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Top ⬆ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="0" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Bottom ⬇ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="0" Y="{Binding StrokeSize}"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Right ➡ -->\n <TextBlock Foreground="{Binding StrokeColor}" \n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize}" Y="0"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <!--Left ⬅ -->\n <TextBlock Foreground="{Binding StrokeColor}"\n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"\n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n RenderTransformOrigin="0.5, 0.5"\n Text="{Binding Text}" >\n <TextBlock.RenderTransform>\n <TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="0"/>\n </TextBlock.RenderTransform>\n </TextBlock>\n <TextBlock Foreground="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Foreground}"\n FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"\n FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}" \n FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"\n Text="{Binding Text}" />\n</Grid>\n</code></pre>\n\n<p>The used converter here is a simple *(-1) on an integer, to avoid using another property.</p>\n<p>Usage :</p>\n<pre><code><local:OutlinedText Margin="WHATEVER" HorizontalAlignment="WHATEVER" VerticalAlignment="WHATEVER"\n Text="Your Text" StrokeColor="WhiteSmoke" StrokeSize="2" FontSize="20" FontWeight="Bold"\n Foreground="Magenta"/>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
| How do you apply stroke (outline around text) to a textblock in xaml in WPF? | Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including:
* all font related properties including stretch and style
* text alignment (left, right, center, justify)
* text wrapping
* text trimming
* text decorations (underline, strike through etcetera)
Here's a simple example of what can be achieved with it:
```
<local:OutlinedTextBlock FontFamily="Verdana" FontSize="20pt" FontWeight="ExtraBold" TextWrapping="Wrap" StrokeThickness="1" Stroke="{StaticResource TextStroke}" Fill="{StaticResource TextFill}">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
</local:OutlinedTextBlock>
```
Which results in:

Here's the code for the control:
```cs
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
[ContentProperty("Text")]
public class OutlinedTextBlock : FrameworkElement
{
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextInvalidated));
public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(
"TextAlignment",
typeof(TextAlignment),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(
"TextDecorations",
typeof(TextDecorationCollection),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(
"TextTrimming",
typeof(TextTrimming),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));
private FormattedText formattedText;
private Geometry textGeometry;
public OutlinedTextBlock()
{
this.TextDecorations = new TextDecorationCollection();
}
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public FontStretch FontStretch
{
get { return (FontStretch)GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); }
set { this.SetValue(TextDecorationsProperty, value); }
}
public TextTrimming TextTrimming
{
get { return (TextTrimming)GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
public TextWrapping TextWrapping
{
get { return (TextWrapping)GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
protected override void OnRender(DrawingContext drawingContext)
{
this.EnsureGeometry();
drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);
}
protected override Size MeasureOverride(Size availableSize)
{
this.EnsureFormattedText();
// constrain the formatted text according to the available size
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
// the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw
this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);
this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height);
// return the desired size
return new Size(this.formattedText.Width, this.formattedText.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
this.EnsureFormattedText();
// update the formatted text with the final size
this.formattedText.MaxTextWidth = finalSize.Width;
this.formattedText.MaxTextHeight = finalSize.Height;
// need to re-generate the geometry now that the dimensions have changed
this.textGeometry = null;
return finalSize;
}
private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.formattedText = null;
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.UpdateFormattedText();
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private void EnsureFormattedText()
{
if (this.formattedText != null || this.Text == null)
{
return;
}
this.formattedText = new FormattedText(
this.Text,
CultureInfo.CurrentUICulture,
this.FlowDirection,
new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),
this.FontSize,
Brushes.Black);
this.UpdateFormattedText();
}
private void UpdateFormattedText()
{
if (this.formattedText == null)
{
return;
}
this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;
this.formattedText.TextAlignment = this.TextAlignment;
this.formattedText.Trimming = this.TextTrimming;
this.formattedText.SetFontSize(this.FontSize);
this.formattedText.SetFontStyle(this.FontStyle);
this.formattedText.SetFontWeight(this.FontWeight);
this.formattedText.SetFontFamily(this.FontFamily);
this.formattedText.SetFontStretch(this.FontStretch);
this.formattedText.SetTextDecorations(this.TextDecorations);
}
private void EnsureGeometry()
{
if (this.textGeometry != null)
{
return;
}
this.EnsureFormattedText();
this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0));
}
}
``` |
93,653 | <p>I've got a stored procedure in my database, that looks like this</p>
<pre><code>ALTER PROCEDURE [dbo].[GetCountingAnalysisResults]
@RespondentFilters varchar
AS
BEGIN
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'''
DECLARE @SQL nvarchar(600)
SET @SQL =
'SELECT *
FROM Answer
WHERE Answer.RespondentId IN ('+@RespondentFilters+'''))
GROUP BY ChosenOptionId'
exec sp_executesql @SQL
END
</code></pre>
<p>It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me.</p>
| [
{
"answer_id": 93701,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like you don't have closing quotes around your @RespondentFilters <pre>'8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'</pre></p>\n\n<p>Since GUIDs do a string compare, that's not going to work. </p>\n\n<p>Your best bet is to use some code to split the list out into multiple values.</p>\n\n<p>Something like this:</p>\n\n<pre><code>\n-- This would be the input parameter of the stored procedure, if you want to do it that way, or a UDF\ndeclare @string varchar(500)\nset @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'\n\n\ndeclare @pos int\ndeclare @piece varchar(500)\n\n-- Need to tack a delimiter onto the end of the input string if one doesn't exist\nif right(rtrim(@string),1) ','\n set @string = @string + ','\n\nset @pos = patindex('%,%' , @string)\nwhile @pos 0\nbegin\n set @piece = left(@string, @pos - 1)\n\n -- You have a piece of data, so insert it, print it, do whatever you want to with it.\n print cast(@piece as varchar(500))\n\n set @string = stuff(@string, 1, @pos, '')\n set @pos = patindex('%,%' , @string)\nend\n</code></pre>\n\n<p>Code stolen from <a href=\"http://codebetter.com/blogs/raymond.lewallen/archive/2005/10/26/133774.aspx\" rel=\"nofollow noreferrer\">Raymond Lewallen</a></p>\n"
},
{
"answer_id": 93729,
"author": "TrevorD",
"author_id": 12492,
"author_profile": "https://Stackoverflow.com/users/12492",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need quotes inside the string too. Try:</p>\n\n<pre><code>@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'',''114c61f2-8935-4755-b4e9-4a598a51cc7f'''\n</code></pre>\n\n<p>You could also consider parsing the @RespondentFilters into a temporary table.</p>\n"
},
{
"answer_id": 93734,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>You need single quotes around each GUID in the list</p>\n\n<pre><code>@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'', ''114c61f2-8935-4755-b4e9-4a598a51cc7f'''\n</code></pre>\n"
},
{
"answer_id": 93886,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "<p>You should definitely look at splitting the list of GUIDs into a table and joining against that table. You should be able to find plenty of examples online for a table-valued function that splits an input string into a table.</p>\n\n<p>Otherwise, your stored procedure is vulnerable to SQL injection. Consider the following value for @RespondentFilters:</p>\n\n<pre><code>@RespondentFilters = '''''); SELECT * FROM User; /*'\n</code></pre>\n\n<p>Your query would be more secure parsing (i.e. validating) the parameter values and joining:</p>\n\n<pre><code>SELECT *\nFROM Answer\nWHERE Answer.RespondentId IN (SELECT [Item] FROM dbo.ParseList(@RespondentFilters))\nGROUP BY ChosenOptionId\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT *\nFROM Answer\nINNER JOIN dbo.ParseList(@RespondentFilters) Filter ON Filter.Item = Answer.RespondentId\nGROUP BY ChosenOptionId\n</code></pre>\n\n<p>It's slightly more efficient as well, since you aren't dealing with dynamic SQL (sp_executesql will cache query plans, but I'm not sure if it will accurately identify your query as a <em>parameterized</em> query since it has a variable list of items in the IN clause).</p>\n"
},
{
"answer_id": 108040,
"author": "Kociub",
"author_id": 16003,
"author_profile": "https://Stackoverflow.com/users/16003",
"pm_score": 0,
"selected": false,
"text": "<p>Tank you all for your ansewers. They all helped a lot. I've dealt with the problem by writing a split function, and it works fine. It's a litte bit overhead from what I could have done, but you know, the deadline is hiding around the corner :)</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16003/"
]
| I've got a stored procedure in my database, that looks like this
```
ALTER PROCEDURE [dbo].[GetCountingAnalysisResults]
@RespondentFilters varchar
AS
BEGIN
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'''
DECLARE @SQL nvarchar(600)
SET @SQL =
'SELECT *
FROM Answer
WHERE Answer.RespondentId IN ('+@RespondentFilters+'''))
GROUP BY ChosenOptionId'
exec sp_executesql @SQL
END
```
It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me. | You need single quotes around each GUID in the list
```
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'', ''114c61f2-8935-4755-b4e9-4a598a51cc7f'''
``` |
93,672 | <p>Is there a 7-Zip command-line switch that prevents the filenames from echoing to the screen as they are added to the archive?</p>
| [
{
"answer_id": 93702,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>If it doesn't have one, you can still redirect the output using <code>></code> into a file, then deleting the file afterwards. If you are on *nix, you can redirect into <code>/dev/null</code>.</p>\n<h2>Edit</h2>\n<p>In MS-DOS and <code>cmd.exe</code> you can redirect into NUL, instead of a file. Thanks to <a href=\"https://stackoverflow.com/users/6069/agnul\">agnul</a> for this hint.</p>\n"
},
{
"answer_id": 93714,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 3,
"selected": false,
"text": "<p>Not built in, but if you add </p>\n\n<pre><code><7z command here> 2>&1 NUL\n</code></pre>\n\n<p>to the end of your command-line, it will redirect all the output into the null device and stops it echoing to the screen. This is the MS-DOS equivalent of</p>\n\n<pre><code>2>&1 /dev/null\n</code></pre>\n\n<p>in Linux and Unix systems.</p>\n"
},
{
"answer_id": 93719,
"author": "Dario Solera",
"author_id": 16026,
"author_profile": "https://Stackoverflow.com/users/16026",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, there is not a switch for that, but you could hide the output redirecting it to a file, for example (DOS batch):</p>\n\n<pre><code>7z.exe ... normal parameters > DumpFile.txt\n</code></pre>\n\n<p>This way all the output ends in DumpFile.txt and not on the screen.</p>\n"
},
{
"answer_id": 5734620,
"author": "Karl Glennon",
"author_id": 23393,
"author_profile": "https://Stackoverflow.com/users/23393",
"pm_score": 2,
"selected": false,
"text": "<p>7-Zip has no switch for this. If you are using PowerShell to call 7-Zip, you can redirect the output to null using <code>Out-Null</code>. For example,</p>\n\n<pre><code>C:\\PS>my-create-7zip-function | out-null\n</code></pre>\n"
},
{
"answer_id": 12208911,
"author": "Bruno Dermario",
"author_id": 1080818,
"author_profile": "https://Stackoverflow.com/users/1080818",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid file names echoing on the screen and display only the confirmations, do:</p>\n\n<pre><code>...\\right_path\\7z a output.zip folder_to_be_compressed | findstr /b /r /c:\"\\<Everything is Ok\" /c:\"\\<Scanning\" /c:\"\\<Creating archive\"\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7519/"
]
| Is there a 7-Zip command-line switch that prevents the filenames from echoing to the screen as they are added to the archive? | Not built in, but if you add
```
<7z command here> 2>&1 NUL
```
to the end of your command-line, it will redirect all the output into the null device and stops it echoing to the screen. This is the MS-DOS equivalent of
```
2>&1 /dev/null
```
in Linux and Unix systems. |
93,695 | <p>My users would like to be able to hit <kbd>Ctrl</kbd>+<kbd>S</kbd> to save a form. Is there a good cross-browser way of capturing the <kbd>Ctrl</kbd>+<kbd>S</kbd> key combination and submit my form?</p>
<p>App is built on Drupal, so jQuery is available.</p>
| [
{
"answer_id": 93836,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 8,
"selected": true,
"text": "<pre><code>$(window).keypress(function(event) {\n if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;\n alert(\"Ctrl-S pressed\");\n event.preventDefault();\n return false;\n});\n</code></pre>\n\n<p>Key codes can differ between browsers, so you may need to check for more than just 115.</p>\n"
},
{
"answer_id": 93926,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 5,
"selected": false,
"text": "<p>You could use a <a href=\"http://www.openjs.com/scripts/events/keyboard_shortcuts/#\" rel=\"nofollow noreferrer\">shortcut library</a> to handle the browser specific stuff.</p>\n\n<pre><code>shortcut.add(\"Ctrl+S\",function() {\n alert(\"Hi there!\");\n});\n</code></pre>\n"
},
{
"answer_id": 94742,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 3,
"selected": false,
"text": "<p>I would like Web applications to not override my default shortcut keys, honestly. <kbd>Ctrl</kbd>+<kbd>S</kbd> already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack <kbd>Ctrl</kbd>+<kbd>Tab</kbd> because it looked the same as <kbd>Ctrl</kbd>+<kbd>I</kbd>, both ruining my work on the site and preventing me from switching tabs as usual.</p>\n\n<p>If you want shortcut keys, use the <code>accesskey</code> attribute. Please don't break existing browser functionality.</p>\n"
},
{
"answer_id": 266033,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": false,
"text": "<p>@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis. </p>\n\n<p>Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets <kbd>Ctrl</kbd>+<kbd>Del</kbd> as \"Blockquote\" rather than \"delete word forward\". I'm curious if there's a standard list somewhere of \"browser-safe\" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.</p>\n"
},
{
"answer_id": 973641,
"author": "misteraidan",
"author_id": 24406,
"author_profile": "https://Stackoverflow.com/users/24406",
"pm_score": 1,
"selected": false,
"text": "<p>I like <a href=\"http://code.google.com/p/js-hotkeys/\" rel=\"nofollow noreferrer\">this little plugin</a>. It needs a bit more cross browser friendliness though.</p>\n"
},
{
"answer_id": 3366290,
"author": "André",
"author_id": 406103,
"author_profile": "https://Stackoverflow.com/users/406103",
"pm_score": 0,
"selected": false,
"text": "<p>example:</p>\n\n<pre><code>shortcut.add(\"Ctrl+c\",function() {\n alert('Ok...');\n}\n,{\n 'type':'keydown',\n 'propagate':false,\n 'target':document\n});\n</code></pre>\n\n<p>usage</p>\n\n<pre><code><script type=\"text/javascript\" src=\"js/shortcut.js\"></script>\n</code></pre>\n\n<p>link for download: <a href=\"http://www.openjs.com/scripts/events/keyboard_shortcuts/#\" rel=\"nofollow noreferrer\">http://www.openjs.com/scripts/events/keyboard_shortcuts/#</a></p>\n"
},
{
"answer_id": 8760097,
"author": "pelms",
"author_id": 388902,
"author_profile": "https://Stackoverflow.com/users/388902",
"pm_score": 0,
"selected": false,
"text": "<p>This should work (adapted from <a href=\"https://stackoverflow.com/a/8285722/388902\">https://stackoverflow.com/a/8285722/388902</a>).</p>\n\n<pre><code>var ctrl_down = false;\nvar ctrl_key = 17;\nvar s_key = 83;\n\n$(document).keydown(function(e) {\n if (e.keyCode == ctrl_key) ctrl_down = true;\n}).keyup(function(e) {\n if (e.keyCode == ctrl_key) ctrl_down = false;\n});\n\n$(document).keydown(function(e) {\n if (ctrl_down && (e.keyCode == s_key)) {\n alert('Ctrl-s pressed');\n // Your code\n return false;\n }\n}); \n</code></pre>\n"
},
{
"answer_id": 10273585,
"author": "Eran Medan",
"author_id": 239168,
"author_profile": "https://Stackoverflow.com/users/239168",
"pm_score": 5,
"selected": false,
"text": "<p>This one worked for me on Chrome... \nfor some reason <code>event.which</code> returns a capital S (83) for me, not sure why (regardless of the caps lock state) so I used <code>fromCharCode</code> and <code>toLowerCase</code> just to be on the safe side</p>\n\n<pre><code>$(document).keydown(function(event) {\n\n //19 for Mac Command+S\n if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;\n\n alert(\"Ctrl-s pressed\");\n\n event.preventDefault();\n return false;\n});\n</code></pre>\n\n<p>If anyone knows why I get <strong>83</strong> and not <strong>115</strong>, I will be happy to hear, also if anyone tests this on other browsers I'll be happy to hear if it works or not</p>\n"
},
{
"answer_id": 14180949,
"author": "Danny Ruijters",
"author_id": 1584657,
"author_profile": "https://Stackoverflow.com/users/1584657",
"pm_score": 8,
"selected": false,
"text": "<p>This works for me (using jquery) to overload <kbd>Ctrl</kbd>+<kbd>S</kbd>, <kbd>Ctrl</kbd>+<kbd>F</kbd> and <kbd>Ctrl</kbd>+<kbd>G</kbd>:</p>\n\n<pre><code>$(window).bind('keydown', function(event) {\n if (event.ctrlKey || event.metaKey) {\n switch (String.fromCharCode(event.which).toLowerCase()) {\n case 's':\n event.preventDefault();\n alert('ctrl-s');\n break;\n case 'f':\n event.preventDefault();\n alert('ctrl-f');\n break;\n case 'g':\n event.preventDefault();\n alert('ctrl-g');\n break;\n }\n }\n});\n</code></pre>\n"
},
{
"answer_id": 14385600,
"author": "Alan Bellows",
"author_id": 1154998,
"author_profile": "https://Stackoverflow.com/users/1154998",
"pm_score": 5,
"selected": false,
"text": "<p>This jQuery solution works for me in Chrome and Firefox, for both <kbd>Ctrl</kbd>+<kbd>S</kbd> and <kbd>Cmd</kbd>+<kbd>S</kbd>.</p>\n\n<pre><code>$(document).keydown(function(e) {\n\n var key = undefined;\n var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];\n\n while (key === undefined && possible.length > 0)\n {\n key = possible.pop();\n }\n\n if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))\n {\n e.preventDefault();\n alert(\"Ctrl-s pressed\");\n return false;\n }\n return true;\n}); \n</code></pre>\n"
},
{
"answer_id": 15529207,
"author": "uadrive",
"author_id": 947898,
"author_profile": "https://Stackoverflow.com/users/947898",
"pm_score": 3,
"selected": false,
"text": "<p>I combined a few options to support FireFox, IE and Chrome. I've also updated it to better support mac</p>\n\n<pre><code>// simply disables save event for chrome\n$(window).keypress(function (event) {\n if (!(event.which == 115 && (navigator.platform.match(\"Mac\") ? event.metaKey : event.ctrlKey)) && !(event.which == 19)) return true;\n event.preventDefault();\n return false;\n});\n\n// used to process the cmd+s and ctrl+s events\n$(document).keydown(function (event) {\n if (event.which == 83 && (navigator.platform.match(\"Mac\") ? event.metaKey : event.ctrlKey)) {\n event.preventDefault();\n save(event);\n return false;\n }\n});\n</code></pre>\n"
},
{
"answer_id": 31150541,
"author": "user2570311",
"author_id": 2570311,
"author_profile": "https://Stackoverflow.com/users/2570311",
"pm_score": 0,
"selected": false,
"text": "<p>I solved my problem on <strong>IE</strong>, using an <code>alert(\"With a message\")</code> to prevent default Behavior:</p>\n\n<pre><code>window.addEventListener(\"keydown\", function (e) {\n if(e.ctrlKey || e.metaKey){\n e.preventDefault(); //Good browsers\n if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie\n alert(\"Please, use the print button located on the top bar\");\n return;\n }\n }\n});\n</code></pre>\n"
},
{
"answer_id": 40395848,
"author": "Jaś Fasola",
"author_id": 5682470,
"author_profile": "https://Stackoverflow.com/users/5682470",
"pm_score": 1,
"selected": false,
"text": "<p>To Alan Bellows answer: !(e.altKey) added for users who use <kbd>AltGr</kbd> when typing (e.g Poland). Without this pressing <kbd>AltGr</kbd>+<kbd>S</kbd> will give same result as <kbd>Ctrl</kbd>+<kbd>S</kbd></p>\n\n<pre><code>$(document).keydown(function(e) {\nif ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))\n{\n e.preventDefault();\n alert(\"Ctrl-s pressed\");\n return false;\n}\nreturn true; });\n</code></pre>\n"
},
{
"answer_id": 43966196,
"author": "Cannicide",
"author_id": 6901876,
"author_profile": "https://Stackoverflow.com/users/6901876",
"pm_score": 3,
"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>$(document).keydown(function(e) {\r\n if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))\r\n {\r\n e.preventDefault();\r\n alert(\"Ctrl-s pressed\");\r\n return false;\r\n }\r\n return true;\r\n}); </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\nTry pressing ctrl+s somewhere.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This is an up-to-date version of @AlanBellows's answer, replacing <code>which</code> with <code>key</code>. It also works even with Chrome's capital key glitch (where if you press <kbd>Ctrl</kbd>+<kbd>S</kbd> it sends capital S instead of s). Works in all modern browsers.</p>\n"
},
{
"answer_id": 44973660,
"author": "10011101111",
"author_id": 5845598,
"author_profile": "https://Stackoverflow.com/users/5845598",
"pm_score": 0,
"selected": false,
"text": "<p>This Plugin Made by me may be helpful.</p>\n\n<p><a href=\"https://codepen.io/dhruvsinghal/pen/ZyjMJQ?editors=0011\" rel=\"nofollow noreferrer\">Plugin</a></p>\n\n<p>You can use this plugin you have to supply the key Codes and function to be run like this</p>\n\n<pre><code>simulatorControl([17,83], function(){\n console.log('You have pressed Ctrl+Z');\n});\n</code></pre>\n\n<p>In the code i have displayed how to perform for <kbd>Ctrl</kbd>+<kbd>S</kbd>. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.</p>\n"
},
{
"answer_id": 49258098,
"author": "R. Salisbury",
"author_id": 4230970,
"author_profile": "https://Stackoverflow.com/users/4230970",
"pm_score": 0,
"selected": false,
"text": "<p>This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:</p>\n<pre><code>$(window).keydown(function(evt) {\n var key = String.fromCharCode(evt.keyCode).toLowerCase();\n switch(key) {\n case "s":\n if(evt.ctrlKey || evt.metaKey) {\n fnToRun();\n evt.preventDefault(true);\n return false;\n }\n break;\n }\n return true;\n});\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902010/"
]
| My users would like to be able to hit `Ctrl`+`S` to save a form. Is there a good cross-browser way of capturing the `Ctrl`+`S` key combination and submit my form?
App is built on Drupal, so jQuery is available. | ```
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
```
Key codes can differ between browsers, so you may need to check for more than just 115. |
93,716 | <p>How can I hide the title bar from a Windows Form but still have a Resizing Frame?</p>
| [
{
"answer_id": 93721,
"author": "Brian Gillespie",
"author_id": 6151,
"author_profile": "https://Stackoverflow.com/users/6151",
"pm_score": 5,
"selected": true,
"text": "<p>Setting FormBorderStyle = None will remove the title bar (at both design and\nrun time) - and also remove your ability to resize the form.</p>\n\n<p>If you need a border you can set:</p>\n\n<pre><code>ControlBox = false\nText = \"\"\n</code></pre>\n"
},
{
"answer_id": 94532,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 2,
"selected": false,
"text": "<p>Set the ControlBox property of the form to False, and the Text property to empty string. The form will open with no perceivable (to the user) title bar, but they will be able to resize the form.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6151/"
]
| How can I hide the title bar from a Windows Form but still have a Resizing Frame? | Setting FormBorderStyle = None will remove the title bar (at both design and
run time) - and also remove your ability to resize the form.
If you need a border you can set:
```
ControlBox = false
Text = ""
``` |
93,720 | <p><strong>How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class?</strong></p>
<p>E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo.</p>
<p>If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense).</p>
| [
{
"answer_id": 93721,
"author": "Brian Gillespie",
"author_id": 6151,
"author_profile": "https://Stackoverflow.com/users/6151",
"pm_score": 5,
"selected": true,
"text": "<p>Setting FormBorderStyle = None will remove the title bar (at both design and\nrun time) - and also remove your ability to resize the form.</p>\n\n<p>If you need a border you can set:</p>\n\n<pre><code>ControlBox = false\nText = \"\"\n</code></pre>\n"
},
{
"answer_id": 94532,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 2,
"selected": false,
"text": "<p>Set the ControlBox property of the form to False, and the Text property to empty string. The form will open with no perceivable (to the user) title bar, but they will be able to resize the form.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16399/"
]
| **How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class?**
E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo.
If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense). | Setting FormBorderStyle = None will remove the title bar (at both design and
run time) - and also remove your ability to resize the form.
If you need a border you can set:
```
ControlBox = false
Text = ""
``` |
93,728 | <p>I want to do the following imports in a class.</p>
<pre><code>import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.TextEdit;
</code></pre>
<p>How can I import the JDT within Eclipse?
Cheers.</p>
| [
{
"answer_id": 93820,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 2,
"selected": false,
"text": "<p>Unless I'm misunderstanding you, you just need to include the JDT JAR files on your classpath; they're all available in your Eclipse plugins directory. So for your project, right-click on the project's name in the Package Explorer, go to the Build Path... submenu, and choose Configure Build Path. Then in the Libraries tab, use the \"Add External JARs\" button to add each of the relevant JAR files from the Eclipse plugins directory.</p>\n"
},
{
"answer_id": 95354,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 4,
"selected": false,
"text": "<p>I think I found an easier way to do this:</p>\n\n<ul>\n<li>right-click on your project in the Package Explorer;</li>\n<li>choose \"Build Path...\";</li>\n<li>choose \"Configure Build Path\";</li>\n<li>choose the Libraries tab;</li>\n<li>click the \"Add Variable...\" button;</li>\n<li>in the list box, choose the \"ECLIPSE_HOME\" entry, and then click the \"Extend\" button;</li>\n<li>in the list box, open up the \"plugins\" folder entry, scroll way down, and shift-click all the org.eclipse.jdt.* JAR files that are in the file listing <em>beneath</em> the folders;</li>\n<li>click OK until you're all the way back out.</li>\n</ul>\n\n<p>That should do it.</p>\n"
},
{
"answer_id": 96204,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 1,
"selected": false,
"text": "<p>If you need these classes, you are probably in a plug-in project already. You should be able to import these classes by applying the quick fix \"Fix project setup...\" (Ctrl+1) on the line where Eclipse is complaining about the imports. That will add the required plug-ins to your MANIFEST.MF file in the META-INF directory (org.eclipse.jdt.core and org.eclipse.jface.text in your case). You can also add them manually in your MANIFEST.MF file. If your project is no plug-in project (and you have no MANIFEST.MF file) you can convert it by right-click on the project -> PDE Tools -> Convert Projects to Plug-in Project first. If you add dependencies to plug-in projects in the normal way (\"configure build path\") the classloading won't work properly at runtime (though it will compile).</p>\n"
},
{
"answer_id": 454386,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 2,
"selected": false,
"text": "<p>If your'e writing plugins for Eclipse, you shouldn't really be trying to instantiate the <code>internal</code> packages. According to this <a href=\"http://www.eclipse.org/articles/article.php?file=Article-API-Use/index.html\" rel=\"nofollow noreferrer\">API Rules of Engagement</a></p>\n\n<blockquote>\n <p>Stick to officially documented APIs. Only reference packages that are documented in the published API Javadoc for the component. Never reference a package belonging to another component that has \"internal\" in its name---these are never API. Never reference a package for which there is no published API Javadoc---these are not API either.</p>\n</blockquote>\n\n<p>For the others, add the package name to the <code>Import-Package</code> entry in your manifest. </p>\n\n<p>There are extension points into the JDT, but if what you want to do falls outside of these, then I'm afraid you're out of luck.</p>\n\n<p>If you're just looking to use a compiler in your code, without relying on the JDK (i.e. on a JRE), then I would consider shipping with a more standalone Java based Java compiler like <a href=\"http://www.janino.net/\" rel=\"nofollow noreferrer\">Janino</a>.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5915/"
]
| I want to do the following imports in a class.
```
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.TextEdit;
```
How can I import the JDT within Eclipse?
Cheers. | I think I found an easier way to do this:
* right-click on your project in the Package Explorer;
* choose "Build Path...";
* choose "Configure Build Path";
* choose the Libraries tab;
* click the "Add Variable..." button;
* in the list box, choose the "ECLIPSE\_HOME" entry, and then click the "Extend" button;
* in the list box, open up the "plugins" folder entry, scroll way down, and shift-click all the org.eclipse.jdt.\* JAR files that are in the file listing *beneath* the folders;
* click OK until you're all the way back out.
That should do it. |
93,744 | <p>For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.</p>
<p>For example: </p>
<pre><code>flags = flags | FlagsEnum.Bit4; // Set bit 4.
</code></pre>
<p>or</p>
<pre><code>if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?
</code></pre>
<p>Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?</p>
| [
{
"answer_id": 93780,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 1,
"selected": false,
"text": "<p>C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.</p>\n\n<p>So, to test for a bit being set in a flag, you would use:\n if (flags & 8) //tests bit 4 has been set</p>\n"
},
{
"answer_id": 93785,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 7,
"selected": false,
"text": "<p>The idiom is to use the bitwise or-equal operator to set bits:</p>\n\n<pre><code>flags |= 0x04;\n</code></pre>\n\n<p>To clear a bit, the idiom is to use bitwise and with negation:</p>\n\n<pre><code>flags &= ~0x04;\n</code></pre>\n\n<p>Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:</p>\n\n<pre><code>flags |= 1 << offset;\nflags &= ~(1 << offset);\n</code></pre>\n"
},
{
"answer_id": 93872,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 3,
"selected": false,
"text": "<p>C++ syntax, assuming bit 0 is LSB, assuming flags is unsigned long:</p>\n\n<p>Check if Set:</p>\n\n<pre><code>flags & (1UL << (bit to test# - 1))\n</code></pre>\n\n<p>Check if not set:</p>\n\n<pre><code>invert test !(flag & (...))\n</code></pre>\n\n<p>Set:</p>\n\n<pre><code>flag |= (1UL << (bit to set# - 1))\n</code></pre>\n\n<p>Clear:</p>\n\n<pre><code>flag &= ~(1UL << (bit to clear# - 1))\n</code></pre>\n\n<p>Toggle:</p>\n\n<pre><code>flag ^= (1UL << (bit to set# - 1))\n</code></pre>\n"
},
{
"answer_id": 93893,
"author": "Nashirak",
"author_id": 15484,
"author_profile": "https://Stackoverflow.com/users/15484",
"pm_score": 2,
"selected": false,
"text": "<p>To test a bit you would do the following:\n(assuming flags is a 32 bit number)</p>\n\n<p>Test Bit: \n <pre><code>if((flags & 0x08) == 0x08)</code></pre> (If bit 4 is set then its true)\nToggle Back (1 - 0 or 0 - 1): <pre><code>flags = flags ^ 0x08;</code></pre>\nReset Bit 4 to Zero: <pre><code>flags = flags & 0xFFFFFF7F;</code></pre></p>\n"
},
{
"answer_id": 417217,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 8,
"selected": false,
"text": "<p><strong>I did some more work on these extensions - <a href=\"http://hugoware.net:4000/blog/enumeration-extensions-2-0\" rel=\"noreferrer\" >You can find the code here</a> </strong></p>\n<p>I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... <em>Comments removed...</em></p>\n<pre><code>namespace Enum.Extensions {\n\n public static class EnumerationExtensions {\n\n public static bool Has<T>(this System.Enum type, T value) {\n try {\n return (((int)(object)type & (int)(object)value) == (int)(object)value);\n } \n catch {\n return false;\n }\n }\n\n public static bool Is<T>(this System.Enum type, T value) {\n try {\n return (int)(object)type == (int)(object)value;\n }\n catch {\n return false;\n } \n }\n\n\n public static T Add<T>(this System.Enum type, T value) {\n try {\n return (T)(object)(((int)(object)type | (int)(object)value));\n }\n catch(Exception ex) {\n throw new ArgumentException(\n string.Format(\n "Could not append value from enumerated type '{0}'.",\n typeof(T).Name\n ), ex);\n } \n }\n\n\n public static T Remove<T>(this System.Enum type, T value) {\n try {\n return (T)(object)(((int)(object)type & ~(int)(object)value));\n }\n catch (Exception ex) {\n throw new ArgumentException(\n string.Format(\n "Could not remove value from enumerated type '{0}'.",\n typeof(T).Name\n ), ex);\n } \n }\n\n }\n}\n</code></pre>\n<p>Then they are used like the following</p>\n<pre><code>SomeType value = SomeType.Grapes;\nbool isGrapes = value.Is(SomeType.Grapes); //true\nbool hasGrapes = value.Has(SomeType.Grapes); //true\n\nvalue = value.Add(SomeType.Oranges);\nvalue = value.Add(SomeType.Apples);\nvalue = value.Remove(SomeType.Grapes);\n\nbool hasOranges = value.Has(SomeType.Oranges); //true\nbool isApples = value.Is(SomeType.Apples); //false\nbool hasGrapes = value.Has(SomeType.Grapes); //false\n</code></pre>\n"
},
{
"answer_id": 6179308,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 7,
"selected": false,
"text": "<p>In .NET 4 you can now write:</p>\n\n<pre><code>flags.HasFlag(FlagsEnum.Bit4)\n</code></pre>\n"
},
{
"answer_id": 7181407,
"author": "Chuck Dee",
"author_id": 275594,
"author_profile": "https://Stackoverflow.com/users/275594",
"pm_score": 5,
"selected": false,
"text": "<p>@Drew</p>\n\n<p>Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:</p>\n\n<pre><code>[Flags]\npublic enum TestFlags\n{\n One = 1,\n Two = 2,\n Three = 4,\n Four = 8,\n Five = 16,\n Six = 32,\n Seven = 64,\n Eight = 128,\n Nine = 256,\n Ten = 512\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n TestFlags f = TestFlags.Five; /* or any other enum */\n bool result = false;\n\n Stopwatch s = Stopwatch.StartNew();\n for (int i = 0; i < 10000000; i++)\n {\n result |= f.HasFlag(TestFlags.Three);\n }\n s.Stop();\n Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*\n\n s.Restart();\n for (int i = 0; i < 10000000; i++)\n {\n result |= (f & TestFlags.Three) != 0;\n }\n s.Stop();\n Console.WriteLine(s.ElapsedMilliseconds); // *27 ms* \n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.</p>\n"
},
{
"answer_id": 9641681,
"author": "Tony Tanzillo",
"author_id": 1173769,
"author_profile": "https://Stackoverflow.com/users/1173769",
"pm_score": 2,
"selected": false,
"text": "<p>This was inspired by using Sets as indexers in Delphi, way back when:</p>\n\n<pre><code>/// Example of using a Boolean indexed property\n/// to manipulate a [Flags] enum:\n\npublic class BindingFlagsIndexer\n{\n BindingFlags flags = BindingFlags.Default;\n\n public BindingFlagsIndexer()\n {\n }\n\n public BindingFlagsIndexer( BindingFlags value )\n {\n this.flags = value;\n }\n\n public bool this[BindingFlags index]\n {\n get\n {\n return (this.flags & index) == index;\n }\n set( bool value )\n {\n if( value )\n this.flags |= index;\n else\n this.flags &= ~index;\n }\n }\n\n public BindingFlags Value \n {\n get\n { \n return flags;\n } \n set( BindingFlags value ) \n {\n this.flags = value;\n }\n }\n\n public static implicit operator BindingFlags( BindingFlagsIndexer src )\n {\n return src != null ? src.Value : BindingFlags.Default;\n }\n\n public static implicit operator BindingFlagsIndexer( BindingFlags src )\n {\n return new BindingFlagsIndexer( src );\n }\n\n}\n\npublic static class Class1\n{\n public static void Example()\n {\n BindingFlagsIndexer myFlags = new BindingFlagsIndexer();\n\n // Sets the flag(s) passed as the indexer:\n\n myFlags[BindingFlags.ExactBinding] = true;\n\n // Indexer can specify multiple flags at once:\n\n myFlags[BindingFlags.Instance | BindingFlags.Static] = true;\n\n // Get boolean indicating if specified flag(s) are set:\n\n bool flatten = myFlags[BindingFlags.FlattenHierarchy];\n\n // use | to test if multiple flags are set:\n\n bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 44551135,
"author": "TylerBrinkley",
"author_id": 8137269,
"author_profile": "https://Stackoverflow.com/users/8137269",
"pm_score": 4,
"selected": false,
"text": "<p>.NET's built-in flag enum operations are unfortunately quite limited. Most of the time users are left with figuring out the bitwise operation logic.</p>\n\n<p>In .NET 4, the method <code>HasFlag</code> was added to <code>Enum</code> which helps simplify user's code but unfortunately there are many problems with it.</p>\n\n<ol>\n<li><code>HasFlag</code> is not type-safe as it accepts any type of enum value argument, not just the given enum type.</li>\n<li><code>HasFlag</code> is ambiguous as to whether it checks if the value has all or any of the flags provided by the enum value argument. It's all by the way.</li>\n<li><code>HasFlag</code> is rather slow as it requires boxing which causes allocations and thus more garbage collections.</li>\n</ol>\n\n<p>Due in part to .NET's limited support for flag enums I wrote the OSS library <a href=\"https://github.com/TylerBrinkley/Enums.NET\" rel=\"noreferrer\" title=\"Enums.NET\">Enums.NET</a> which addresses each of these issues and makes dealing with flag enums much easier.</p>\n\n<p>Below are some of the operations it provides along with their equivalent implementations using just the .NET framework.</p>\n\n<h1>Combine Flags</h1>\n\n<p><b>.NET</b> <code>flags | otherFlags</code></p>\n\n<p><b>Enums.NET</b> <code>flags.CombineFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Remove Flags</h1>\n\n<p><b>.NET</b> <code>flags & ~otherFlags</code></p>\n\n<p><b>Enums.NET</b> <code>flags.RemoveFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Common Flags</h1>\n\n<p><b>.NET</b> <code>flags & otherFlags</code></p>\n\n<p><b>Enums.NET</b> <code>flags.CommonFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Toggle Flags</h1>\n\n<p><b>.NET</b> <code>flags ^ otherFlags</code></p>\n\n<p><b>Enums.NET</b> <code>flags.ToggleFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Has All Flags</h1>\n\n<p><b>.NET</b> <code>(flags & otherFlags) == otherFlags</code> or <code>flags.HasFlag(otherFlags)</code></p>\n\n<p><b>Enums.NET</b> <code>flags.HasAllFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Has Any Flags</h1>\n\n<p><b>.NET</b> <code>(flags & otherFlags) != 0</code></p>\n\n<p><b>Enums.NET</b> <code>flags.HasAnyFlags(otherFlags)</code></p>\n\n<hr>\n\n<h1>Get Flags</h1>\n\n<p><b>.NET</b></p>\n\n<pre><code>Enumerable.Range(0, 64)\n .Where(bit => ((flags.GetTypeCode() == TypeCode.UInt64 ? (long)(ulong)flags : Convert.ToInt64(flags)) & (1L << bit)) != 0)\n .Select(bit => Enum.ToObject(flags.GetType(), 1L << bit))`\n</code></pre>\n\n<p><b>Enums.NET</b> <code>flags.GetFlags()</code></p>\n\n<hr>\n\n<p>I'm trying to get these improvements incorporated into .NET Core and maybe eventually the full .NET Framework. You can check out my proposal <a href=\"https://github.com/dotnet/corefx/issues/15453\" rel=\"noreferrer\" title=\"GitHub/corefx#15453\">here</a>.</p>\n"
},
{
"answer_id": 54973342,
"author": "Mark Bamford",
"author_id": 9004349,
"author_profile": "https://Stackoverflow.com/users/9004349",
"pm_score": 3,
"selected": false,
"text": "<p>For the best performance and zero garbage, use this:</p>\n\n<pre><code>using System;\nusing T = MyNamespace.MyFlags;\n\nnamespace MyNamespace\n{\n [Flags]\n public enum MyFlags\n {\n None = 0,\n Flag1 = 1,\n Flag2 = 2\n }\n\n static class MyFlagsEx\n {\n public static bool Has(this T type, T value)\n {\n return (type & value) == value;\n }\n\n public static bool Is(this T type, T value)\n {\n return type == value;\n }\n\n public static T Add(this T type, T value)\n {\n return type | value;\n }\n\n public static T Remove(this T type, T value)\n {\n return type & ~value;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68399061,
"author": "Connor Low",
"author_id": 6789816,
"author_profile": "https://Stackoverflow.com/users/6789816",
"pm_score": 2,
"selected": false,
"text": "<h1>Bitwise (<code>Flags</code>) enum guide</h1>\n<p>Old, but wanted to take a stab at a cheat sheet, even if for my own reference:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Operation</th>\n<th>Syntax</th>\n<th>Example</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>On</strong></td>\n<td><code>|=</code></td>\n<td><code>e |= E.A</code></td>\n</tr>\n<tr>\n<td><strong>Off</strong></td>\n<td><code>&=</code> + <code>~</code></td>\n<td><code>e &= ~E.A</code></td>\n</tr>\n<tr>\n<td><strong>Toggle</strong></td>\n<td><code>^=</code></td>\n<td><code>e ^= E.A</code></td>\n</tr>\n<tr>\n<td><strong>Test</strong> (.NET API)</td>\n<td><code>.HasFlag</code></td>\n<td><code>e.HasFlag(E.A)</code></td>\n</tr>\n<tr>\n<td><strong>Test</strong> (bitwise)</td>\n<td>(see example)</td>\n<td><code>(e & E.A) == E.A</code></td>\n</tr>\n</tbody>\n</table>\n</div><h3>Examples</h3>\n<pre class=\"lang-c# prettyprint-override\"><code>[Flags]\nenum E {\n A = 0b1,\n B = 0b10,\n C = 0b100\n}\n\nE e = E.A; // Assign (e = A)\ne |= E.B | E.C; // Add (e = A, B, C)\ne &= ~E.A & ~E.B; // Remove (e = C) -- alt syntax: &= ~(E.A | E.B)\ne ^= E.A | E.C; // Toggle (e = A)\ne.HasFlag(E.A); // Test (returns true)\n\n// Testing multiple flags using bit operations:\nbool hasAandB = ( e & (E.A | E.B) ) == (E.A | E.B);\n</code></pre>\n<h3>Bonus: defining a <code>Flags</code> enum</h3>\n<p>Typically, we use integers like so:</p>\n<pre><code>[Flags]\nenum E {\n A = 1,\n B = 2,\n C = 4,\n // etc.\n</code></pre>\n<p>But as we approach larger numbers, it's not as easy to calculate the next value:</p>\n<pre><code> // ...\n W = 4194304,\n X = 8388608,\n // ..\n</code></pre>\n<p>There are a couple of alternatives, however: binary and hexadecimal literals.</p>\n<p>For <strong>Binary</strong>, just append a <code>0</code> at the end of the previous value:</p>\n<pre><code>[Flags]\nenum E {\n A = 0b1,\n B = 0b10,\n C = 0b100,\n // ...\n W = 0b100_0000_0000_0000_0000_0000,\n X = 0b1000_0000_0000_0000_0000_0000,\n</code></pre>\n<p><strong>Hexadecimal</strong> also has a handy pattern and might look a bit less ugly: cycle through 1, 2, 4, 8, adding a zero after each complete iteration.</p>\n<pre><code>[Flags]\nenum E {\n A = 0x1,\n B = 0x2,\n C = 0x4,\n D = 0x8,\n E = 0x10, // 16\n F = 0x20, // 32, etc.\n // ...\n W = 0x400000,\n X = 0x800000,\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
]
| For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.
For example:
```
flags = flags | FlagsEnum.Bit4; // Set bit 4.
```
or
```
if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?
```
Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum? | **I did some more work on these extensions - [You can find the code here](http://hugoware.net:4000/blog/enumeration-extensions-2-0)**
I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... *Comments removed...*
```
namespace Enum.Extensions {
public static class EnumerationExtensions {
public static bool Has<T>(this System.Enum type, T value) {
try {
return (((int)(object)type & (int)(object)value) == (int)(object)value);
}
catch {
return false;
}
}
public static bool Is<T>(this System.Enum type, T value) {
try {
return (int)(object)type == (int)(object)value;
}
catch {
return false;
}
}
public static T Add<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type | (int)(object)value));
}
catch(Exception ex) {
throw new ArgumentException(
string.Format(
"Could not append value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
public static T Remove<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type & ~(int)(object)value));
}
catch (Exception ex) {
throw new ArgumentException(
string.Format(
"Could not remove value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
}
}
```
Then they are used like the following
```
SomeType value = SomeType.Grapes;
bool isGrapes = value.Is(SomeType.Grapes); //true
bool hasGrapes = value.Has(SomeType.Grapes); //true
value = value.Add(SomeType.Oranges);
value = value.Add(SomeType.Apples);
value = value.Remove(SomeType.Grapes);
bool hasOranges = value.Has(SomeType.Oranges); //true
bool isApples = value.Is(SomeType.Apples); //false
bool hasGrapes = value.Has(SomeType.Grapes); //false
``` |
93,767 | <p>I am using the mootools based Rokbox plugin, on one of my sites, and I can't figure out how to close it with javascript.</p>
<p>I triggered the click event on the close button, but that did not work.</p>
<p>I found the code in the rokbox source that is used to add the click listener</p>
<pre><code>this.closeButton.addEvent('click',function(e){new Event(e).stop();self.swtch=false;self.close(e)});
</code></pre>
<p>but since it is minified i cannot find what "this" refers to</p>
| [
{
"answer_id": 94526,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>this</code> likely refers to the rokbox instance; I don't think you need to worry about it, you're interested in the code that runs on the click event. The salient part looks to be the following:</p>\n\n<pre><code>self.swtch=false;\nself.close(e);\n</code></pre>\n\n<p><code>self</code> most likely refers to the rokbox instance, again, so assuming you instantiate it with something like </p>\n\n<pre><code>var rokbox = new RokBox(...);\n</code></pre>\n\n<p>you should be able to just call</p>\n\n<pre><code>rokbox.close(); \n</code></pre>\n\n<p>and have it close. I haven't looked at rokbox source, so no guarantees, and not quite sure what the <code>swtch=false</code> does, so you probably will need to experiment a bit.</p>\n"
},
{
"answer_id": 4003178,
"author": "yitwail",
"author_id": 471803,
"author_profile": "https://Stackoverflow.com/users/471803",
"pm_score": 0,
"selected": false,
"text": "<p>For the current rokbox and mootools 1.12, the command is</p>\n\n<pre><code>window.parent.rokbox.close(null)\n</code></pre>\n\n<p>it took forever to come up with this. By the way, this is to close the rokbox from the page that's loaded in the rokbox, by clicking a regular button instead of the 'x' for instance. Also, to add to what Aeon wrote, the rokbox is automatically created so it's unnecessary to instantiate it.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am using the mootools based Rokbox plugin, on one of my sites, and I can't figure out how to close it with javascript.
I triggered the click event on the close button, but that did not work.
I found the code in the rokbox source that is used to add the click listener
```
this.closeButton.addEvent('click',function(e){new Event(e).stop();self.swtch=false;self.close(e)});
```
but since it is minified i cannot find what "this" refers to | The `this` likely refers to the rokbox instance; I don't think you need to worry about it, you're interested in the code that runs on the click event. The salient part looks to be the following:
```
self.swtch=false;
self.close(e);
```
`self` most likely refers to the rokbox instance, again, so assuming you instantiate it with something like
```
var rokbox = new RokBox(...);
```
you should be able to just call
```
rokbox.close();
```
and have it close. I haven't looked at rokbox source, so no guarantees, and not quite sure what the `swtch=false` does, so you probably will need to experiment a bit. |
93,770 | <p>For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper. </p>
<p>I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!</p>
<p>Managed C++ wrapper code (this is in a DLL):</p>
<pre><code>extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
</code></pre>
<p>Test Code (this is an EXE):</p>
<pre><code>typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
</code></pre>
<p>For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)</p>
<p>Unfortunately, Microsoft has no information on that error.</p>
| [
{
"answer_id": 94320,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 4,
"selected": false,
"text": "<p>The first issue is to make sure the Debugger type is set to mixed. Then you get useful exceptions.</p>\n"
},
{
"answer_id": 96651,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 6,
"selected": true,
"text": "<p>The problem was where the DLLs were located.</p>\n\n<ul>\n<li>c:\\dlls\\managed.dll</li>\n<li>c:\\dlls\\wrapper.dll</li>\n<li>c:\\exe\\my.exe</li>\n</ul>\n\n<p>I confirmed this by copying managed.dll into c:\\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC).</p>\n\n<p>For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:</p>\n\n<p>AssemblyResolver.h:</p>\n\n<pre><code>/// <summary>\n/// Summary for AssemblyResolver\n/// </summary>\npublic ref class AssemblyResolver\n{\npublic:\n\nstatic Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )\n{\n Console::WriteLine( \"Resolving...\" );\n\n Assembly^ thisAssembly = Assembly::GetExecutingAssembly();\n String^ thisPath = thisAssembly->Location;\n String^ directory = Path::GetDirectoryName(thisPath);\n String^ pathToManagedAssembly = Path::Combine(directory, \"managed.dll\");\n\n Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);\n return newAssembly;\n}\n\n};\n</code></pre>\n\n<p>Wrapper.cpp:</p>\n\n<pre><code>#include \"AssemblyResolver.h\"\n\nextern \"C\" __declspec(dllexport) IMyObject* CreateMyObject(void)\n{\n try\n {\n AppDomain^ currentDomain = AppDomain::CurrentDomain;\n currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );\n\n return new CMyWrapper( );\n }\n catch(System::Exception^ e)\n {\n System::Console::WriteLine(e->Message);\n\n return NULL;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4663364,
"author": "tomanu",
"author_id": 547677,
"author_profile": "https://Stackoverflow.com/users/547677",
"pm_score": -1,
"selected": false,
"text": "<p>When you run in debugger C++ native project which use C++ managed dll you may get this exception. When VS2010 catch it and your application after some chain exceptions will be aborted you may try in exception filter (Menu|Debug|Excpetion) disable all C++ exceptions. You will still see this exception in output but your application won't abort</p>\n"
},
{
"answer_id": 17762325,
"author": "Fredrik Ullner",
"author_id": 149813,
"author_profile": "https://Stackoverflow.com/users/149813",
"pm_score": 1,
"selected": false,
"text": "<p>In case anyone else stumbles upon this question, and you are using a dynamic assembly name: make sure you are stripping the assembly name, it may contain version, culture and other content that you may not use.</p>\n\n<p>I.e., your MyResolveEventHandler should be in the form of:</p>\n\n<pre><code>static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )\n{\n Console::WriteLine( \"Resolving...\" );\n\n String^ assemblyName = args->Name;\n\n // Strip irrelevant information, such as assembly, version etc.\n // Example: \"Acme.Foobar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"\n if( assemblyName->Contains(\",\") ) \n {\n assemblyName = assemblyName->Substring(0, assemblyName->IndexOf(\",\"));\n }\n\n Assembly^ thisAssembly = Assembly::GetExecutingAssembly();\n String^ thisPath = thisAssembly->Location;\n String^ directory = Path::GetDirectoryName(thisPath);\n String^ pathToManagedAssembly = Path::Combine(directory, assemblyName );\n\n Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);\n return newAssembly;\n}\n</code></pre>\n"
},
{
"answer_id": 31723080,
"author": "A.B.",
"author_id": 4914757,
"author_profile": "https://Stackoverflow.com/users/4914757",
"pm_score": 3,
"selected": false,
"text": "<p>For you native application consuming the mixed mode dll (Your EXE), change the **\"Debugger Type\" to \"Mixed\" mode. (Go to Project Properties -> Configuration Properties -> Debugging)</p>\n\n<p>There are some other points (which might not be relevant to you) but in my experience they could cause issues.\n - On windows 8 (with tighter security) please try launching your VS as admin.\n - Make sure that for x86 configuration you are using x86 binaries.\n - Watch for StrongName verification, if your C# assemblies which you are consuming in Managed C++ as signed, please consider signing the mixed mode dll too.</p>\n\n<p>Hope this would help.</p>\n"
},
{
"answer_id": 40223503,
"author": "Gareth",
"author_id": 1271626,
"author_profile": "https://Stackoverflow.com/users/1271626",
"pm_score": 1,
"selected": false,
"text": "<p>I was getting the C++ EEFileLoadException thrown a lot by iisexpress.exe during debugging of an ASP.NET MVC application. The call stack and C++ exception itself were not terribly helpful in helping me pin down the problem.</p>\n\n<p>After looking directly at the pointer address given in the C++ exception I eventually discovered a library string which was pointing to an old version no longer in use. This in turn was due to an out-of-date entry in my web.config file:</p>\n\n<pre><code><runtime>\n<assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n<dependentAssembly>\n <assemblyIdentity name=\"Microsoft.Owin.Security.OAuth\" publicKeyToken=\"31bf3856ad364e35\" />\n <bindingRedirect oldVersion=\"0.0.0.0-3.0.1.0\" newVersion=\"3.0.1.0\" />\n </dependentAssembly> </assemblyBinding> </runtime>\n</code></pre>\n\n<p>I had upgraded various Microsoft.Own security libraries via NuGet to version 4.0.30319 but this line in the config was instructing the server to redirect calls to version 3.0.1.0, which was now no longer part of my project. Updating the config resovled my problems.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
]
| For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper.
I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!
Managed C++ wrapper code (this is in a DLL):
```
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
```
Test Code (this is an EXE):
```
typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
```
For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)
Unfortunately, Microsoft has no information on that error. | The problem was where the DLLs were located.
* c:\dlls\managed.dll
* c:\dlls\wrapper.dll
* c:\exe\my.exe
I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC).
For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:
AssemblyResolver.h:
```
/// <summary>
/// Summary for AssemblyResolver
/// </summary>
public ref class AssemblyResolver
{
public:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll");
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
};
```
Wrapper.cpp:
```
#include "AssemblyResolver.h"
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
try
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );
return new CMyWrapper( );
}
catch(System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return NULL;
}
}
``` |
93,832 | <p>What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser.</p>
| [
{
"answer_id": 93862,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start#System_Diagnostics_Process_Start_System_String_\" rel=\"nofollow noreferrer\">Process.Start method</a>.</p>\n"
},
{
"answer_id": 93866,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "<pre><code>private void launchURL_Click(object sender, System.EventArgs e){\n string targetURL = \"http://stackoverflow.com\";\n System.Diagnostics.Process.Start(targetURL);\n}\n</code></pre>\n"
},
{
"answer_id": 93870,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 0,
"selected": false,
"text": "<pre><code>System.Diagnostics.Process.Start(\"http://www.stackoverflow.com\");\n</code></pre>\n"
},
{
"answer_id": 93877,
"author": "Dario Solera",
"author_id": 16026,
"author_profile": "https://Stackoverflow.com/users/16026",
"pm_score": 4,
"selected": true,
"text": "<p>The following code surely works:</p>\n\n<pre><code>Process.Start(\"http://www.yoururl.com/Blah.aspx\");\n</code></pre>\n\n<p>It opens the default browser (technically, the default program that handles HTTP URIs).</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17891/"
]
| What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser. | The following code surely works:
```
Process.Start("http://www.yoururl.com/Blah.aspx");
```
It opens the default browser (technically, the default program that handles HTTP URIs). |
93,839 | <p>If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file?</p>
<p>This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!</p>
| [
{
"answer_id": 93889,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 4,
"selected": true,
"text": "<p>Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.</p>\n\n<p>The inner loop would look something like:</p>\n\n<p><pre><code>\nbyte[] buffer = new byte[ ( string.length + 7 ) / 8 ];\nfor ( int i = 0; i < buffer.length; ++i ) {\n byte current = 0;\n for ( int j = 7; j >= 0; --j )\n if ( string[ i * 8 + j ] == '1' )\n current |= 1 << j;\n output( current );\n}\n</pre></code></p>\n\n<p>You'll need to make some adjustments, but that's the general idea.</p>\n"
},
{
"answer_id": 93925,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming the String has a multiple of eight bits, (you can pad it otherwise), take advantage of Java's built in parsing in the Integer.valueOf method to do something like this:</p>\n\n<pre><code>String s = \"11001010001010101110101001001110\";\nbyte[] data = new byte[s.length() / 8];\nfor (int i = 0; i < data.length; i++) {\n data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2);\n}\n</code></pre>\n\n<p>Then you should be able to write the bytes to a <code>FileOutputStream</code> pretty simply.</p>\n\n<p>On the other hand, if you looking for effeciency, you should consider not using a String to store the bits to begin with, but build up the bytes directly in your compressor.</p>\n"
},
{
"answer_id": 93964,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public class BitOutputStream extends FilterOutputStream\n{\n private int buffer = 0;\n private int bitCount = 0;\n\n public BitOutputStream(OutputStream out)\n {\n super(out);\n }\n\n public void writeBits(int value, int numBits) throws IOException\n {\n while(numBits>0)\n {\n numBits--;\n int mix = ((value&1)<<bitCount++);\n buffer|=mix;\n value>>=1;\n if(bitCount==8)\n align8();\n }\n }\n\n @Override\n public void close() throws IOException\n {\n align8(); /* Flush any remaining partial bytes */\n super.close();\n }\n\n public void align8() throws IOException\n {\n if(bitCount > 0)\n {\n bitCount=0;\n write(buffer);\n buffer=0;\n }\n }\n}\n</code></pre>\n\n<p>And then...</p>\n\n<pre><code>if (nextChar == '0')\n{\n bos.writeBits(0, 1);\n}\nelse\n{\n bos.writeBits(1, 1);\n}\n</code></pre>\n"
},
{
"answer_id": 94405,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": false,
"text": "<p>If you're lucky, java.math.BigInteger may do everything for you.</p>\n\n<pre><code>String s = \"11001010001010101110101001001110\";\nbyte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();\n</code></pre>\n\n<p>This does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want but it may be simpler to modify the array afterwards than to do the character conversion yourself.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6833/"
]
| If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file?
This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks! | Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.
The inner loop would look something like:
```
byte[] buffer = new byte[ ( string.length + 7 ) / 8 ];
for ( int i = 0; i < buffer.length; ++i ) {
byte current = 0;
for ( int j = 7; j >= 0; --j )
if ( string[ i * 8 + j ] == '1' )
current |= 1 << j;
output( current );
}
```
You'll need to make some adjustments, but that's the general idea. |
93,853 | <p>I have seen this problem arise in many different circumstances and would like to get the best practices for fixing / debugging it on StackOverflow.</p>
<p>To use a real world example this occurred to me this morning:</p>
<pre><code>expected announcement.rb to define Announcement
</code></pre>
<p>The class worked fine in development, testing <em>and</em> from a production console, but failed from in a production Mongrel. Here's the class:</p>
<pre><code>class Announcement < ActiveRecord::Base
has_attachment :content_type => 'audio/mp3', :storage => :s3
end
</code></pre>
<p>The issue I would like addressed in the answers is not so much solving this specific problem, but how to properly debug to get Rails to give you a meaningful error as expected x.rb to define X.rb' is often a red herring...</p>
<p><strong>Edit (3 great responses so far, each w/ a partial solution</strong>)</p>
<p><strong>Debugging:</strong></p>
<ol>
<li><p>From Joe Van Dyk: Try accessing the model via a console on the environment / instance that is causing the error (in the case above: script/console production then type in 'Announcement'.</p></li>
<li><p>From Otto: Try setting a minimal plugin set via an initializer, eg: config.plugins = [ :exception_notification, :ssl_requirement, :all ] then re-enable one at a time.</p></li>
</ol>
<p><strong>Specific causes:</strong></p>
<ol>
<li><p>From Ian Terrell: if you're using attachment_fu make sure you have the correct image processor installed. attachment_fu will require it even if you aren't attaching an image.</p></li>
<li><p>From Otto: make sure you didn't name a model that conflicts with a built-in Rails class, eg: Request.</p></li>
<li><p>From Josh Lewis: make sure you don't have duplicated class or module names somewhere in your application (or Gem list).</p></li>
</ol>
| [
{
"answer_id": 94243,
"author": "Joe Van Dyk",
"author_id": 17076,
"author_profile": "https://Stackoverflow.com/users/17076",
"pm_score": 5,
"selected": true,
"text": "<p>That is a tricky one. </p>\n\n<p>What generally works for me is to run \"script/console production\" on the production server, and type in:</p>\n\n<p><code>Announcement</code></p>\n\n<p>That will usually give you a better error message. But you said you already tried that?</p>\n"
},
{
"answer_id": 94797,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 2,
"selected": false,
"text": "<p>I've encountered this before, and the <code>AttachmentFu</code> plugin was to blame. I believe in my case it was due to <code>AttachmentFu</code> expecting a different image processor than what was available, or non-supported versions were also installed. The problem was solved when I explicitly added <code>:with => :rmagick</code> (or similar -- I was using RMagick) to the <code>has_attachment</code> method call <em>even for non-image attachments.</em> Obviously, make sure that your production environment has all the right gems (or freeze them into your application) and supporting software (ImageMagick) installed. YMMV.</p>\n\n<p>As for not getting Rails and AttachmentFu to suck up and hide the real error -- we fixed it before figuring it out completely.</p>\n"
},
{
"answer_id": 96959,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 1,
"selected": false,
"text": "<p>You can try disabling all your plugins and add them back in one by one.</p>\n\n<p>In <code>environment.rb</code> in the Initalizer section, add a line like this one:</p>\n\n<pre><code>config.plugins = [ :exception_notification, :ssl_requirement, :all ]\n</code></pre>\n\n<p>Start with the minimum set to run your application and add them in one by one. I usually get this error when I've defined a model that happens to map to an existing filename. For example, a Request model but Rails already has a request.rb that gets loaded first. </p>\n"
},
{
"answer_id": 1198996,
"author": "Masolino",
"author_id": 464018,
"author_profile": "https://Stackoverflow.com/users/464018",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem for a while and in my case the error was always preceded from this S3 error: </p>\n\n<blockquote>\n <p>(AWS::S3::Operation Aborted) \"A\n conflicting conditional operation is\n currently in progress against this\n resource. Please try again.\"</p>\n</blockquote>\n\n<p>This problem usually occurs when creating the same bucket over and over again. (Source <a href=\"http://developer.amazonwebservices.com/connect/message.jspa?messageID=103933#103933\" rel=\"nofollow noreferrer\">AWS Developers forum</a>)</p>\n\n<p>This was due to the fact that I had used <code>attachment_fu to</code> create the bucket and I had decommented the line containing the command <code>Bucket.create(@@bucket_name)</code> in <code>lib/technoweenie/attachment_fu/backends/s3_backends.rb</code> (near to line 152).</p>\n\n<p>Once commented or deleted the command <code>Bucket.create(@@bucket_name)</code> the problem disappeared.</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 6390478,
"author": "schwabsauce",
"author_id": 101080,
"author_profile": "https://Stackoverflow.com/users/101080",
"pm_score": 0,
"selected": false,
"text": "<p>in my case, I am getting this error in the development console but I can load the class in irb</p>\n"
},
{
"answer_id": 6673342,
"author": "pix",
"author_id": 195061,
"author_profile": "https://Stackoverflow.com/users/195061",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry this isn't a definitive answer, but another approach that might work in some specific circumstance:</p>\n\n<p>I just ran in to this problem while debugging a site using Ruby 1.8.7 and Merb 1.0.15. It seemed that the class in question (let's call it SomeClass) was falling out of scope, but when some_class.rb file was automatically loaded, the other files it required (some_class/base.rb etc) were not loaded by the require mechanism. Possibly a bug in require?</p>\n\n<p>If I required some_class file earlier, such as the end of environment.rb, it seems to prevent the object falling out of scope.</p>\n"
},
{
"answer_id": 12069375,
"author": "bluehallu",
"author_id": 512907,
"author_profile": "https://Stackoverflow.com/users/512907",
"pm_score": 0,
"selected": false,
"text": "<p>I was getting this error duo to a controller definition being in a file that wasn't named as a controller. For instance, you have a Comment model and you define the controller in a comment.rb file instead of comments_controller.rb</p>\n"
},
{
"answer_id": 12118883,
"author": "Josh W Lewis",
"author_id": 1406964,
"author_profile": "https://Stackoverflow.com/users/1406964",
"pm_score": 2,
"selected": false,
"text": "<p>Since this is still the top Google result, I thought I'd share what fixed the problem for me:</p>\n\n<p>I had a module in the lib folder with the exact same name as my application. So, I had a conflict in module names, but I also had a conflict of folder names (not sure if the latter actually makes a difference though).</p>\n\n<p>So, for the OP, make sure you don't have duplicated class or module names somewhere in your application (or Gem list).</p>\n"
},
{
"answer_id": 12284833,
"author": "Gazza",
"author_id": 1452148,
"author_profile": "https://Stackoverflow.com/users/1452148",
"pm_score": 1,
"selected": false,
"text": "<p>Changing class names while using STI caused this for me:</p>\n\n<ul>\n<li>Class changed from 'EDBeneficiary' to 'EdBeneficiary'</li>\n<li>Existing records had 'EDBeneficiary' stored in the 'type' column, so when Rails tried to load them up the exception was raised.</li>\n</ul>\n\n<p>Fix: Run a migration to update values in the 'type' column to match the new class name.</p>\n"
},
{
"answer_id": 13279825,
"author": "f.cipriani",
"author_id": 599072,
"author_profile": "https://Stackoverflow.com/users/599072",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem with rails version 1.2.3. I could reproduce the problem only with mongrel, using console environment access didn't give any useful info. In my case, I solved making the RAILS_ROOT/html folder writable by mongrel and then restarting the web server, as some users reported here:</p>\n\n<p><a href=\"http://www.ruby-forum.com/topic/77708\" rel=\"nofollow\">http://www.ruby-forum.com/topic/77708</a></p>\n"
},
{
"answer_id": 13537639,
"author": "mgrant",
"author_id": 771411,
"author_profile": "https://Stackoverflow.com/users/771411",
"pm_score": 2,
"selected": false,
"text": "<p>For me, the cause was a circular dependency in my class definitions, and the problem only showed up using autotest in Rails. In my case, I didn't need the circular dependency, so I simply removed it.</p>\n"
},
{
"answer_id": 17576347,
"author": "Kevin B.",
"author_id": 2569478,
"author_profile": "https://Stackoverflow.com/users/2569478",
"pm_score": 2,
"selected": false,
"text": "<p>I just ran into this error as well.</p>\n\n<p>The short of it was that my rb file in my lib folder was not in a folder structure to match my module naming convention. This caused the ActiveSupport auto loader to use the wrong module to see if my class constant was defined.</p>\n\n<p>Specifically I had defined the following class</p>\n\n<pre><code>module Foo\n class Bar\n end\nend\n</code></pre>\n\n<p>In the root of /lib/bar.rb</p>\n\n<p>This caused the autoloader to ask module Object if Bar was defined instead of module Foo.</p>\n\n<p>Moving my rb file to /lib/foo/bar.rb fixed this problem.</p>\n"
},
{
"answer_id": 39806893,
"author": "taro-k",
"author_id": 6908617,
"author_profile": "https://Stackoverflow.com/users/6908617",
"pm_score": 0,
"selected": false,
"text": "<p>When I upgraded rails from 1.1.6 to 1.2.6 and 2.0.5 for my app, I faced this error. In short, old plugins caused this error. These plugins were already out-dated and no update anymore (even no repo!). After I removed them, the app worked on 1.2.6 and 2.0.5. But I didn't check the detail source code of the plugins.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
]
| I have seen this problem arise in many different circumstances and would like to get the best practices for fixing / debugging it on StackOverflow.
To use a real world example this occurred to me this morning:
```
expected announcement.rb to define Announcement
```
The class worked fine in development, testing *and* from a production console, but failed from in a production Mongrel. Here's the class:
```
class Announcement < ActiveRecord::Base
has_attachment :content_type => 'audio/mp3', :storage => :s3
end
```
The issue I would like addressed in the answers is not so much solving this specific problem, but how to properly debug to get Rails to give you a meaningful error as expected x.rb to define X.rb' is often a red herring...
**Edit (3 great responses so far, each w/ a partial solution**)
**Debugging:**
1. From Joe Van Dyk: Try accessing the model via a console on the environment / instance that is causing the error (in the case above: script/console production then type in 'Announcement'.
2. From Otto: Try setting a minimal plugin set via an initializer, eg: config.plugins = [ :exception\_notification, :ssl\_requirement, :all ] then re-enable one at a time.
**Specific causes:**
1. From Ian Terrell: if you're using attachment\_fu make sure you have the correct image processor installed. attachment\_fu will require it even if you aren't attaching an image.
2. From Otto: make sure you didn't name a model that conflicts with a built-in Rails class, eg: Request.
3. From Josh Lewis: make sure you don't have duplicated class or module names somewhere in your application (or Gem list). | That is a tricky one.
What generally works for me is to run "script/console production" on the production server, and type in:
`Announcement`
That will usually give you a better error message. But you said you already tried that? |
93,888 | <p>By default the session expiry seems to be 20 minutes. </p>
<p>Update: I do not want the session to expire until the browser is closed.</p>
<p>Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and <em>should</em> be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.</p>
<p>In PHP I can set session.cookie_lifetime in php.ini to zero to achieve this. </p>
| [
{
"answer_id": 93907,
"author": "Thomas Jespersen",
"author_id": 8547,
"author_profile": "https://Stackoverflow.com/users/8547",
"pm_score": 1,
"selected": false,
"text": "<p>This is default. When you have a session, it stores the session in a \"Session Cookie\", which is automatically deleted when the browser is closed.</p>\n\n<p>If you want to have the session between 2 browser session, you have to set the Cookie.Expired to a date in the feature.</p>\n\n<p>Because the session you talk about is stored by the server, and not the client you can't do what you want.</p>\n\n<p>But consider not using ASP.NET server side session, and instead only rely on cookies.</p>\n"
},
{
"answer_id": 93934,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 0,
"selected": false,
"text": "<p>There's no way to explicitly clear the session if you don't communicate in some way between the client and the server at the point of window closing, so I would expect sending a special URI request to clear the session at the point of receiving a window close message.</p>\n\n<p>My Javascript is not good enough to give you the actual instructions to do that; sorry :(</p>\n"
},
{
"answer_id": 93953,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 0,
"selected": false,
"text": "<p>You cant, as you can't control how the html client response. </p>\n\n<p>Actually why you need to do so? As long as no one can pick up the session to use again, it would expire after that 20 minutes. If resources does matter, set a more aggressive session expiry (most hosting companies did that, which is horribly annoying) or use less objects in session. Try to avoid any kind of object, instead just store the keys for retrieving them, that is a very important design as it helps you to scale your session to a state server when you get big.</p>\n"
},
{
"answer_id": 93968,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately due to the explicit nature of the web and the fact there is no permanent link between a website server and a users browser it is impossible to tell when a user has closed their browser. There are events and JavaScript which you can implement (e.g. onunload) which you can use to place calls back to the server which in turn could 'kill' a session - <code>Session.Abandon();</code></p>\n\n<p>You can set the timeout length of a session within the web.config, remember this timeout is based on the time since the last call to the server was placed by the users browser.</p>\n\n<p>Browser timedout did not added.</p>\n"
},
{
"answer_id": 94008,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 2,
"selected": false,
"text": "<p>You could set a short session timeout (eg 5 mins) and then get the page to poll the server periodically, either by using Javascript to fire an XmlHttpRequest every 2 minutes, or by having a hidden iframe which points to a page which refreshes itself every 2 minutes.</p>\n\n<p>Once the browser closes, the session would timeout pretty quickly afterwards as there would be nothing to keep it alive.</p>\n"
},
{
"answer_id": 94065,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a new problem, there are several scenarios that must be handled if you want to catch all the ways a session can end, here are general examples of some of them:</p>\n\n<ol>\n<li>The browser instance or tab is closed.</li>\n<li>User navigates away from your website using the same browser instance or tab.</li>\n<li>The users loses their connection to the internet (this could include power loss to user's computer or any other means).</li>\n<li>User walks away from the computer (or in some other way stops interacting with your site).</li>\n<li>The server loses power/reboots.</li>\n</ol>\n\n<p>The first two items must be handled by the client sending information to the server, generally you would use javascript to navigate to a logout page that quickly expires the session.</p>\n\n<p>The third and fourth items are normally handled by setting the session state timeout (it can be any amount of time). The amount of time you use is based on finding a value that allows the users to use your site without overwhelming the server. A very rough rule of thumb could be 30 minutes plus or minus 10 minutes. However the appropriate value would probably have to be the subject of another post.</p>\n\n<p>The fifth item is handled based on how you are storing your sessions. Sessions stored in-state will not survive a reboot since they are in the computer's ram. Sessions stored in a db or cookie would survive the reboot. You could handle this as you see fit.</p>\n\n<p>In my limited experience when this issue has come up before, it's been determined that just setting the session timeout to an acceptable value is all that's needed. However it can be done.</p>\n"
},
{
"answer_id": 94323,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 0,
"selected": false,
"text": "<p>Correct me if I am misreading the intent of your question, but the underlying question seems to be less about how to force the session to end when a user closes the browser and more about how to prevent a session from ending until the browser is closed.</p>\n\n<p>I think the real answer to this is to re-evaluate what you are using sessions to do. If you are using them to maintain state, I agree with the other responses that you may be out of luck.</p>\n\n<p>However, a preferred approach is to use a persistent state mechanism with the same scope as the browser session such as a cookie that expires when the browser is closed. That cookie could contain just enough information to re-initiate the session on the server if it has expired since the last request. Combined with a relatively short (5-10 min) session timeout, I think this gives you the best balance between server resource usage and not making the user continually \"re-boot\" the site.</p>\n"
},
{
"answer_id": 94362,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:</p>\n\n<pre><code><configuration>\n <system.web>\n <sessionState timeout=\"60\" />\n ... other elements omitted ...\n </system.web>\n ... other elements omitted ....\n</configuration>\n</code></pre>\n\n<p>You can do the same for a particular user in code with:</p>\n\n<pre><code>Session.Timeout = 60\n</code></pre>\n\n<p>Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.</p>\n\n<p>There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.</p>\n\n<p>If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course).</p>\n"
},
{
"answer_id": 100748,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 0,
"selected": false,
"text": "<p>Oh you have rewritten the question.</p>\n\n<p>That one is absolutely feasible, as long as javascript is alive. Use any timed ajax will do. Check with prototype library <a href=\"http://www.prototypejs.org\" rel=\"nofollow noreferrer\">http://www.prototypejs.org</a> PeriodicalExecutor or jQuery with the ajax + timer plugin. Setup a dummy page which your executor will call from time to time, so your session is always alive unless if he logouts (kill the ajax timer in the same time) or close browser (which means the executor is killed anyway)</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17404/"
]
| By default the session expiry seems to be 20 minutes.
Update: I do not want the session to expire until the browser is closed.
Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and *should* be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.
In PHP I can set session.cookie\_lifetime in php.ini to zero to achieve this. | If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:
```
<configuration>
<system.web>
<sessionState timeout="60" />
... other elements omitted ...
</system.web>
... other elements omitted ....
</configuration>
```
You can do the same for a particular user in code with:
```
Session.Timeout = 60
```
Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.
There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.
If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course). |
93,932 | <p>We are getting an error in a VB6 application that sends data back and forth over TCP sockets. We get a runtime error "out of string space". Has anyone seen this or have any thoughts on why this would happen? It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well.</p>
| [
{
"answer_id": 94043,
"author": "Robit",
"author_id": 17026,
"author_profile": "https://Stackoverflow.com/users/17026",
"pm_score": 2,
"selected": false,
"text": "<p>Text found on MSDN:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa264524(VS.60).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa264524(VS.60).aspx</a></p>\n\n<blockquote>\n <p>Visual Basic for Applications\n Reference Out of string space (Error\n 14)</p>\n \n <p>Specifics</p>\n \n <p>Visual Basic permits you to use very\n large strings. However, the\n requirements of other programs and the\n way you manipulate your strings may\n cause this error. This error has the\n following causes and solutions:</p>\n \n <ul>\n <li>Expressions requiring that temporary strings be created for\n evaluation may cause this error. For\n example, the following code causes an\n Out of string space error on some\n operating systems:</li>\n </ul>\n</blockquote>\n\n<pre><code>MyString = \"Hello\"\nFor Count = 1 To 100\nMyString = MyString & MyString\nNext Count\n</code></pre>\n\n<blockquote>\n<pre><code> Assign the string to a variable of another name.\n* Your system may have run out of memory, which prevented a string from\n</code></pre>\n \n <p>being allocated.</p>\n \n <p>Remove any unnecessary applications from memory to create\n more space.</p>\n \n <p>For additional information, select the\n item in question and press F1.</p>\n</blockquote>\n"
},
{
"answer_id": 94091,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that you are appending data in a loop, ensure that it's not being appended to itself, which will eat memory extremely quickly.</p>\n\n<p>Example and description of error meaning:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa264524.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa264524.aspx</a></p>\n"
},
{
"answer_id": 94179,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 5,
"selected": true,
"text": "<p>As others have pointed out, every string concatenation in VB will allocate a new string and then copy the data over and then de-allocate the original once it can. In a loop this can cause issues.</p>\n\n<p>To work around this you can create a simple StringBuilder class like this one:</p>\n\n<pre><code>Option Explicit\n\nPrivate data As String\nPrivate allocLen As Long\nPrivate currentPos As Long\n\nPublic Function Text() As String\n Text = Left(data, currentPos)\nEnd Function\n\nPublic Function Length() As Long\n Length = currentPos\nEnd Function\n\nPublic Sub Add(s As String)\n\n Dim newLen As Long\n newLen = Len(s)\n If ((currentPos + newLen) > allocLen) Then\n data = data & Space((currentPos + newLen))\n allocLen = Len(data)\n End If\n\n Mid(data, currentPos + 1, newLen) = s\n currentPos = currentPos + newLen\n\nEnd Sub\n\nPrivate Sub Class_Initialize()\n data = Space(10240)\n allocLen = Len(data)\n currentPos = 1\nEnd Sub\n</code></pre>\n\n<p>This class will minimize the number of string allocations by forcing the string to be built with spaces in it and then overwriting the spaces as needed. It re-allocates to roughly double its size when it finds that it does not have enough space pre-initialized. The Text method will return the portion of the string that is actually used.</p>\n"
},
{
"answer_id": 94201,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you are appending a string often. You could try using a <a href=\"http://www.vbaccelerator.com/home/VB/Code/Techniques/StringBuilder/article.asp\" rel=\"nofollow noreferrer\">StringBuilder class</a></p>\n\n<p>Also, it could be you have some stale objects that contain strings hanging around that aren't being used and should be freed. Check for circular references perhaps by logging object allocation/frees in <code>Class_Initialize/Class_Finalize</code></p>\n"
},
{
"answer_id": 94231,
"author": "Rylee Corradini",
"author_id": 7542,
"author_profile": "https://Stackoverflow.com/users/7542",
"pm_score": 2,
"selected": false,
"text": "<p>Adding to Jacco's response, <a href=\"http://www.vbaccelerator.com/home/VB/Code/Techniques/StringBuilder/article.asp\" rel=\"nofollow noreferrer\">vbAccelerator</a> has a great String Builder class that accomplishes much the same thing but is a little more robust. The author also walks through the solution explaining how it works.</p>\n"
},
{
"answer_id": 1328710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sometime in the spring of 2009, Microsoft did an XP update that interferes with Armadillo/Silicon Realms wrapper. \nThe line of code that was throwing error 14, Out of String space was not logical. There was no problem with a over sized string. It was a simple assignment that I even changed to be \"foo\" and error 14 still occurred. I think the error is mapped incorrectly in XP. \nThe answer for us was to remove copyMem-11 from the Armadillo protection project and rewrap the the exe.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
]
| We are getting an error in a VB6 application that sends data back and forth over TCP sockets. We get a runtime error "out of string space". Has anyone seen this or have any thoughts on why this would happen? It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well. | As others have pointed out, every string concatenation in VB will allocate a new string and then copy the data over and then de-allocate the original once it can. In a loop this can cause issues.
To work around this you can create a simple StringBuilder class like this one:
```
Option Explicit
Private data As String
Private allocLen As Long
Private currentPos As Long
Public Function Text() As String
Text = Left(data, currentPos)
End Function
Public Function Length() As Long
Length = currentPos
End Function
Public Sub Add(s As String)
Dim newLen As Long
newLen = Len(s)
If ((currentPos + newLen) > allocLen) Then
data = data & Space((currentPos + newLen))
allocLen = Len(data)
End If
Mid(data, currentPos + 1, newLen) = s
currentPos = currentPos + newLen
End Sub
Private Sub Class_Initialize()
data = Space(10240)
allocLen = Len(data)
currentPos = 1
End Sub
```
This class will minimize the number of string allocations by forcing the string to be built with spaces in it and then overwriting the spaces as needed. It re-allocates to roughly double its size when it finds that it does not have enough space pre-initialized. The Text method will return the portion of the string that is actually used. |
93,976 | <p>How do you check if a one-character String is a letter - including any letters with accents?</p>
<p>I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me.</p>
| [
{
"answer_id": 93979,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 6,
"selected": true,
"text": "<p>Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.</p>\n\n<p>I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:</p>\n\n<pre><code>string.matches(\"\\\\p{L}\"); // Unicode letter\nstring.matches(\"\\\\p{Lu}\"); // Unicode upper-case letter\n</code></pre>\n\n<p>You can also do this with <em>Character</em> class:</p>\n\n<pre><code>Character.isLetter(character);\n</code></pre>\n\n<p>but that is less convenient if you need to check more than one letter.</p>\n"
},
{
"answer_id": 94004,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 5,
"selected": false,
"text": "<p>Character.isLetter() is much faster than string.matches(), because string.matches() compiles a new Pattern every time. Even caching the pattern, I think isLetter() would still beat it.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> Just ran across this again and thought I'd try to come up with some actual numbers. Here's my attempt at a benchmark, checking all three methods (<code>matches()</code> with and without caching the <code>Pattern</code>, and <code>Character.isLetter()</code>). I also made sure that there were both valid and invalid characters checked, so as not to skew things.</p>\n\n<pre><code>import java.util.regex.*;\n\nclass TestLetter {\n private static final Pattern ONE_CHAR_PATTERN = Pattern.compile(\"\\\\p{L}\");\n private static final int NUM_TESTS = 10000000;\n\n public static void main(String[] args) {\n long start = System.nanoTime();\n int counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testMatches(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of Pattern.matches() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n /*********************************/\n start = System.nanoTime();\n counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testCharacter(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of isLetter() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n /*********************************/\n start = System.nanoTime();\n counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testMatchesNoCache(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of String.matches() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n }\n\n private static boolean testMatches(final String c) {\n return ONE_CHAR_PATTERN.matcher(c).matches();\n }\n private static boolean testMatchesNoCache(final String c) {\n return c.matches(\"\\\\p{L}\");\n }\n private static boolean testCharacter(final String c) {\n return Character.isLetter(c.charAt(0));\n }\n}\n</code></pre>\n\n<p>And my output:</p>\n\n<pre>10000000 tests of Pattern.matches() took 4325146672 ns.\nThere were 4062500/10000000 valid characters\n10000000 tests of isLetter() took 546031201 ns.\nThere were 4062500/10000000 valid characters\n10000000 tests of String.matches() took 11900205444 ns.\nThere were 4062500/10000000 valid characters</pre>\n\n<p>So that's almost 8x better, even with a cached <code>Pattern</code>. (And uncached is nearly 3x worse than cached.)</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
]
| How do you check if a one-character String is a letter - including any letters with accents?
I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me. | Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.
I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:
```
string.matches("\\p{L}"); // Unicode letter
string.matches("\\p{Lu}"); // Unicode upper-case letter
```
You can also do this with *Character* class:
```
Character.isLetter(character);
```
but that is less convenient if you need to check more than one letter. |
93,983 | <p>How can I take the string <code>foo[]=1&foo[]=5&foo[]=2</code> and return a collection with the values <code>1,5,2</code> in that order. I am looking for an answer using regex in C#. Thanks</p>
| [
{
"answer_id": 94009,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know C#, but...</p>\n\n<p>In java:</p>\n\n<pre><code>String[] nums = String.split(yourString, \"&?foo[]\");\n</code></pre>\n\n<p>The second argument in the <code>String.split()</code> method is a regex telling the method where to split the String.</p>\n"
},
{
"answer_id": 94038,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming you're dealing with numbers this pattern should match:</p>\n\n<pre><code>/=(\\d+)&?/\n</code></pre>\n"
},
{
"answer_id": 94063,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 0,
"selected": false,
"text": "<p>This should do:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nRegex.Replace(s, !@\"^[0-9]*$”, \"\");\n</code></pre>\n\n<p>Where s is your String where you want the numbers to be extracted.</p>\n"
},
{
"answer_id": 94064,
"author": "Hans Sjunnesson",
"author_id": 8683,
"author_profile": "https://Stackoverflow.com/users/8683",
"pm_score": 0,
"selected": false,
"text": "<p>Just make sure to escape the ampersand like so:</p>\n\n<pre><code>/=(\\d+)\\&/\n</code></pre>\n"
},
{
"answer_id": 94078,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 3,
"selected": true,
"text": "<p>In C# you can use capturing groups</p>\n\n<pre><code> private void RegexTest()\n {\n String input = \"foo[]=1&foo[]=5&foo[]=2\";\n String pattern = @\"foo\\[\\]=(\\d+)\";\n\n Regex regex = new Regex(pattern);\n\n foreach (Match match in regex.Matches(input))\n {\n Console.Out.WriteLine(match.Groups[1]);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 94096,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 1,
"selected": false,
"text": "<p>Use the Regex.Split() method with an appropriate regex. This will split on parts of the string that match the regular expression and return the results as a string[]. </p>\n\n<p>Assuming you want all the values in your querystring without checking if they're numeric, (and without just matching on names like foo[]) you could use this: \"&?[^&=]+=\" </p>\n\n<pre><code>string[] values = Regex.Split(“foo[]=1&foo[]=5&foo[]=2”, \"&?[^&=]+=\");\n</code></pre>\n\n<p>Incidentally, if you're playing with regular expressions the site <a href=\"http://gskinner.com/RegExr/\" rel=\"nofollow noreferrer\">http://gskinner.com/RegExr/</a> is fantastic (I'm just a fan).</p>\n"
},
{
"answer_id": 94109,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 1,
"selected": false,
"text": "<p>I'd use this particular pattern:</p>\n\n<pre><code>string re = @\"foo\\[\\]=(?<value>\\d+)\";\n</code></pre>\n\n<p>So something like (not tested):</p>\n\n<pre><code>Regex reValues = new Regex(re,RegexOptions.Compiled);\nList<integer> values = new List<integer>();\n\nforeach (Match m in reValues.Matches(...putInputStringHere...)\n{\n values.Add((int) m.Groups(\"value\").Value);\n}\n</code></pre>\n"
},
{
"answer_id": 94649,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an alternative solution using the built-in string.Split function:</p>\n\n<pre><code>string x = \"foo[]=1&foo[]=5&foo[]=2\";\nstring[] separator = new string[2] { \"foo[]=\", \"&\" };\nstring[] vals = x.Split(separator, StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17872/"
]
| How can I take the string `foo[]=1&foo[]=5&foo[]=2` and return a collection with the values `1,5,2` in that order. I am looking for an answer using regex in C#. Thanks | In C# you can use capturing groups
```
private void RegexTest()
{
String input = "foo[]=1&foo[]=5&foo[]=2";
String pattern = @"foo\[\]=(\d+)";
Regex regex = new Regex(pattern);
foreach (Match match in regex.Matches(input))
{
Console.Out.WriteLine(match.Groups[1]);
}
}
``` |
93,989 | <p>In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution?</p>
| [
{
"answer_id": 94005,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.csharp-online.net/Application_Architecture_in_Windows_Forms_2.0\" rel=\"nofollow noreferrer\">http://en.csharp-online.net/Application_Architecture_in_Windows_Forms_2.0</a>—Single-Instance_Detection_and_Management</p>\n"
},
{
"answer_id": 94016,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>This article simply explains how you can create a windows application with control on the number of its instances or run only single instance. This is very typical need of a business application. There are already lots of other possible solutions to control this.</p>\n<p><a href=\"https://web.archive.org/web/20090205153420/http://www.openwinforms.com/single_instance_application.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20090205153420/http://www.openwinforms.com/single_instance_application.html</a></p>\n"
},
{
"answer_id": 94017,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": false,
"text": "<p>Hanselman has <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx\" rel=\"noreferrer\">a post</a> on using the WinFormsApplicationBase class from the Microsoft.VisualBasic assembly to do this.</p>\n"
},
{
"answer_id": 94018,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.codeproject.com/KB/cs/SingleInstancingWithIpc.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/SingleInstancingWithIpc.aspx</a></p>\n"
},
{
"answer_id": 94019,
"author": "Thomas Jespersen",
"author_id": 8547,
"author_profile": "https://Stackoverflow.com/users/8547",
"pm_score": 1,
"selected": false,
"text": "<p>You have to use System.Diagnostics.Process.</p>\n\n<p>Check out: <a href=\"http://www.devx.com/tips/Tip/20044\" rel=\"nofollow noreferrer\">http://www.devx.com/tips/Tip/20044</a></p>\n"
},
{
"answer_id": 94021,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 0,
"selected": false,
"text": "<p>Normally it's done with a named Mutex (use new Mutex( \"your app name\", true ) and check the return value), but there's also some support classes in Microsoft.VisualBasic.dll that <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx\" rel=\"nofollow noreferrer\">can do it for you</a>.</p>\n"
},
{
"answer_id": 94059,
"author": "Thomas Wagner",
"author_id": 13997,
"author_profile": "https://Stackoverflow.com/users/13997",
"pm_score": 5,
"selected": false,
"text": "<pre><code>if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)\n{\n AppLog.Write(\"Application XXXX already running. Only one instance of this application is allowed\", AppLog.LogMessageType.Warn);\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 94115,
"author": "Doliveras",
"author_id": 3611,
"author_profile": "https://Stackoverflow.com/users/3611",
"pm_score": 2,
"selected": false,
"text": "<p>Using Visual Studio 2005 or 2008 when you create a project for an executable, on the properties windows inside the \"Application\" panel there is a check box named “Make single instance application” that you can activate to convert the application on a single instance application.</p>\n\n<p>Here is a capture of the window I'm talking of:\n<img src=\"https://i.stack.imgur.com/Wtori.png\" alt=\"enter image description here\">\nThis is a Visual Studio 2008 windows application project.</p>\n"
},
{
"answer_id": 94255,
"author": "ImJustPondering",
"author_id": 17940,
"author_profile": "https://Stackoverflow.com/users/17940",
"pm_score": 8,
"selected": true,
"text": "<p>Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:</p>\n\n<p><a href=\"http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx\" rel=\"noreferrer\">http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx</a></p>\n\n<pre><code>[STAThread]\nstatic void Main() \n{\n using(Mutex mutex = new Mutex(false, \"Global\\\\\" + appGuid))\n {\n if(!mutex.WaitOne(0, false))\n {\n MessageBox.Show(\"Instance already running\");\n return;\n }\n\n Application.Run(new Form1());\n }\n}\n\nprivate static string appGuid = \"c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9\";\n</code></pre>\n"
},
{
"answer_id": 94713,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like there are 3 fundamental techniques that have been suggested so far.</p>\n\n<ol>\n<li>Derive from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class and set the IsSingleInstance property to true. (I believe a caveat here is that this won't work with WPF applications, will it?)</li>\n<li>Use a named mutex and check if it's already been created.</li>\n<li>Get a list of running processes and compare the names of the processes. (This has the caveat of requiring your process name to be unique relative to any other processes running on a given user's machine.)</li>\n</ol>\n\n<p>Any caveats I've missed?</p>\n"
},
{
"answer_id": 95304,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 5,
"selected": false,
"text": "<p>Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex. </p>\n\n<pre><code>public class Program\n{\n static System.Threading.Mutex singleton = new Mutex(true, \"My App Name\");\n\n static void Main(string[] args)\n {\n if (!singleton.WaitOne(TimeSpan.Zero, true))\n {\n //there is already another instance running!\n Application.Exit();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 95952,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 2,
"selected": false,
"text": "<p>Use VB.NET!\nNo: really ;)</p>\n\n<p>using Microsoft.VisualBasic.ApplicationServices;</p>\n\n<p>The WindowsFormsApplicationBase from VB.Net provides you with a \"SingleInstace\" Property, which determines other Instances and let only one Instance run.</p>\n"
},
{
"answer_id": 509873,
"author": "Ric Tokyo",
"author_id": 42019,
"author_profile": "https://Stackoverflow.com/users/42019",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[STAThread]\nstatic void Main() // args are OK here, of course\n{\n bool ok;\n m = new System.Threading.Mutex(true, \"YourNameHere\", out ok);\n\n if (! ok)\n {\n MessageBox.Show(\"Another instance is already running.\");\n return;\n }\n\n Application.Run(new Form1()); // or whatever was there\n\n GC.KeepAlive(m); // important!\n}\n</code></pre>\n\n<p>From: <a href=\"http://www.ai.uga.edu/mc/SingleInstance.html\" rel=\"nofollow noreferrer\">Ensuring a single instance of .NET Application</a></p>\n\n<p>and: <a href=\"http://www.codeproject.com/KB/cs/SingleInstanceAppMutex.aspx\" rel=\"nofollow noreferrer\">Single Instance Application Mutex</a></p>\n\n<p>Same answer as @Smink and @Imjustpondering with a twist:</p>\n\n<p><a href=\"http://www.yoda.arachsys.com/csharp/faq/\" rel=\"nofollow noreferrer\">Jon Skeet's FAQ on C#</a> to find out why <a href=\"http://msdn.microsoft.com/en-us/library/system.gc.keepalive.aspx\" rel=\"nofollow noreferrer\">GC.KeepAlive</a> matters</p>\n"
},
{
"answer_id": 13153090,
"author": "Shruti",
"author_id": 1352967,
"author_profile": "https://Stackoverflow.com/users/1352967",
"pm_score": 2,
"selected": false,
"text": "<p>This is the code for VB.Net</p>\n\n<pre><code>Private Shared Sub Main()\n Using mutex As New Mutex(False, appGuid)\n If Not mutex.WaitOne(0, False) Then\n MessageBox.Show(\"Instance already running\", \"ERROR\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n Return\n End If\n\n Application.Run(New Form1())\n End Using\nEnd Sub\n</code></pre>\n\n<p>This is the code for C#</p>\n\n<pre><code>private static void Main()\n{\n using (Mutex mutex = new Mutex(false, appGuid)) {\n if (!mutex.WaitOne(0, false)) {\n MessageBox.Show(\"Instance already running\", \"ERROR\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return;\n }\n\n Application.Run(new Form1());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21407828,
"author": "Bitterblue",
"author_id": 1442225,
"author_profile": "https://Stackoverflow.com/users/1442225",
"pm_score": 1,
"selected": false,
"text": "<p><em>(Note: this is a fun-solution! It works but uses bad GDI+ design to achieve this.)</em></p>\n\n<p>Put an image in with your app and load it on startup. Hold it until the app exits. The user wont be able to start a 2nd instance. <em>(Of course the mutex solution is much cleaner)</em></p>\n\n<pre><code>private static Bitmap randomName = new Bitmap(\"my_image.jpg\");\n</code></pre>\n"
},
{
"answer_id": 21598156,
"author": "HypeZ",
"author_id": 1957622,
"author_profile": "https://Stackoverflow.com/users/1957622",
"pm_score": 3,
"selected": false,
"text": "<p>i tried all the solutions here and nothing worked in my C# .net 4.0 project. Hoping to help someone here the solution that worked for me:</p>\n\n<p>As main class variables:</p>\n\n<pre><code>private static string appGuid = \"WRITE AN UNIQUE GUID HERE\";\nprivate static Mutex mutex;\n</code></pre>\n\n<p>When you need to check if app is already running:</p>\n\n<pre><code>bool mutexCreated;\nmutex = new Mutex(true, \"Global\\\\\" + appGuid, out mutexCreated);\nif (mutexCreated)\n mutex.ReleaseMutex();\n\nif (!mutexCreated)\n{\n //App is already running, close this!\n Environment.Exit(0); //i used this because its a console app\n}\n</code></pre>\n\n<p>I needed to close other istances only with some conditions, this worked well for my purpose</p>\n"
},
{
"answer_id": 30907248,
"author": "Derek Wade",
"author_id": 2668852,
"author_profile": "https://Stackoverflow.com/users/2668852",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me in pure C#. the try/catch is when possibly a process in the list exits during your loop.</p>\n\n<pre><code>using System.Diagnostics;\n....\n[STAThread]\nstatic void Main()\n{\n...\n int procCount = 0;\n foreach (Process pp in Process.GetProcesses())\n {\n try\n {\n if (String.Compare(pp.MainModule.FileName, Application.ExecutablePath, true) == 0)\n {\n procCount++; \n if(procCount > 1) {\n Application.Exit();\n return;\n }\n }\n }\n catch { }\n }\n Application.Run(new Form1());\n}\n</code></pre>\n"
},
{
"answer_id": 31827620,
"author": "Kasper Jensen",
"author_id": 2123213,
"author_profile": "https://Stackoverflow.com/users/2123213",
"pm_score": 3,
"selected": false,
"text": "<p>After trying multiple solutions i the question. I ended up using the example for <strong>WPF</strong> here: <a href=\"http://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/\" rel=\"noreferrer\">http://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/</a></p>\n\n<pre><code>public partial class App : Application \n{ \n private static Mutex _mutex = null; \n\n protected override void OnStartup(StartupEventArgs e) \n { \n const string appName = \"MyAppName\"; \n bool createdNew; \n\n _mutex = new Mutex(true, appName, out createdNew); \n\n if (!createdNew) \n { \n //app is already running! Exiting the application \n Application.Current.Shutdown(); \n } \n\n } \n} \n</code></pre>\n\n<p>In App.xaml:</p>\n\n<pre><code>x:Class=\"*YourNameSpace*.App\"\nStartupUri=\"MainWindow.xaml\"\nStartup=\"App_Startup\"\n</code></pre>\n"
},
{
"answer_id": 32336567,
"author": "user5289350",
"author_id": 5289350,
"author_profile": "https://Stackoverflow.com/users/5289350",
"pm_score": 3,
"selected": false,
"text": "<p>1 - Create a reference in program.cs -> </p>\n\n<pre><code>using System.Diagnostics;\n</code></pre>\n\n<p>2 - Put into <code>void Main()</code> as the first line of code -></p>\n\n<pre><code> if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length >1)\n return;\n</code></pre>\n\n<p>That's it.</p>\n"
},
{
"answer_id": 41597643,
"author": "Divins Mathew",
"author_id": 3201403,
"author_profile": "https://Stackoverflow.com/users/3201403",
"pm_score": 1,
"selected": false,
"text": "<p>Simply using a <code>StreamWriter</code>, how about this?</p>\n\n<pre><code>System.IO.File.StreamWriter OpenFlag = null; //globally\n</code></pre>\n\n<p>and</p>\n\n<pre><code>try\n{\n OpenFlag = new StreamWriter(Path.GetTempPath() + \"OpenedIfRunning\");\n}\ncatch (System.IO.IOException) //file in use\n{\n Environment.Exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 41598391,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 0,
"selected": false,
"text": "<p>Be sure to consider security when restricting an application to a single instance:</p>\n\n<p>Full article:\n<a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20060620-13/?p=30813\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/oldnewthing/20060620-13/?p=30813</a></p>\n\n<blockquote>\n <p>We are using a named mutex with a fixed name in order to detect\n whether another copy of the program is running. But that also means an\n attacker can create the mutex first, thereby preventing our program\n from running at all! How can I prevent this type of denial of service\n attack?</p>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n <p>If the attacker is running in the same security context as your\n program is (or would be) running in, then there is nothing you can do.\n Whatever \"secret handshake\" you come up with to determine whether\n another copy of your program is running, the attacker can mimic it.\n Since it is running in the correct security context, it can do\n anything that the \"real\" program can do.</p>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n <p>Clearly you can't protect yourself from an attacker running at the\n same security privilege, but you can still protect yourself against\n unprivileged attackers running at other security privileges.</p>\n</blockquote>\n\n<p>Try setting a DACL on your mutex, here's the .NET way:\n<a href=\"https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexsecurity(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexsecurity(v=vs.110).aspx</a></p>\n"
},
{
"answer_id": 54640621,
"author": "Tono Nam",
"author_id": 637142,
"author_profile": "https://Stackoverflow.com/users/637142",
"pm_score": 0,
"selected": false,
"text": "<p>None of this answers worked for me because I needed this to work under Linux using monodevelop. This works great for me:</p>\n\n<p>Call this method passing it a unique ID</p>\n\n<pre><code> public static void PreventMultipleInstance(string applicationId)\n {\n // Under Windows this is:\n // C:\\Users\\SomeUser\\AppData\\Local\\Temp\\ \n // Linux this is:\n // /tmp/\n var temporaryDirectory = Path.GetTempPath();\n\n // Application ID (Make sure this guid is different accross your different applications!\n var applicationGuid = applicationId + \".process-lock\";\n\n // file that will serve as our lock\n var fileFulePath = Path.Combine(temporaryDirectory, applicationGuid);\n\n try\n {\n // Prevents other processes from reading from or writing to this file\n var _InstanceLock = new FileStream(fileFulePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n _InstanceLock.Lock(0, 0);\n MonoApp.Logger.LogToDisk(LogType.Notification, \"04ZH-EQP0\", \"Aquired Lock\", fileFulePath);\n\n // todo investigate why we need a reference to file stream. Without this GC releases the lock!\n System.Timers.Timer t = new System.Timers.Timer()\n {\n Interval = 500000,\n Enabled = true,\n };\n t.Elapsed += (a, b) =>\n {\n try\n {\n _InstanceLock.Lock(0, 0);\n }\n catch\n {\n MonoApp.Logger.Log(LogType.Error, \"AOI7-QMCT\", \"Unable to lock file\");\n }\n };\n t.Start();\n\n }\n catch\n {\n // Terminate application because another instance with this ID is running\n Environment.Exit(102534); \n }\n } \n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/93989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682/"
]
| In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution? | Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:
<http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx>
```
[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}
Application.Run(new Form1());
}
}
private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
``` |
94,011 | <p>Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.
If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.</p>
<p>How can I do something like that?</p>
<p>PS: There is no loop in the <code>run()</code> method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.</p>
| [
{
"answer_id": 94031,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 3,
"selected": false,
"text": "<p>The thread that is updating the 3D view should periodically check some flag (use a <code>volatile boolean</code>) to see if it should terminate. When you want to abort the thread, just set the flag. When the thread next checks the flag, it should simply break out of whatever loop it is using to update the view and return from its <code>run</code> method.</p>\n\n<p>If you truly cannot access the code the Thread is running to have it check a flag, then there is no safe way to stop the Thread. Does this Thread ever terminate normally before your application completes? If so, what causes it to stop?</p>\n\n<p>If it runs for some long period of time, and you simply must end it, you can consider using the deprecated <code>Thread.stop()</code> method. However, it was deprecated for a good reason. If that Thread is stopped while in the middle of some operation that leaves something in an inconsistent state or some resource not cleaned up properly, then you could be in trouble. Here's a note from the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#stop()\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>This method is inherently unsafe.\n Stopping a thread with Thread.stop\n causes it to unlock all of the\n monitors that it has locked (as a\n natural consequence of the unchecked\n ThreadDeath exception propagating up\n the stack). If any of the objects\n previously protected by these monitors\n were in an inconsistent state, the\n damaged objects become visible to\n other threads, potentially resulting\n in arbitrary behavior. Many uses of\n stop should be replaced by code that\n simply modifies some variable to\n indicate that the target thread should\n stop running. The target thread should\n check this variable regularly, and\n return from its run method in an\n orderly fashion if the variable\n indicates that it is to stop running.\n If the target thread waits for long\n periods (on a condition variable, for\n example), the interrupt method should\n be used to interrupt the wait. For\n more information, see <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html\" rel=\"nofollow noreferrer\">Why are\n Thread.stop, Thread.suspend and\n Thread.resume Deprecated?</a></p>\n</blockquote>\n"
},
{
"answer_id": 94068,
"author": "Olvagor",
"author_id": 17473,
"author_profile": "https://Stackoverflow.com/users/17473",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe this can help you: <a href=\"http://www.jguru.com/forums/view.jsp?EID=1268343\" rel=\"nofollow noreferrer\">How can we kill a running thread in Java?</a></p>\n\n<blockquote>\n <p>You can kill a particular thread by setting an external class variable.</p>\n</blockquote>\n\n<pre><code> Class Outer\n { \n public static flag=true;\n Outer()\n {\n new Test().start();\n } \n class Test extends Thread\n { \n public void run()\n {\n while(Outer.flag)\n {\n //do your work here\n } \n }\n }\n } \n</code></pre>\n\n<blockquote>\n <p>if you want to stop the above thread, set flag variable to <code>false</code>. The other way to kill a thread is just registering it in ThreadGroup, then call <code>destroy()</code>. This way can also be used to kill similar threads by creating them as group or register with group.</p>\n</blockquote>\n"
},
{
"answer_id": 94069,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>The way I have implemented something like this in the past is to implement a <code>shutdown()</code> method in my <code>Runnable</code> subclass which sets an instance variable called <code>should_shutdown</code> to true. The <code>run()</code> method normally does something in a loop, and will periodically check <code>should_shutdown</code> and when it is true, returns, or calls <code>do_shutdown()</code> and then returns.</p>\n\n<p>You should keep a reference to the current worker thread handy, and when the user changes a value, call <code>shutdown()</code> on the current thread, and wait for it to shutdown. Then you can launch a new thread.</p>\n\n<p>I would not recommend using <code>Thread.stop</code> as it was deprecated last time I checked.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Read your comment about how your worker thread just calls another method which takes a while to run, so the above does not apply. In this case, your only real options are to try calling <code>interrupt()</code> and see if has any effect. If not, consider somehow manually causing the function your worker thread is calling to break. For example, it sounds like it is doing some complex rendering, so maybe destroy the canvas and cause it to throw an exception. This is not a nice solution, but as far as I can tell, this is the only way to stop a thread in suituations like this.</p>\n"
},
{
"answer_id": 94088,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 1,
"selected": false,
"text": "<p>A thread will exit once it's <code>run()</code> method is complete, so you need some check which will make it finish the method.</p>\n\n<p>You can interrupt the thread, and then have some check which would periodically check <code>isInterrupted()</code> and return out of the <code>run()</code> method.</p>\n\n<p>You could also use a boolean which gets periodically checked within the thread, and makes it return if so, or put the thread inside a loop if it's doing some repetative task and it will then exit the run() method when you set the boolean. For example,</p>\n\n<pre><code>static boolean shouldExit = false;\nThread t = new Thread(new Runnable() {\n public void run() {\n while (!shouldExit) {\n // do stuff\n }\n }\n}).start();\n</code></pre>\n"
},
{
"answer_id": 94117,
"author": "bmeck",
"author_id": 12781,
"author_profile": "https://Stackoverflow.com/users/12781",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately killing a thread is inherently unsafe due to the possibilities of using resources that can be synchronized by locks and if the thread you kill currently has a lock could result in the program going into deadlock (constant attempt to grab a resource that cannot be obtained). You will have to manually check if it needs to be killed from the thread that you want to stop. Volatile will ensure checking the variable's true value rather than something that may have been stored previously. On a side note Thread.join on the exiting thread to ensure you wait until the dying thread is actually gone before you do anything rather than checking all the time.</p>\n"
},
{
"answer_id": 94190,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of rolling your own boolean flag, why not just use the thread interrupt mechanism already in Java threads? Depending on how the internals were implemented in the code you can't change, you may be able to abort part of its execution too.</p>\n\n<p>Outer Thread:</p>\n\n<pre><code>if(oldThread.isRunning())\n{\n oldThread.interrupt();\n // Be careful if you're doing this in response to a user\n // action on the Event Thread\n // Blocking the Event Dispatch Thread in Java is BAD BAD BAD\n oldThread.join();\n}\n\noldThread = new Thread(someRunnable);\noldThread.start();\n</code></pre>\n\n<p>Inner Runnable/Thread:</p>\n\n<pre><code>public void run()\n{\n // If this is all you're doing, interrupts and boolean flags may not work\n callExternalMethod(args);\n}\n\npublic void run()\n{\n while(!Thread.currentThread().isInterrupted)\n {\n // If you have multiple steps in here, check interrupted peridically and\n // abort the while loop cleanly\n }\n}\n</code></pre>\n"
},
{
"answer_id": 94304,
"author": "toluju",
"author_id": 12457,
"author_profile": "https://Stackoverflow.com/users/12457",
"pm_score": 0,
"selected": false,
"text": "<p>Since you're dealing with code you don't have access to you're probably out of luck. The standard procedure (as outlined in the other answers) is to have a flag that is checked periodically by the running thread. If the flag is set, do cleanup and exit. </p>\n\n<p>Since that option is not available to you, the only other option is to force quit the running process. This used to be possible by calling <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#stop()\" rel=\"nofollow noreferrer\">Thread.stop()</a>, but that method has been permanently deprecated for the following reason (copied from the javadocs):</p>\n\n<blockquote>\n <p>This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.</p>\n</blockquote>\n\n<p>More info on this topic can be found <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>One absolute sure way you could accomplish your request (although this is not a very efficient way to do this) is to start a new java process via <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#exec(java.lang.String)\" rel=\"nofollow noreferrer\">Runtime.exec()</a> and then stopping that process as necessary via <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#destroy()\" rel=\"nofollow noreferrer\">Process.destroy()</a>. Sharing state between processes like this is not exactly trivial, however.</p>\n"
},
{
"answer_id": 94326,
"author": "Nerdfest",
"author_id": 7855,
"author_profile": "https://Stackoverflow.com/users/7855",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of playing with thread starting and stopping, have you considered having the thread observe the properties that you're changing through your interface? You will at some point still want a stop condition for your thread, but this can be done this was as well. If you're a fan of MVC, this fits nicely into that sort of design</p>\n\n<p>Sorry, after re-reading your question, neither this nor any of the other 'check variable' suggestions will solve your problem. </p>\n"
},
{
"answer_id": 94454,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 2,
"selected": false,
"text": "<p>Isn't this a little like asking \"How can I abort a thread when no method other than Thread.stop() is available?\"</p>\n\n<p>Obviously, the only valid answer is Thread.stop(). Its ugly, could break things in some circumstances, can lead to memory/resource leaks, and is frowned upon by TLEJD (The League of Extraordinary Java Developers), however it can still be useful in a few cases like this. There really isn't any other method if the third party code doesn't have some close method available to it.</p>\n\n<p>OTOH, sometimes there are backdoor close methods. Ie, closing an underlying stream that its working with, or some other resource that it needs to do its job. This is seldom better than just calling Thread.stop() and letting it experience a ThreadDeathException, however.</p>\n"
},
{
"answer_id": 95372,
"author": "Javamann",
"author_id": 10166,
"author_profile": "https://Stackoverflow.com/users/10166",
"pm_score": 1,
"selected": false,
"text": "<p>You appear to not have any control over the thread that is rendering the screen but you do appear to have control of the spinner component. I would disable the spinner while the thread is rendering the screen. This way the user at least has some feedback relating to their actions.</p>\n"
},
{
"answer_id": 95636,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 5,
"selected": true,
"text": "<p>Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it.</p>\n\n<p>If performance is tolerable, you might view each 3D update as a discrete non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this:</p>\n\n<pre><code>boolean stopFlag = false;\nObject[] latestArgs = null;\n\npublic void run() {\n while (!stopFlag) {\n if (latestArgs != null) {\n Object[] args = latestArgs;\n latestArgs = null;\n perform3dUpdate(args);\n } else {\n Thread.sleep(500);\n }\n }\n}\n\npublic void endThread() {\n stopFlag = true;\n}\n\npublic void updateSettings(Object[] args) {\n latestArgs = args;\n}\n</code></pre>\n"
},
{
"answer_id": 95647,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest that you just prevent multiple Threads by using wait and notify so that if the user changes the value many times it will only run the Thread once. If the users changes the value 10 times it will fire off the Thread at the first change and then any changes made before the Thread is done all get \"rolled up\" into one notification. That won't stop a Thread but there are no good ways to do that based on your description.</p>\n"
},
{
"answer_id": 106009,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 1,
"selected": false,
"text": "<p>The solutions that purpose the usage of a boolean field are the right direction. But the field must be volatile.\nThe Java Language Spec <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.9\" rel=\"nofollow noreferrer\">says</a>:</p>\n\n<blockquote>\n <p>\"For example, in the following (broken) code fragment, assume that this.done is a non-\n volatile boolean field:</p>\n\n<pre>while (!this.done)\n Thread.sleep(1000);\n</pre>\n \n <p>The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.\"</p>\n</blockquote>\n\n<p>As far as I remember <a href=\"http://jcip.net/\" rel=\"nofollow noreferrer\">\"Java Concurrency in Pratice\"</a> purposes to use the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupt()\" rel=\"nofollow noreferrer\">interrupt()</a> and <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupted()\" rel=\"nofollow noreferrer\">interrupted()</a> methods of java.lang.Thread.</p>\n"
},
{
"answer_id": 240729,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 2,
"selected": false,
"text": "<p>The accepted answer to this question allows you to submit batch work into a background thread. This might be a better pattern for that:</p>\n\n<pre><code>public abstract class dispatcher<T> extends Thread {\n\n protected abstract void processItem(T work);\n\n private List<T> workItems = new ArrayList<T>();\n private boolean stopping = false;\n public void submit(T work) {\n synchronized(workItems) {\n workItems.add(work);\n workItems.notify();\n }\n }\n public void exit() {\n stopping = true;\n synchronized(workItems) {\n workItems.notifyAll();\n }\n this.join();\n }\n public void run() {\n while(!stopping) {\n T work;\n synchronized(workItems) {\n if (workItems.empty()) {\n workItems.wait();\n continue;\n }\n work = workItems.remove(0);\n }\n this.processItem(work);\n }\n }\n}\n</code></pre>\n\n<p>To use this class, extend it, providing a type for T and an implementation of processItem(). Then just construct one and call start() on it.</p>\n\n<p>You might consider adding an abortPending method:</p>\n\n<pre><code>public void abortPending() {\n synchronized(workItems) {\n workItems.clear();\n }\n}\n</code></pre>\n\n<p>for those cases where the user has skipped ahead of the rendering engine and you want to throw away the work that has been scheduled so far.</p>\n"
},
{
"answer_id": 250994,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 0,
"selected": false,
"text": "<p>The correct answer is to not use a thread.</p>\n\n<p>You should be using Executors, see the package: java.util.concurrent</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2612/"
]
| Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.
If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.
How can I do something like that?
PS: There is no loop in the `run()` method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code. | Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it.
If performance is tolerable, you might view each 3D update as a discrete non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this:
```
boolean stopFlag = false;
Object[] latestArgs = null;
public void run() {
while (!stopFlag) {
if (latestArgs != null) {
Object[] args = latestArgs;
latestArgs = null;
perform3dUpdate(args);
} else {
Thread.sleep(500);
}
}
}
public void endThread() {
stopFlag = true;
}
public void updateSettings(Object[] args) {
latestArgs = args;
}
``` |
94,023 | <p>I came across a controller in an older set of code (Rails 1.2.3) that had the following in a controller:</p>
<pre><code>class GenericController > ApplicationController
# filters and such
model :some_model
</code></pre>
<p>Although the name of the model does not match the name of the model, is there any reason to specify this? Or is this something that has disappeared from later versions of Rails?</p>
| [
{
"answer_id": 94040,
"author": "Joe Van Dyk",
"author_id": 17076,
"author_profile": "https://Stackoverflow.com/users/17076",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, that is something that has disappeared in later versions of Rails. There is no need to specify it.</p>\n"
},
{
"answer_id": 94041,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 3,
"selected": true,
"text": "<p>This had to do with dependency injection. I don't recall the details.</p>\n\n<p>By now it's just a glorified <code>require</code>, which you don't need because rails auto-requires files for missing constants.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13710/"
]
| I came across a controller in an older set of code (Rails 1.2.3) that had the following in a controller:
```
class GenericController > ApplicationController
# filters and such
model :some_model
```
Although the name of the model does not match the name of the model, is there any reason to specify this? Or is this something that has disappeared from later versions of Rails? | This had to do with dependency injection. I don't recall the details.
By now it's just a glorified `require`, which you don't need because rails auto-requires files for missing constants. |
94,037 | <p>How can I convert a character to its ASCII code using JavaScript?</p>
<p>For example:</p>
<blockquote>
<p>get 10 from "\n".</p>
</blockquote>
| [
{
"answer_id": 94049,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 12,
"selected": true,
"text": "<pre><code>\"\\n\".charCodeAt(0);\n</code></pre>\n"
},
{
"answer_id": 9539389,
"author": "Mohsen",
"author_id": 650722,
"author_profile": "https://Stackoverflow.com/users/650722",
"pm_score": 9,
"selected": false,
"text": "<p><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt\" rel=\"noreferrer\"><code>String.prototype.charCodeAt()</code></a> can convert string characters to ASCII numbers. For example:</p>\n\n<pre><code>\"ABC\".charCodeAt(0) // returns 65\n</code></pre>\n\n<p>For opposite use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/fromCharCode\" rel=\"noreferrer\"><code>String.fromCharCode(10)</code></a> that convert numbers to equal ASCII character. This function can accept multiple numbers and join all the characters then return the string. Example:</p>\n\n<pre><code>String.fromCharCode(65,66,67); // returns 'ABC'\n</code></pre>\n\n<p>Here is a quick ASCII characters reference:</p>\n\n<pre><code>{\n\"31\": \"\", \"32\": \" \", \"33\": \"!\", \"34\": \"\\\"\", \"35\": \"#\", \n\"36\": \"$\", \"37\": \"%\", \"38\": \"&\", \"39\": \"'\", \"40\": \"(\", \n\"41\": \")\", \"42\": \"*\", \"43\": \"+\", \"44\": \",\", \"45\": \"-\", \n\"46\": \".\", \"47\": \"/\", \"48\": \"0\", \"49\": \"1\", \"50\": \"2\", \n\"51\": \"3\", \"52\": \"4\", \"53\": \"5\", \"54\": \"6\", \"55\": \"7\", \n\"56\": \"8\", \"57\": \"9\", \"58\": \":\", \"59\": \";\", \"60\": \"<\", \n\"61\": \"=\", \"62\": \">\", \"63\": \"?\", \"64\": \"@\", \"65\": \"A\", \n\"66\": \"B\", \"67\": \"C\", \"68\": \"D\", \"69\": \"E\", \"70\": \"F\", \n\"71\": \"G\", \"72\": \"H\", \"73\": \"I\", \"74\": \"J\", \"75\": \"K\", \n\"76\": \"L\", \"77\": \"M\", \"78\": \"N\", \"79\": \"O\", \"80\": \"P\", \n\"81\": \"Q\", \"82\": \"R\", \"83\": \"S\", \"84\": \"T\", \"85\": \"U\", \n\"86\": \"V\", \"87\": \"W\", \"88\": \"X\", \"89\": \"Y\", \"90\": \"Z\", \n\"91\": \"[\", \"92\": \"\\\\\", \"93\": \"]\", \"94\": \"^\", \"95\": \"_\", \n\"96\": \"`\", \"97\": \"a\", \"98\": \"b\", \"99\": \"c\", \"100\": \"d\", \n\"101\": \"e\", \"102\": \"f\", \"103\": \"g\", \"104\": \"h\", \"105\": \"i\", \n\"106\": \"j\", \"107\": \"k\", \"108\": \"l\", \"109\": \"m\", \"110\": \"n\", \n\"111\": \"o\", \"112\": \"p\", \"113\": \"q\", \"114\": \"r\", \"115\": \"s\", \n\"116\": \"t\", \"117\": \"u\", \"118\": \"v\", \"119\": \"w\", \"120\": \"x\", \n\"121\": \"y\", \"122\": \"z\", \"123\": \"{\", \"124\": \"|\", \"125\": \"}\", \n\"126\": \"~\", \"127\": \"\"\n}\n</code></pre>\n"
},
{
"answer_id": 21861724,
"author": "Marco Altieri",
"author_id": 824846,
"author_profile": "https://Stackoverflow.com/users/824846",
"pm_score": 6,
"selected": false,
"text": "<p>If you have only one char and not a string, you can use:</p>\n<pre><code>'\\n'.charCodeAt();\n'\\n'.codePointAt();\n</code></pre>\n<p>omitting the 0...</p>\n<p>It used to be significantly slower than <code>'n'.charCodeAt(0)</code>, but I've tested it now and I do not see any difference anymore (executed 10 billions times with and without the 0). Tested for performance only in Chrome and Firefox.</p>\n"
},
{
"answer_id": 22173154,
"author": "Francisco Presencia",
"author_id": 938236,
"author_profile": "https://Stackoverflow.com/users/938236",
"pm_score": 5,
"selected": false,
"text": "<p>While the other answers are right, I prefer this way:</p>\n\n<pre><code>function ascii (a) { return a.charCodeAt(0); }\n</code></pre>\n\n<p>Then, to use it, simply:</p>\n\n<pre><code>var lineBreak = ascii(\"\\n\");\n</code></pre>\n\n<p>I am using this for a small shortcut system:</p>\n\n<pre><code>$(window).keypress(function(event) {\n if (event.ctrlKey && event.which == ascii(\"s\")) {\n savecontent();\n }\n // ...\n });\n</code></pre>\n\n<p>And you can even use it inside map() or other methods:</p>\n\n<pre><code>var ints = 'ergtrer'.split('').map(ascii);\n</code></pre>\n"
},
{
"answer_id": 30887763,
"author": "Filip Dupanović",
"author_id": 44041,
"author_profile": "https://Stackoverflow.com/users/44041",
"pm_score": 5,
"selected": false,
"text": "<p>For those that want to get a sum of all the ASCII codes for a string:</p>\n<pre><code>'Foobar'\n .split('')\n .map(char => char.charCodeAt(0))\n .reduce((current, previous) => previous + current)\n</code></pre>\n<p>Or, ES6:</p>\n<pre><code>[...'Foobar']\n .map(char => char.charCodeAt(0))\n .reduce((current, previous) => previous + current)\n</code></pre>\n"
},
{
"answer_id": 34821258,
"author": "maioman",
"author_id": 2417031,
"author_profile": "https://Stackoverflow.com/users/2417031",
"pm_score": 2,
"selected": false,
"text": "<p>For supporting all UTF-16 (also <a href=\"http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane\" rel=\"nofollow\">non-BMP/supplementary characters</a>) from ES6 the <a href=\"https://tc39.github.io/ecma262/#sec-string.prototype.charcodeat\" rel=\"nofollow\">string.codePointAt()</a> method is available;</p>\n\n<p>This method is an improved version of charCodeAt which could support only unicode codepoints < 65536 ( 2<sup>16</sup> - a single 16bit ) .</p>\n"
},
{
"answer_id": 40700617,
"author": "Steven de Salas",
"author_id": 448568,
"author_profile": "https://Stackoverflow.com/users/448568",
"pm_score": 3,
"selected": false,
"text": "<p>JavaScript stores strings as <code>UTF-16</code> (double byte) so if you want to ignore the second byte just strip it out with a bitwise <code>&</code> operator on <code>0000000011111111</code> (ie 255):</p>\n\n<pre><code>'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0 \n'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0 \n'✓'.charCodeAt(0) & 255 === 19; // because '✓' = 19 39\n</code></pre>\n"
},
{
"answer_id": 44431682,
"author": "Keshav Gera",
"author_id": 5316872,
"author_profile": "https://Stackoverflow.com/users/5316872",
"pm_score": 2,
"selected": false,
"text": "<p>You can enter a character and get Ascii Code Using this Code</p>\n\n<p>For Example Enter a Character Like A \nYou Get Ascii Code 65</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function myFunction(){\r\n var str=document.getElementById(\"id1\");\r\n if (str.value==\"\") {\r\n str.focus();\r\n return;\r\n }\r\n var a=\"ASCII Code is == > \";\r\ndocument.getElementById(\"demo\").innerHTML =a+str.value.charCodeAt(0);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Check ASCII code</p>\r\n\r\n<p>\r\n Enter any character: \r\n <input type=\"text\" id=\"id1\" name=\"text1\" maxLength=\"1\"> </br>\r\n</p>\r\n\r\n<button onclick=\"myFunction()\">Get ASCII code</button>\r\n\r\n<p id=\"demo\" style=\"color:red;\"></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 58568127,
"author": "Ibrahim Lawal",
"author_id": 671568,
"author_profile": "https://Stackoverflow.com/users/671568",
"pm_score": 4,
"selected": false,
"text": "<p>To ensure full Unicode support and reversibility, consider using:</p>\n\n<pre><code>'\\n'.codePointAt(0);\n</code></pre>\n\n<p>This will ensure that when testing characters over the UTF-16 limit, you will get their true code point value.</p>\n\n<p>e.g.</p>\n\n<pre><code>''.codePointAt(0); // 68181\nString.fromCodePoint(68181); // ''\n\n''.charCodeAt(0); // 55298\nString.fromCharCode(55298); // '�'\n</code></pre>\n"
},
{
"answer_id": 62300522,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>str.charCodeAt(index)\n</code></pre>\n<p>Using <code>charCodeAt()</code>\nThe following example returns 65, the Unicode value for <code>A</code>.</p>\n<p><code>'ABC'.charCodeAt(0)</code> <em><strong>// returns 65</strong></em></p>\n"
},
{
"answer_id": 66281755,
"author": "Roko C. Buljan",
"author_id": 383904,
"author_profile": "https://Stackoverflow.com/users/383904",
"pm_score": 2,
"selected": false,
"text": "<p>To convert a String to a cumulative number:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const stringToSum = str => [...str||\"A\"].reduce((a, x) => a += x.codePointAt(0), 0);\n\nconsole.log(stringToSum(\"A\")); // 65\nconsole.log(stringToSum(\"Roko\")); // 411\nconsole.log(stringToSum(\"Stack Overflow\")); // 1386</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Use case:</h2>\n<p>Say you want to generate different background colors depending on a username:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const stringToSum = str => [...str||\"A\"].reduce((a, x) => a += x.codePointAt(0), 0);\n\nconst UI_userIcon = user => {\n const hue = (stringToSum(user.name) - 65) % 360; // \"A\" = hue: 0\n console.log(`Hue: ${hue}`);\n return `<div class=\"UserIcon\" style=\"background:hsl(${hue}, 80%, 60%)\" title=\"${user.name}\">\n <span class=\"UserIcon-letter\">${user.name[0].toUpperCase()}</span>\n </div>`;\n};\n\n[\n {name:\"A\"},\n {name:\"Amanda\"},\n {name:\"amanda\"},\n {name:\"Anna\"},\n].forEach(user => {\n document.body.insertAdjacentHTML(\"beforeend\", UI_userIcon(user));\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.UserIcon {\n width: 4em;\n height: 4em;\n border-radius: 4em;\n display: inline-flex;\n justify-content: center;\n align-items: center;\n}\n\n.UserIcon-letter {\n font: 700 2em/0 sans-serif;\n color: #fff;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68711802,
"author": "Vladimir Bushma",
"author_id": 7164061,
"author_profile": "https://Stackoverflow.com/users/7164061",
"pm_score": 3,
"selected": false,
"text": "<p>Converting string into array(stream) of UTF-8:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const str_to_arr_of_UTF8 = new TextEncoder().encode("Adfgdfs");\n// [65, 100, 102, 103, 100, 102, 115]\n</code></pre>\n<p><strong>Note</strong>: ASCII is a subset of UTF-8, so this is a universal solution</p>\n"
},
{
"answer_id": 69385623,
"author": "menomanabdulla",
"author_id": 7620847,
"author_profile": "https://Stackoverflow.com/users/7620847",
"pm_score": 0,
"selected": false,
"text": "<p>For those who want to get a sum of all the ASCII codes for a string with average value:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ASCIIAverage = (str) =>Math.floor(str.split('').map(item => item.charCodeAt(0)).reduce((prev,next) => prev+next)/str.length)\n\nconsole.log(ASCIIAverage('Hello World!'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69583492,
"author": "simlev",
"author_id": 7659430,
"author_profile": "https://Stackoverflow.com/users/7659430",
"pm_score": 1,
"selected": false,
"text": "<p>Expanding on the comments by <a href=\"https://stackoverflow.com/users/13508/%C3%81lvaro-gonz%C3%A1lez\">Álvaro González</a> and others, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt\" rel=\"nofollow noreferrer\">charCodeAt</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt\" rel=\"nofollow noreferrer\">codePointAt</a> are mighty fine if you are working with the 128 original ASCII characters only (codes 0 to 127). Outside of this range, <strong>the code is dependent on the character set</strong>, and you need a charset conversion before calculating it if you want the result to make sense.</p>\n<p>Let's take the Euro sign as an example: <code>'€'.codePointAt(0)</code> returns <code>8364</code>, which is well outside the 0-127 range and is relative to the UTF-16 (or <a href=\"https://www.charset.org/utf-8/9\" rel=\"nofollow noreferrer\">UTF-8</a>) charset.</p>\n<p>I was porting a Visual Basic program, and noticed that it made use of the <code>Asc</code> function to get the character code. Obviously from its point of view, it would return the character code in the <a href=\"https://www.charset.org/charsets/windows-1252\" rel=\"nofollow noreferrer\">Windows-1252</a> character set. To be sure to obtain the same number, I need to convert the string charset and then calculate the code.</p>\n<p>Pretty straightforward e.g. in Python: <code>ord('€'.encode('Windows-1252'))</code>.<br />\nTo achieve the same in Javascript, however, I had to resort to buffers and a <a href=\"https://github.com/ashtuchkin/iconv-lite\" rel=\"nofollow noreferrer\">conversion library</a>:</p>\n<pre><code>iconv = require('iconv-lite');\nbuf = iconv.encode("€", 'win1252');\nbuf.forEach(console.log);\n</code></pre>\n"
},
{
"answer_id": 69671681,
"author": "tejas_spy007",
"author_id": 2873677,
"author_profile": "https://Stackoverflow.com/users/2873677",
"pm_score": 0,
"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-html lang-html prettyprint-override\"><code>charCodeAt(0);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Above code works in most cases, however there is a catch when working with words to find a ranking based on above code. For example, aa would give a ranking of 97+97 = 194 (actual would be 1+1 = 2) whereas w would give 119 (actual would be 23) which makes aa > w.\nTo fix this subtract 96 from above result, to start he positioning from 1.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>charCodeAt(0) - 96;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n"
},
{
"answer_id": 72073372,
"author": "claypooj",
"author_id": 13871578,
"author_profile": "https://Stackoverflow.com/users/13871578",
"pm_score": 0,
"selected": false,
"text": "<p>As others have pointed out, ASCII only covers 128 characters (including non-printing characters). Unicode includes ASCII as its first 128 characters for the purpose of backwards compatibility, but it also includes far more characters.</p>\n<p>To get <em>only</em> ASCII character codes as integers, you can do the following:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function ascii_code (character) {\n \n // Get the decimal code\n let code = character.charCodeAt(0);\n\n // If the code is 0-127 (which are the ASCII codes,\n if (code < 128) {\n \n // Return the code obtained.\n return code;\n\n // If the code is 128 or greater (which are expanded Unicode characters),\n }else{\n\n // Return -1 so the user knows this isn't an ASCII character.\n return -1;\n };\n};\n</code></pre>\n<p>If you're looking for <em>only</em> the ASCII characters in a string (for say, slugifying a string), you could do something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function ascii_out (str) {\n // Takes a string and removes non-ASCII characters.\n\n // For each character in the string,\n for (let i=0; i < str.length; i++) {\n\n // If the character is outside the first 128 characters (which are the ASCII\n // characters),\n if (str.charCodeAt(i) > 127) {\n\n // Remove this character and all others like it.\n str = str.replace(new RegExp(str[i],"g"),'');\n\n // Decrement the index, since you just removed the character you were on.\n i--;\n };\n };\n return str\n};\n</code></pre>\n<h3>Sources</h3>\n<ul>\n<li><a href=\"https://www.geeksforgeeks.org/ascii-vs-unicode/#:%7E:text=Unicode%20is%20the%20universal%20character,encoding%20standard%20for%20electronic%20communication\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/ascii-vs-unicode/#:~:text=Unicode%20is%20the%20universal%20character,encoding%20standard%20for%20electronic%20communication</a>.</li>\n<li><a href=\"https://www.w3schools.com/jsref/jsref_charcodeat.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/jsref/jsref_charcodeat.asp</a></li>\n</ul>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
]
| How can I convert a character to its ASCII code using JavaScript?
For example:
>
> get 10 from "\n".
>
>
> | ```
"\n".charCodeAt(0);
``` |
94,053 | <p>For ASP.Net application deployment what type of information (if any) are you storing in the machine.config? </p>
<p>If you're not using it, how are you managing environment specific configuration settings that may change for each environment?</p>
<p>I'm looking for some "best practices" and the benefits/pitfalls of each. We're about to deploy a brand new application to production in two months and I've got some latitude in these types of decisions. I want to make sure that I'm approaching things in the best way possible and attempting to avoid shooting myself in the foot at a later date. </p>
<p>FYI We're using it (machine.config) currently for just the DB connection information and storing all other variables that might change in a config table in the database.</p>
| [
{
"answer_id": 94152,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 2,
"selected": false,
"text": "<p>I use machine.config for not just ASP.NET, but for overall config as well. I implemented a hash algorithm (Tiger) in C# and wanted it to be available via machine request. So, registered my assembly in the GAC and added the following to machine.config:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <mscorlib>\n <cryptographySettings>\n <cryptoNameMapping>\n <cryptoClasses>\n <cryptoClass Tiger192=\"Jcs.Tiger.Tiger192, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4\"/>\n <cryptoClass Tiger160=\"Jcs.Tiger.Tiger160, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4\"/>\n <cryptoClass Tiger128=\"Jcs.Tiger.Tiger128, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4\"/>\n </cryptoClasses>\n <nameEntry name=\"Tiger\" class=\"Tiger192\"/>\n <nameEntry name=\"TigerFull\" class=\"Tiger192\"/>\n <nameEntry name=\"Tiger192\" class=\"Tiger192\"/>\n <nameEntry name=\"Tiger160\" class=\"Tiger160\"/>\n <nameEntry name=\"Tiger128\" class=\"Tiger128\"/>\n <nameEntry name=\"System.Security.Cryptography.HashAlgorithm\" class=\"Tiger192\"/>\n </cryptoNameMapping>\n <oidMap>\n <oidEntry OID=\"1.3.6.1.4.1.11591.12.2\" name=\"Jcs.Tiger.Tiger192\"/>\n </oidMap>\n </cryptographySettings>\n </mscorlib>\n</configuration>\n</code></pre>\n\n<p>This allows my code to look like so:</p>\n\n<pre><code>using (var h1 = HashAlgorithm.Create(\"Tiger192\"))\n{\n ...\n}\n</code></pre>\n\n<p>and there's no dependency on the Jcs.Tiger.dll assembly in my code at all, hard or soft.</p>\n"
},
{
"answer_id": 94167,
"author": "Thomas Jespersen",
"author_id": 8547,
"author_profile": "https://Stackoverflow.com/users/8547",
"pm_score": 4,
"selected": true,
"text": "<p>We are considering using machine.config to add one key for the environment, and then have one section in the web.config which is excactly the same for all environments. This way we can do a \"real\" XCopy deployment.</p>\n\n<p>E.g. in the machine.config for every computer (local dev workstations, stage servers, build servers, production servers), we'll add the following:</p>\n\n<pre><code><appSettings>\n <add key=\"Environment\" value=\"Staging\"/>\n</appSettings>\n</code></pre>\n\n<p>Then, any configuration element that is environment-specific gets the environment appended, like so:</p>\n\n<pre><code><connectionStrings>\n <add name=\"Customers.Staging\" provider=\"...\" connectionString=\"...\"/>\n</connectionStrings>\n<appSettings>\n <add key=\"NTDomain.Staging\" value=\"test.mydomain.com\"/>\n</appSettings>\n</code></pre>\n\n<p>One problem that we don't have a solution for is how to enable say tracing in web.config for debugging environment and not for live environment.</p>\n\n<p>Another problem is that the live connectionstring incl. username and password is now in your Source Control system. This is however not a problem for us.</p>\n"
},
{
"answer_id": 94439,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 3,
"selected": false,
"text": "<p>We use machine.config on our production server to set/remove specific configuration that are important for production and we never want to forget to set them.</p>\n\n<p>These are the 2 most important:</p>\n\n<pre><code><system.web>\n <deployment retail=\"true\" />\n <healthMonitoring enabled=\"true\" />\n</system.web> \n</code></pre>\n"
},
{
"answer_id": 95857,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 3,
"selected": false,
"text": "<p>If you load balance your servers, you ABSOLUTELY have to make sure the machine key is the same on all the servers. Viewstate is supposed to be server agnostic, but it is not, so you'll get viewstate corruption errors if the machine key is not the same across servers.</p>\n\n<pre><code><machineKey validationKey='A130E240DF1C49E2764EF8A86CEDCBB11274E5298A130CA08B90EED016C0\n14CEAE1D86344C29E67E99DF83347E43820050A2B9C9FC89E0574BF3394B6D0401A9'\ndecryptionKey='2CC37FFA8D14925B9CBCC0E3B1506F35066FEF33FEB4ADC8' validation='SHA1'/>\n</code></pre>\n\n<p>From: <a href=\"http://www.c-sharpcorner.com/UploadFile/gopenath/Page107182007032219AM/Page1.aspx\" rel=\"noreferrer\">http://www.c-sharpcorner.com/UploadFile/gopenath/Page107182007032219AM/Page1.aspx</a></p>\n\n<p>PS sure you can enableViewStateMAC=\"false\", but don't.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| For ASP.Net application deployment what type of information (if any) are you storing in the machine.config?
If you're not using it, how are you managing environment specific configuration settings that may change for each environment?
I'm looking for some "best practices" and the benefits/pitfalls of each. We're about to deploy a brand new application to production in two months and I've got some latitude in these types of decisions. I want to make sure that I'm approaching things in the best way possible and attempting to avoid shooting myself in the foot at a later date.
FYI We're using it (machine.config) currently for just the DB connection information and storing all other variables that might change in a config table in the database. | We are considering using machine.config to add one key for the environment, and then have one section in the web.config which is excactly the same for all environments. This way we can do a "real" XCopy deployment.
E.g. in the machine.config for every computer (local dev workstations, stage servers, build servers, production servers), we'll add the following:
```
<appSettings>
<add key="Environment" value="Staging"/>
</appSettings>
```
Then, any configuration element that is environment-specific gets the environment appended, like so:
```
<connectionStrings>
<add name="Customers.Staging" provider="..." connectionString="..."/>
</connectionStrings>
<appSettings>
<add key="NTDomain.Staging" value="test.mydomain.com"/>
</appSettings>
```
One problem that we don't have a solution for is how to enable say tracing in web.config for debugging environment and not for live environment.
Another problem is that the live connectionstring incl. username and password is now in your Source Control system. This is however not a problem for us. |
94,074 | <p>I'm using wget to connect to a secure site like this:</p>
<p><code>wget -nc -i inputFile</code></p>
<p>where inputeFile consists of URLs like this:</p>
<p><code><a href="https://clientWebsite.com/TheirPageName.asp?orderValue=1.00&merchantID=36&programmeID=92&ref=foo&Ofaz=0" rel="nofollow noreferrer">https://clientWebsite.com/TheirPageName.asp?orderValue=1.00&merchantID=36&programmeID=92&ref=foo&Ofaz=0</a></code></p>
<p>This page returns a small gif file. For some reason, this is taking around 2.5 minutes. When I paste the same URL into a browser, I get back a response within seconds. </p>
<p>Does anyone have any idea what could be causing this?</p>
<p>The version of wget, by the way, is "GNU Wget 1.9+cvs-stable (Red Hat modified)"</p>
| [
{
"answer_id": 94100,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>Try forging your UserAgent</p>\n\n<pre><code>-U \"Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-GB; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1\" \n</code></pre></li>\n<li><p>Disable Ceritificate Checking ( slow ) </p>\n\n<pre><code>--no-check-certificate\n</code></pre></li>\n<li><p>Debug whats happening by enabling verbostity</p>\n\n<pre><code>-v\n</code></pre></li>\n<li><p>Eliminate need for DNS lookups: </p>\n\n<p>Hardcode thier IP address in your HOSTS file </p>\n\n<pre><code>/etc/hosts \n123.122.121.120 foo.bar.com\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 94113,
"author": "Brian Kelly",
"author_id": 5079,
"author_profile": "https://Stackoverflow.com/users/5079",
"pm_score": 0,
"selected": false,
"text": "<p>Is the certificate on the client site valid? You may want to specify --no-certificate-check if it is a self-signed certificate.</p>\n\n<p><a href=\"http://www.gnu.org/software/wget/manual/wget.html#HTTPS-_0028SSL_002fTLS_0029-Options\" rel=\"nofollow noreferrer\">HTTPS (SSL/TLS) Options for wget</a></p>\n"
},
{
"answer_id": 94189,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried profiling the requests using strace/dtrace/truss (depending on your platform)?</p>\n\n<p>There are a wide variety of issues that could be causing this. What version of openssl is being used by wget - there could be an issue there. What OS is this running on (full information would be useful there).</p>\n\n<p>There could be some form of download slowdown being enforced due to the agent ID being passed by wget implemented on the site to reduce the effects of spiders.</p>\n\n<p>Is wget performing full certificate validation? Have you tried using --no-check-certificate?</p>\n"
},
{
"answer_id": 1676013,
"author": "sdot257",
"author_id": 166836,
"author_profile": "https://Stackoverflow.com/users/166836",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is a year old but this exact problem plagued us for days.\nTurns out it was our DNS server but I got around it by <a href=\"https://wiki.debian.org/DebianIPv6#How_to_turn_off_IPv6\" rel=\"nofollow noreferrer\">disabling IP6</a> on my box.</p>\n\n<p>You can test it out prior to making the system change by adding \"--inet4-only\" to the end of the command (w/o quotes).</p>\n"
},
{
"answer_id": 70194890,
"author": "Teddy",
"author_id": 10025369,
"author_profile": "https://Stackoverflow.com/users/10025369",
"pm_score": 0,
"selected": false,
"text": "<p>One effective solution is to delete <code>https:\\\\</code>.\nThis accelerate my download for around 100 times.</p>\n<p>For instance, you wanna download via:</p>\n<pre><code>wget https://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2\n</code></pre>\n<p>You can use the following command alternatively to speed up.</p>\n<pre><code>wget data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm using wget to connect to a secure site like this:
`wget -nc -i inputFile`
where inputeFile consists of URLs like this:
`<https://clientWebsite.com/TheirPageName.asp?orderValue=1.00&merchantID=36&programmeID=92&ref=foo&Ofaz=0>`
This page returns a small gif file. For some reason, this is taking around 2.5 minutes. When I paste the same URL into a browser, I get back a response within seconds.
Does anyone have any idea what could be causing this?
The version of wget, by the way, is "GNU Wget 1.9+cvs-stable (Red Hat modified)" | 1. Try forging your UserAgent
```
-U "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-GB; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1"
```
2. Disable Ceritificate Checking ( slow )
```
--no-check-certificate
```
3. Debug whats happening by enabling verbostity
```
-v
```
4. Eliminate need for DNS lookups:
Hardcode thier IP address in your HOSTS file
```
/etc/hosts
123.122.121.120 foo.bar.com
``` |
94,123 | <p>I'm working on a webapp, and every so often we run into situations where pages will load without applying CSS. This problem has shown up in IE6, IE7, Safari 3, and FF3.</p>
<p>A page refresh will always fix the problem.</p>
<p>There are 3 CSS files loaded, all within the same style block using @import:</p>
<pre><code><STYLE type="text/css">
@import url([base css file]);
@import url([skin css file]);
@import url([generated css path]);
</STYLE>
</code></pre>
<p>In any situation when we take the time to examine the html source, nothing is out of the ordinary. Access logs seem normal as well - we're getting HTTP 304 responses for the static CSS files whenever they are requested, and an HTTP 200 response for our generated CSS.</p>
<p>The mimetype is text/css for the css files and the generated css. We're using an iPlanet server, which forwards requests to a Tomcat server.</p>
<p>davebug asked: </p>
<blockquote>
<p>Is it always the same css file not loading, or is the problem with all of them, evenly?</p>
</blockquote>
<p>None of the CSS files load. Any styles defined within the HTML work fine, but nothing in any of the CSS files works when this happens.</p>
| [
{
"answer_id": 94166,
"author": "Joe Van Dyk",
"author_id": 17076,
"author_profile": "https://Stackoverflow.com/users/17076",
"pm_score": -1,
"selected": false,
"text": "<p>Use ab or httperf or curl or something to repeatedly load the CSS files from the webserver. Perhaps it's not consistently serving the pages.</p>\n"
},
{
"answer_id": 94272,
"author": "Jason Morrison",
"author_id": 15098,
"author_profile": "https://Stackoverflow.com/users/15098",
"pm_score": 2,
"selected": false,
"text": "<p>if it happens often enough that you're able to see it in your browser, try intalling the Live http headers Firefox extension or the Tamper Data extension, and watch the response headers as they are seen by the browser.</p>\n"
},
{
"answer_id": 94786,
"author": "Matt Dawdy",
"author_id": 232,
"author_profile": "https://Stackoverflow.com/users/232",
"pm_score": 0,
"selected": false,
"text": "<p>Examining the headers is a good idea, but I imagine all you will learn from them is that the server didn't respond to a request every once in a while.</p>\n\n<p>I see this happen all the time on the net. Images won't load until you refresh, css is messed up, etc. All of the situations are solved by a refresh.</p>\n\n<p>I imagine one way you could \"fix\" this, maybe, is by specifying in your cs file a url for an image for some element. Then, on page load in javascript, get that element and see if that image has loaded. If not, then have the page reload itself.</p>\n\n<p>Seems pretty exotic, but that's the only idea I had...</p>\n"
},
{
"answer_id": 98158,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 3,
"selected": true,
"text": "<p>I've had a similar thing happen that I was able to fix by including a base style sheet first using the \"link rel\" method rather than \"@import\". i.e. move your [base css file] inclusion to:</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"[base css file]\" type=\"text/css\" media=\"screen\" />\n</code></pre>\n\n<p>and put it before the others.</p>\n"
},
{
"answer_id": 8058417,
"author": "Ciummo",
"author_id": 1036652,
"author_profile": "https://Stackoverflow.com/users/1036652",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know why, but in my case if the page is loaded from an action with the path like <code>/ActionName</code>, I see this problem.</p>\n\n<p>But if I change it (for example) to <code>/reservedArea/ActionName</code> or <code>/aPath/ActionName</code> it works :/</p>\n\n<p>It's crazy...</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17887/"
]
| I'm working on a webapp, and every so often we run into situations where pages will load without applying CSS. This problem has shown up in IE6, IE7, Safari 3, and FF3.
A page refresh will always fix the problem.
There are 3 CSS files loaded, all within the same style block using @import:
```
<STYLE type="text/css">
@import url([base css file]);
@import url([skin css file]);
@import url([generated css path]);
</STYLE>
```
In any situation when we take the time to examine the html source, nothing is out of the ordinary. Access logs seem normal as well - we're getting HTTP 304 responses for the static CSS files whenever they are requested, and an HTTP 200 response for our generated CSS.
The mimetype is text/css for the css files and the generated css. We're using an iPlanet server, which forwards requests to a Tomcat server.
davebug asked:
>
> Is it always the same css file not loading, or is the problem with all of them, evenly?
>
>
>
None of the CSS files load. Any styles defined within the HTML work fine, but nothing in any of the CSS files works when this happens. | I've had a similar thing happen that I was able to fix by including a base style sheet first using the "link rel" method rather than "@import". i.e. move your [base css file] inclusion to:
```
<link rel="stylesheet" href="[base css file]" type="text/css" media="screen" />
```
and put it before the others. |
94,141 | <p>I have the following script, where the first and third <code>document.writeline</code> are static and <strong>the second is generated</strong>:</p>
<pre><code><script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");
</script>
</code></pre>
<p>Firefox and Chrome will display <em>before</em>, <em>during</em> and <em>after</em>, while Internet Explorer first shows <em>during</em> and only then does it show <em>before</em> and <em>after</em>.</p>
<p>I've come across <a href="http://www.elctech.com/blog/nesting-document-write" rel="noreferrer">an article that states</a> that I'm not the first to encounter this, but that hardly makes me feel any better.</p>
<p><strong>Does anyone know how I can set the order to be deterministic in all browsers, or hack IE to work like all the other, sane browsers do?</strong></p>
<p><strong>Caveats</strong>: The code snippet is a very simple repro. It is generated on the server and the second script is the only thing that changes. It's a long script and the reason there are two scripts before and after it are so that the browser will cache them and the dynamic part of the code will be as small as possible. It may also appears many times in the same page with different generated code.</p>
| [
{
"answer_id": 94328,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 1,
"selected": false,
"text": "<p>Slides 25/26 of <a href=\"http://sites.google.com/site/io/even-faster-web-sites\" rel=\"nofollow noreferrer\">this presentation</a> talk about the characteristics of different methods for inserting scripts. It suggests that IE is the only browser that will execute those scripts in order. All other browsers will execute them in the order that they finish loading. Even IE won't execute them in order if one or more have inline js instead of a src.</p>\n\n<p>One of the methods suggested is to insert a new DOM element:</p>\n\n<pre><code>var se1 = document.createElement('script');\nse1.src = 'a.js';\n\nvar se2 = document.createElement('script');\nse2.src = 'b.js';\n\nvar se3 = document.createElement('script');\nse3.src = 'c.js';\n\nvar head = document.getElementsByTagName('head')[0]\nhead.appendChild(se1);\nhead.appendChild(se2);\nhead.appendChild(se3);\n</code></pre>\n\n<p>To make the second script section generated you could use a script to generate that content and pass the parameters:</p>\n\n<pre><code>se2.src = 'generateScript.php?params=' + someParam;\n</code></pre>\n\n<p>EDIT: In spite of what the article I sited says, my testing suggests that most browsers will execute your document.write scripts in order if they each have a src, so while I think the method above is preferred, you could do this as well:</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script type='text/javascript' src='before.js'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='during.php?params=\" + params + \"'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='after.js'><\\/sc\" + \"ript>\");\n</script>\n</code></pre>\n\n<p>EDIT AGAIN (response to comments to myself and others): You are already generating the script on your page. Whatever you are doing can be moved to another server-side script that generates the same block of code. If you need parameters on your page then pass them to the script in the query string.</p>\n\n<p>Also, you can use this same method if, as you suggest, you are generating the inline script multiple times:</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script type='text/javascript' src='before.js'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='during.php?params=\" + params1 + \"'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='during.php?params=\" + params2 + \"'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='during.php?params=\" + params3 + \"'><\\/sc\" + \"ript>\");\ndocument.write(\"<script type='text/javascript' src='after.js'><\\/sc\" + \"ript>\");\n</script>\n</code></pre>\n\n<p>However, this is starting to look as though you are approaching this the wrong way. If you are generating a large block of code multiple times then you should probably be replacing it with a single js function and calling it with different params instead...</p>\n"
},
{
"answer_id": 94503,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 1,
"selected": false,
"text": "<p>Okay...during...</p>\n\n<pre><code>// During.js\nduring[fish]();\n</code></pre>\n\n<p>after...</p>\n\n<pre><code>// After.js\nalert(\"After\");\nfish++\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code><!-- some html -->\n<script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script language='javascript' type='text/javascript' src='before.js'></sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript'>during[\" + fish + \"] = function(){alert('During!' + fish);}</sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='during.js'></sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='after.js'></sc\" + \"ript>\");\n</script>\n<!-- some other html -->\n<script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script language='javascript' type='text/javascript' src='before.js'></sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript'>during[\" + fish + \"] = function(){alert('During!' + fish);}</sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='during.js'></sc\" + \"ript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='after.js'></sc\" + \"ript>\");\n</script>\n</code></pre>\n\n<p>I'm inclined to agree about the way this is starting to smell, though. In particular, why couldn't you codegen the \"during\" into a dynamically created js file, and insert that?</p>\n\n<p>Note that the dynamically generated script goes <strong>inside</strong> the function in the <strong>second</strong> document.write.<br>\nTested in FF2, IE7</p>\n"
},
{
"answer_id": 94744,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": 5,
"selected": false,
"text": "<p>No, this is the behavior of Internet Explorer.</p>\n\n<p>If you attach scripts dynamically, IE, Firefox, and Chrome will all download the scripts in an asynchronous manner.</p>\n\n<p>Firefox and Chrome will wait till all of the async requests return and then will execute the scripts in the order that they are attached in the DOM but IE executes the scripts in the order that they are returned over the wire.</p>\n\n<p>Since the alert takes less time to \"retrieve\" than an external javascript file, that likely explains the behavior that you are seeing.</p>\n\n<p>From Kristoffer Henriksson's <a href=\"http://blogs.msdn.com/kristoffer/archive/2006/12/22/loading-javascript-files-in-parallel.aspx\" rel=\"noreferrer\">post on the subject of asynchronous script loading</a>:</p>\n\n<blockquote>\n <p>In this scenario IE and Firefox will\n download both scripts but Internet\n Explorer will also execute them in the\n order they finish downloading in\n whereas Firefox downloads them\n asynchronously but still executes them\n in the order they are attached in the\n DOM.</p>\n \n <p>In Internet Explorer this means your\n scripts cannot have dependancies on\n one another as the execution order\n will vary depending on network\n traffic, caches, etc.</p>\n</blockquote>\n\n<p>Consider using a Javascript loader. It will let you specify script dependencies and order of execution while also loading your scripts asynchronously for speed as well as smoothing out some of the browser differences.</p>\n\n<p>This is a pretty good overview of a few of them: <a href=\"http://www.netmagazine.com/features/essential-javascript-top-five-script-loaders\" rel=\"noreferrer\">Essential JavaScript: the top five script loaders</a>.</p>\n\n<p>I've used both RequireJS and LabJS. In my opinion, LabJS is a little less opinionated.</p>\n"
},
{
"answer_id": 100632,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Code to provide:</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script language='javascript' type='text/javascript'>function callGeneratedContent() { alert('during'); }<\\x2Fscript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='before.js'><\\x2Fscript>\");\ndocument.write(\"<script language='javascript' type='text/javascript' src='after.js'><\\x2Fscript>\");\n</script>\n</code></pre>\n\n<p>In before.js:</p>\n\n<pre><code>alert(\"Before\");\ncallGeneratedContent();\n</code></pre>\n\n<p>In after.js:</p>\n\n<pre><code>alert(\"After\");\n</code></pre>\n\n<p>You have to put the generated line first, otherwise FF will complain because it executes before.js before seeing the function definition.</p>\n"
},
{
"answer_id": 101106,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 1,
"selected": false,
"text": "<p>You can force secuential execution by defining \"onload\" (or similar) events on the scripts and inject the next one in the event function.\nIt is not trivial, but there are plenty of examples out there, here is one.</p>\n\n<p><a href=\"http://www.phpied.com/javascript-include-ready-onload/\" rel=\"nofollow noreferrer\">http://www.phpied.com/javascript-include-ready-onload/</a></p>\n\n<p>I think popular libraries like jQuery or prototype can help with this.</p>\n"
},
{
"answer_id": 120165,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 4,
"selected": true,
"text": "<p>I've found an answer more to my liking:</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\ndocument.write(\"<script language='javascript' type='text/javascript' src='before.js'><\\/sc\" + \"ript>\");\ndocument.write(\"<script defer language='javascript' type='text/javascript'>alert('during');<\\/sc\" + \"ript>\");\ndocument.write(\"<script defer language='javascript' type='text/javascript' src='after.js'><\\/sc\" + \"ript>\");\n</script>\n</code></pre>\n\n<p>This will defer the loading of both <em>during</em> and <em>after</em> until the page has finished loading.</p>\n\n<p>I think this is as good as I can get. Hopefully, someone will be able to give a better answer.</p>\n"
},
{
"answer_id": 711448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>How about that:</p>\n\n<pre><code><script>\ndocument.write(\"<script src='before.js'><\\/script>\");\n</script>\n\n<script >\ndocument.write(\"<script>alert('during');<\\/script>\");\n</script>\n\n<script>\ndocument.write(\"<script src='after.js'><\\/script>\");\n</script>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4979/"
]
| I have the following script, where the first and third `document.writeline` are static and **the second is generated**:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");
</script>
```
Firefox and Chrome will display *before*, *during* and *after*, while Internet Explorer first shows *during* and only then does it show *before* and *after*.
I've come across [an article that states](http://www.elctech.com/blog/nesting-document-write) that I'm not the first to encounter this, but that hardly makes me feel any better.
**Does anyone know how I can set the order to be deterministic in all browsers, or hack IE to work like all the other, sane browsers do?**
**Caveats**: The code snippet is a very simple repro. It is generated on the server and the second script is the only thing that changes. It's a long script and the reason there are two scripts before and after it are so that the browser will cache them and the dynamic part of the code will be as small as possible. It may also appears many times in the same page with different generated code. | I've found an answer more to my liking:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");
</script>
```
This will defer the loading of both *during* and *after* until the page has finished loading.
I think this is as good as I can get. Hopefully, someone will be able to give a better answer. |
94,153 | <p>I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError:</p>
<pre><code>>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> f.write('foo')
>>> shutil.copy(f.name, 'bar.txt')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
shutil.copy(f.name, 'bar.txt')
File "C:\Python25\lib\shutil.py", line 80, in copy
copyfile(src, dst)
File "C:\Python25\lib\shutil.py", line 46, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'
>>>
</code></pre>
<p>Is this not intended when using the 'tempfile' library? Is there a better way to do this? (Maybe I am overlooking something very trivial)</p>
| [
{
"answer_id": 94206,
"author": "Hans Sjunnesson",
"author_id": 8683,
"author_profile": "https://Stackoverflow.com/users/8683",
"pm_score": 3,
"selected": false,
"text": "<p>You could always use <em>shutil.copyfileobj</em>, in your example:</p>\n\n<pre><code>new_file = open('bar.txt', 'rw')\nshutil.copyfileobj(f, new_file)\n</code></pre>\n"
},
{
"answer_id": 94339,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 6,
"selected": true,
"text": "<p>The file you create with <code>TemporaryFile</code> or <code>NamedTemporaryFile</code> is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use <code>mkstemp</code> instead (see the docs for <a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp\" rel=\"noreferrer\">tempfile</a>).</p>\n\n<pre><code>>>> import tempfile, shutil, os\n>>> fd, path = tempfile.mkstemp()\n>>> os.write(fd, 'foo')\n>>> os.close(fd)\n>>> shutil.copy(path, 'bar.txt')\n>>> os.remove(path)\n</code></pre>\n"
},
{
"answer_id": 109591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Starting from python 2.6 you can also use <code>NamedTemporaryFile</code> with the <code>delete=</code> option set to False. This way the temporary file will be accessible, even after you close it.</p>\n\n<p>Note that on Windows (NT and later) you cannot access the file a second time while it is still open. You have to close it before you can copy it. This is not true on Unix systems.</p>\n"
},
{
"answer_id": 9155528,
"author": "K Z",
"author_id": 853611,
"author_profile": "https://Stackoverflow.com/users/853611",
"pm_score": 5,
"selected": false,
"text": "<p>hop is right, and dF. is incorrect on why the error occurs.</p>\n\n<p>Since you haven't called <code>f.close()</code> yet, the file is <strong>not</strong> removed. </p>\n\n<p>The <a href=\"http://docs.python.org/library/tempfile.html#tempfile.NamedTemporaryFile\" rel=\"noreferrer\">doc</a> for <code>NamedTemporaryFile</code> says: </p>\n\n<blockquote>\n <p>Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). </p>\n</blockquote>\n\n<p>And for <code>TemporaryFile</code>:</p>\n\n<blockquote>\n <p>Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.</p>\n</blockquote>\n\n<p>Therefore, to persist a temporary file (on Windows), you can do the following:</p>\n\n<pre><code>import tempfile, shutil\nf = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\nf.write('foo')\nfile_name = f.name\nf.close()\nshutil.copy(file_name, 'bar.txt')\nos.remove(file_name)\n</code></pre>\n\n<p>The solution Hans Sjunnesson provided is also off, because <code>copyfileobj</code> only copies from file-like object to file-like object, not file name:</p>\n\n<blockquote>\n <p>shutil.copyfileobj(fsrc, fdst[, length])</p>\n \n <blockquote>\n <p>Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.</p>\n </blockquote>\n</blockquote>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
| I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError:
```
>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> f.write('foo')
>>> shutil.copy(f.name, 'bar.txt')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
shutil.copy(f.name, 'bar.txt')
File "C:\Python25\lib\shutil.py", line 80, in copy
copyfile(src, dst)
File "C:\Python25\lib\shutil.py", line 46, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'
>>>
```
Is this not intended when using the 'tempfile' library? Is there a better way to do this? (Maybe I am overlooking something very trivial) | The file you create with `TemporaryFile` or `NamedTemporaryFile` is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use `mkstemp` instead (see the docs for [tempfile](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp)).
```
>>> import tempfile, shutil, os
>>> fd, path = tempfile.mkstemp()
>>> os.write(fd, 'foo')
>>> os.close(fd)
>>> shutil.copy(path, 'bar.txt')
>>> os.remove(path)
``` |
94,154 | <p>I'm trying to configure the Quick Launch menu to only display the ancestors and descendant nodes of the currently select node. The menu also needs to display all the childern of the root node. More simply:</p>
<p>Given a site map of:</p>
<p><strong>RootSite</strong></p>
<p>---<strong>SubSite1</strong> = navigation set at "Display the current site, the navigation items below the current site, and the current site's siblings"</p>
<p>-----<strong>Heading1</strong> = navigation set at "Display the same navigation items as the parent site"</p>
<p>-------<strong>Page1</strong> = navigation set at "Display the same navigation items as the parent site"</p>
<p>-------<strong>Page2</strong> = navigation set at "Display the same navigation items as the parent site"</p>
<p>-----<strong>Heading2</strong> = navigation set at "Display the same navigation items as the parent site"</p>
<p>---<strong>SubSite2</strong> = navigation set at "Display the current site, the navigation items below the current site, and the current site's siblings"</p>
<p>-----<strong>Heading1</strong> = navigation set at "Display the same navigation items as the parent site"</p>
<p>SiteMapProvider configuration:</p>
<pre><code><PublishingNavigation:PortalSiteMapDataSource ID="SiteMapDS" Runat="server"
SiteMapProvider="CurrentNavSiteMapProvider" EnableViewState="true"
StartFromCurrentNode="true" ShowStartingNode="false"/>
</code></pre>
<p>The expected and actual behavior of the Quick Launch menu displayed at SubSite1 is:</p>
<p>---SubSite1</p>
<p>-----Heading1</p>
<p>-------Page1</p>
<p>-------Page2</p>
<p>-----Heading2</p>
<p>---SubSite2</p>
<p>The expected behavior of the menu after navigating to Heading1 of SubSite2:</p>
<p>---SubSite1</p>
<p>---SubSite2</p>
<p>-----Heading1</p>
<p>What I actually see after navigating to Heading1 of SubSite2:</p>
<p>---SubSite1</p>
<p>-----Heading1</p>
<p>-------Page1</p>
<p>-------Page2</p>
<p>-----Heading2</p>
<p>---SubSite2</p>
<p>-----Heading1</p>
<p>This does not match what I expect to see if I set the Heading1 navigation to "Display the
same navigation items as the parent site" and SubSite2 is set to "Display the current site, the navigation items below the current site, and the current site's siblings". I expect
Heading1 to inherit the navigation item of SubSite2 with the SubSite1 items collapsed from view. I've also played with the various
Trim... attributes without success. Any help will be greatly appreciated!</p>
| [
{
"answer_id": 98428,
"author": "Nat",
"author_id": 13813,
"author_profile": "https://Stackoverflow.com/users/13813",
"pm_score": 1,
"selected": false,
"text": "<p>I personally don't like the html that the default menu provides (table based layout).\nFortunately the SharePoint team has released the code for that <a href=\"http://blogs.msdn.com/ecm/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control-mossmenu-source-code-released.aspx\" rel=\"nofollow noreferrer\">control</a>. </p>\n\n<p>What we have done is to include that code in a project and have overridden the render method to do whatever we want. This give you the flexibility to define the exact relationship between parents that needs to be display as well as setting the styles on any divs you create.</p>\n\n<p>On the down side you are now coding, not configuring and a change needs to be made to the master page you are using to use the control.</p>\n\n<p>Worth it in my opinion. This is now a standard change we make for any site.</p>\n"
},
{
"answer_id": 129428,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 3,
"selected": true,
"text": "<p>I followed @Nat's guidance into the murky world Sharepoint webparts to achieve the behavior I described above. My approach was to roll my own version of the <a href=\"http://blogs.msdn.com/ecm/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control-mossmenu-source-code-released.aspx\" rel=\"nofollow noreferrer\" title=\"MossMenu webpart\">MossMenu webpart</a> that Microsoft has released through the ECM Team Blog. This code is based on the native AspMenu control. I used this control to \"intercept\" the native SiteMapDataSource injected into through DataSourceId attribute in the markup and create a new XML data source to exhibit the desired behavior. I've included the final source code at the end of this wordy answer. Here are the bits from the master page markup:</p>\n\n<pre><code><%@ Register TagPrefix=\"myCustom\" Namespace=\"YourCompany.CustomWebParts\"\n Assembly=\"YourCompany.CustomWebParts, Version=1.0.0.0, Culture=neutral,\n PublicKeyToken=9f4da00116c38ec5\" %>\n\n...\n\n<myCustom:MossMenu ID=\"CurrentNav\" runat=\"server\" datasourceID=\"SiteMapDS\"\n orientation=\"Vertical\" UseCompactMenus=\"true\" StaticDisplayLevels=\"6\"\n MaximumDynamicDisplayLevels=\"0\" StaticSubMenuIndent=\"5\" ItemWrap=\"false\"\n AccessKey=\"3\" CssClass=\"leftNav\"\n SkipLinkText=\"<%$Resources:cms,masterpages_skiplinktext%>\">\n <LevelMenuItemStyles>\n <asp:MenuItemStyle CssClass=\"Nav\" />\n <asp:MenuItemStyle CssClass=\"SecNav\" />\n </LevelMenuItemStyles>\n <StaticHoverStyle CssClass=\"leftNavHover\"/>\n <StaticSelectedStyle CssClass=\"leftNavSelected\"/>\n <DynamicMenuStyle CssClass=\"leftNavFlyOuts\" />\n <DynamicMenuItemStyle CssClass=\"leftNavFlyOutsItem\"/>\n <DynamicHoverStyle CssClass=\"leftNavFlyOutsHover\"/>\n</myCustom:MossMenu>\n\n<PublishingNavigation:PortalSiteMapDataSource ID=\"SiteMapDS\" Runat=\"server\"\n SiteMapProvider=\"CurrentNavSiteMapProvider\" EnableViewState=\"true\"\n StartFromCurrentNode=\"true\" ShowStartingNode=\"false\"/>\n\n...\n</code></pre>\n\n<p>I followed the excellent step-by-step instructions to create my custom web part in the comments section of the <a href=\"http://blogs.msdn.com/ecm/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control-mossmenu-source-code-released.aspx\" rel=\"nofollow noreferrer\" title=\"MossMenu webpart\">MossMenu webpart</a> at \"Wednesday, September 19, 2007 7:20 AM by Roel\". In my googling, I also found something to configure a Sharepoint site to display exceptions in the same lovely way that ASP.NET does by making the web.config changes <a href=\"http://blog.thekid.me.uk/archive/2007/02/15/a-solution-to-quot-an-unexpected-error-has-occurred-quot-in-wss-v3.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I decided to call my custom behavior a \"compact menu\" so I created a UseCompactMenus property on the control. If you don't set this attribute in the markup to true, the control will behave identically to an AspMenu control.</p>\n\n<p>My application has the user always starting from the home page at the site map root. I can have the custom control store the initial (complete) site map when the root page is displayed. This is stored in a static string for use in the customizing behavior. If you application doesn't follow this assumption, the control will not work as expected.</p>\n\n<p>On the initial application page, only the direct child pages to the root page are displayed in the menu. Clicking on these menu nodes will open all the child nodes under it but keeps the sibling nodes \"closed\". If you click on one of the other sibling nodes, it collapses the current node and it opens the newly selected node. That's it, enjoy!! </p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.ComponentModel;\nusing System.Collections.Generic;\nusing System.Security.Permissions;\nusing System.Xml;\nusing System.Xml.Serialization;\n\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.Design.WebControls;\n\nusing Microsoft.SharePoint;\nusing Microsoft.SharePoint.Utilities;\nusing Microsoft.SharePoint.Security;\n\nnamespace YourCompany.CustomWebParts\n{\n [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]\n [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]\n [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]\n [SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]\n [Designer(typeof(MossMenuDesigner))]\n [ToolboxData(\"<{0}:MossMenu runat=\\\"server\\\" />\")]\n public class MossMenu : System.Web.UI.WebControls.Menu\n {\n private string idPrefix;\n\n // a url->menuItem dictionary\n private Dictionary<string, System.Web.UI.WebControls.MenuItem> menuItemDictionary =\n new Dictionary<string, System.Web.UI.WebControls.MenuItem>(StringComparer.OrdinalIgnoreCase);\n\n private bool customSelectionEnabled = true;\n private bool selectStaticItemsOnly = true;\n\n private bool performTargetBinding = true;\n\n //** Variables used for compact menu behavior **//\n private bool useCompactMenus = false;\n private static bool showStartingNode;\n private static string originalSiteMap;\n\n /// <summary>\n /// Controls whether or not the control performs compacting of the site map to display only ancestor and child nodes of the selected and first level root childern.\n /// </summary>\n [Category(\"Behavior\")]\n public bool UseCompactMenus\n {\n get\n {\n return this.useCompactMenus;\n }\n set\n {\n this.useCompactMenus = value;\n }\n }\n\n /// <summary>\n /// Controls whether or not the control performs custom selection/highlighting.\n /// </summary>\n [Category(\"Behavior\")]\n public bool CustomSelectionEnabled\n {\n get\n {\n return this.customSelectionEnabled;\n }\n set\n {\n this.customSelectionEnabled = value;\n }\n }\n\n /// <summary>\n /// Controls whether only static items may be selected or if\n /// dynamic (fly-out) items may be selected too.\n /// </summary>\n [Category(\"Behavior\")]\n public bool SelectStaticItemsOnly\n {\n get\n {\n return this.selectStaticItemsOnly;\n }\n set\n {\n this.selectStaticItemsOnly = value;\n }\n }\n\n /// <summary>\n /// Controls whether or not to bind the Target property of any menu\n /// items to the Target property in the SiteMapNode's Attributes\n /// collection.\n /// </summary>\n [Category(\"Behavior\")]\n public bool PerformTargetBinding\n {\n get\n {\n return this.performTargetBinding;\n }\n set\n {\n this.performTargetBinding = value;\n }\n }\n\n /// <summary>\n /// Gets the ClientID of this control. \n /// </summary>\n public override string ClientID\n {\n [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]\n get\n {\n if (this.idPrefix == null)\n {\n this.idPrefix = SPUtility.GetNewIdPrefix(this.Context);\n }\n\n return SPUtility.GetShortId(this.idPrefix, this);\n }\n }\n\n [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]\n protected override void OnMenuItemDataBound(MenuEventArgs e)\n {\n base.OnMenuItemDataBound(e);\n\n if (this.customSelectionEnabled)\n {\n // store in the url->item dictionary\n this.menuItemDictionary[e.Item.NavigateUrl] = e.Item;\n }\n\n if (this.performTargetBinding)\n {\n // try to bind to the Target property if the data item is a SiteMapNode\n SiteMapNode smn = e.Item.DataItem as SiteMapNode;\n if (smn != null)\n {\n string target = smn[\"Target\"];\n if (!string.IsNullOrEmpty(target))\n {\n e.Item.Target = target;\n }\n }\n }\n }\n\n /// <id guid=\"08e034e7-5872-4a31-a771-84cac1dcd53d\" />\n /// <owner alias=\"MarkWal\">\n /// </owner>\n [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]\n protected override void OnPreRender(System.EventArgs e)\n {\n\n SiteMapDataSource dataSource = this.GetDataSource() as SiteMapDataSource;\n SiteMapProvider provider = (dataSource != null) ? dataSource.Provider : null;\n\n if (useCompactMenus && dataSource != null && provider != null)\n {\n showStartingNode = dataSource.ShowStartingNode;\n\n SiteMapNodeCollection rootChildNodes = provider.RootNode.ChildNodes;\n\n if (provider.CurrentNode.Equals(provider.RootNode))\n {\n //** Store original site map for future use in compacting menus **//\n if (originalSiteMap == null)\n {\n //Store original SiteMapXML for future adjustments:\n XmlDocument newSiteMapDoc = new XmlDocument();\n newSiteMapDoc.LoadXml(\"<?xml version='1.0' ?>\"\n + \"<siteMapNode title='\" + provider.RootNode.Title\n + \"' url='\" + provider.RootNode.Url\n + \"' />\");\n\n foreach (SiteMapNode node in rootChildNodes)\n {\n XmlNode newNode = GetXmlSiteMapNode(newSiteMapDoc.DocumentElement, node);\n\n newSiteMapDoc.DocumentElement.AppendChild(newNode);\n\n //Create XML for all the child nodes for selected menu item:\n NavigateSiteMap(newNode, node);\n }\n\n originalSiteMap = newSiteMapDoc.OuterXml;\n }\n\n //This is set to only display the child nodes of the root node on first view:\n this.StaticDisplayLevels = 1;\n }\n else\n {\n //\n //Adjust site map for this page\n //\n XmlDocument newSiteMapDoc = InitializeNewSiteMapXml(provider, rootChildNodes);\n\n //Clear the current default site map:\n this.DataSourceID = null;\n\n //Create the new site map data source\n XmlDataSource newSiteMap = new XmlDataSource();\n newSiteMap.ID = \"XmlDataSource1\";\n newSiteMap.EnableCaching = false; //Required to prevent redisplay of the previous menu\n\n //Add bindings for dynamic site map:\n MenuItemBindingCollection bindings = this.DataBindings;\n bindings.Clear();\n\n MenuItemBinding binding = new MenuItemBinding();\n binding.DataMember = \"siteMapNode\";\n binding.TextField = \"title\";\n binding.Text = \"title\";\n binding.NavigateUrlField = \"url\";\n binding.NavigateUrl = \"url\";\n binding.ValueField = \"url\";\n binding.Value = \"url\";\n\n bindings.Add(binding);\n\n //Bind menu to new site map:\n this.DataSource = newSiteMap;\n\n //Assign the newly created dynamic site map:\n ((XmlDataSource)this.DataSource).Data = newSiteMapDoc.OuterXml;\n\n /** this expression removes the root if initialized: **/\n if (!showStartingNode)\n ((XmlDataSource)this.DataSource).XPath = \"/siteMapNode/siteMapNode\";\n\n /** Re-initialize menu data source with new site map: **/\n this.DataBind();\n\n /** Find depth of current node: **/\n int depth = 0;\n SiteMapNode currNode = provider.CurrentNode;\n do\n {\n depth++;\n currNode = currNode.ParentNode;\n }\n while (currNode != null);\n\n //Set the StaticDisplayLevels to match the current depth:\n if (depth >= this.StaticDisplayLevels)\n this.StaticDisplayLevels = depth;\n }\n }\n\n base.OnPreRender(e);\n\n // output some script to override the default menu flyout behaviour; this helps to avoid\n // intermittent \"Operation Aborted\" errors\n Page.ClientScript.RegisterStartupScript(\n typeof(MossMenu),\n \"overrideMenu_HoverStatic\",\n \"if (typeof(overrideMenu_HoverStatic) == 'function' && typeof(Menu_HoverStatic) == 'function')\\n\" +\n \"{\\n\" +\n \"_spBodyOnLoadFunctionNames.push('enableFlyoutsAfterDelay');\\n\" +\n \"Menu_HoverStatic = overrideMenu_HoverStatic;\\n\" +\n \"}\\n\",\n true);\n\n // output some script to avoid a known issue with SSL Termination and the ASP.NET\n // Menu implementation. http://support.microsoft.com/?id=910444\n Page.ClientScript.RegisterStartupScript(\n typeof(MossMenu),\n \"MenuHttpsWorkaround_\" + this.ClientID,\n this.ClientID + \"_Data.iframeUrl='/_layouts/images/blank.gif';\",\n true);\n\n // adjust the fly-out indicator arrow direction for locale if not already set\n if (this.Orientation == System.Web.UI.WebControls.Orientation.Vertical &&\n ((string.IsNullOrEmpty(this.StaticPopOutImageUrl) && this.StaticEnableDefaultPopOutImage) ||\n (string.IsNullOrEmpty(this.DynamicPopOutImageUrl) && this.DynamicEnableDefaultPopOutImage)))\n {\n SPWeb currentWeb = SPContext.Current.Web;\n if (currentWeb != null)\n {\n uint localeId = currentWeb.Language;\n\n bool isBidiWeb = SPUtility.IsRightToLeft(currentWeb, currentWeb.Language);\n\n string arrowUrl = \"/_layouts/images/\" + (isBidiWeb ? \"largearrowleft.gif\" : \"largearrowright.gif\");\n\n if (string.IsNullOrEmpty(this.StaticPopOutImageUrl) && this.StaticEnableDefaultPopOutImage)\n {\n this.StaticPopOutImageUrl = arrowUrl;\n }\n if (string.IsNullOrEmpty(this.DynamicPopOutImageUrl) && this.DynamicEnableDefaultPopOutImage)\n {\n this.DynamicPopOutImageUrl = arrowUrl;\n }\n }\n }\n\n if (provider == null)\n {\n // if we're not attached to a SiteMapDataSource we'll just leave everything alone\n return;\n }\n else if (this.customSelectionEnabled)\n {\n MenuItem selectedMenuItem = this.SelectedItem;\n SiteMapNode currentNode = provider.CurrentNode;\n\n // if no menu item is presently selected, we need to work our way up from the current \n // node until we can find a node in the menu item dictionary\n while (selectedMenuItem == null && currentNode != null)\n {\n this.menuItemDictionary.TryGetValue(currentNode.Url, out selectedMenuItem);\n\n currentNode = currentNode.ParentNode;\n }\n\n if (this.selectStaticItemsOnly)\n {\n // only static items may be selected, keep moving up until we find an item\n // that falls within the static range\n while (selectedMenuItem != null && selectedMenuItem.Depth >= this.StaticDisplayLevels)\n {\n selectedMenuItem = selectedMenuItem.Parent;\n }\n\n // if we found an item to select, go ahead and select (highlight) it\n if (selectedMenuItem != null && selectedMenuItem.Selectable)\n {\n selectedMenuItem.Selected = true;\n }\n }\n }\n }\n\n private XmlDocument InitializeNewSiteMapXml(SiteMapProvider provider, SiteMapNodeCollection rootChildNodes)\n {\n /** Find the level 1 ancestor node of the current node: **/\n SiteMapNode levelOneAncestorOfSelectedNode = null;\n SiteMapNode currNode = provider.CurrentNode;\n do\n {\n levelOneAncestorOfSelectedNode = (currNode.ParentNode == null ? levelOneAncestorOfSelectedNode : currNode);\n currNode = currNode.ParentNode;\n }\n while (currNode != null);\n\n /** Initialize base SiteMapXML **/\n XmlDocument newSiteMapDoc = new XmlDocument();\n newSiteMapDoc.LoadXml(originalSiteMap);\n\n /** Prune out the childern nodes that shouldn't display: **/\n currNode = provider.CurrentNode;\n do\n {\n if (currNode.ParentNode != null)\n {\n SiteMapNodeCollection currNodeSiblings = currNode.ParentNode.ChildNodes;\n foreach (SiteMapNode siblingNode in currNodeSiblings)\n {\n if (siblingNode.HasChildNodes)\n {\n if (provider.CurrentNode.Equals(siblingNode))\n {\n //Remove all the childerns child nodes from display:\n SiteMapNodeCollection currNodesChildren = siblingNode.ChildNodes;\n foreach (SiteMapNode childNode in currNodesChildren)\n {\n XmlNode currentXmNode = GetCurrentXmlNode(newSiteMapDoc, childNode);\n\n DeleteChildNodes(currentXmNode);\n }\n }\n else if (!provider.CurrentNode.IsDescendantOf(siblingNode)\n && !levelOneAncestorOfSelectedNode.Equals(siblingNode))\n {\n XmlNode currentXmNode = GetCurrentXmlNode(newSiteMapDoc, siblingNode);\n\n DeleteChildNodes(currentXmNode);\n }\n }\n }\n }\n\n currNode = currNode.ParentNode;\n }\n while (currNode != null);\n\n return newSiteMapDoc;\n }\n\n private XmlNode GetCurrentXmlNode(XmlDocument newSiteMapDoc, SiteMapNode node)\n {\n //Find this node in the original site map:\n XmlNode currentXmNode = newSiteMapDoc.DocumentElement.SelectSingleNode(\n \"//siteMapNode[@url='\"\n + node.Url\n + \"']\");\n return currentXmNode;\n }\n\n private void DeleteChildNodes(XmlNode currentXmNode)\n {\n if (currentXmNode != null && currentXmNode.HasChildNodes)\n {\n //Remove child nodes:\n XmlNodeList xmlNodes = currentXmNode.ChildNodes;\n int lastNodeIndex = xmlNodes.Count - 1;\n for (int i = lastNodeIndex; i >= 0; i--)\n {\n currentXmNode.RemoveChild(xmlNodes[i]);\n }\n }\n }\n private XmlNode GetXmlSiteMapNode(XmlNode currentDocumentNode, SiteMapNode currentNode)\n {\n XmlElement newNode = currentDocumentNode.OwnerDocument.CreateElement(\"siteMapNode\");\n\n XmlAttribute newAttr = currentDocumentNode.OwnerDocument.CreateAttribute(\"title\");\n newAttr.InnerText = currentNode.Title;\n newNode.Attributes.Append(newAttr);\n\n newAttr = currentDocumentNode.OwnerDocument.CreateAttribute(\"url\");\n newAttr.InnerText = currentNode.Url;\n newNode.Attributes.Append(newAttr);\n\n return newNode;\n }\n\n private void NavigateSiteMap(XmlNode currentDocumentNode, SiteMapNode currentNode)\n {\n foreach (SiteMapNode node in currentNode.ChildNodes)\n {\n //Add this node to structure:\n XmlNode newNode = GetXmlSiteMapNode(currentDocumentNode, node);\n currentDocumentNode.AppendChild(newNode);\n\n if (node.HasChildNodes)\n {\n //Make a recursive call to add any child nodes:\n NavigateSiteMap(newNode, node);\n }\n }\n }\n }\n\n [PermissionSet(SecurityAction.LinkDemand, Name = \"FullTrust\")]\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Security\", \"CA2117:AptcaTypesShouldOnlyExtendAptcaBaseTypes\")]\n public sealed class MossMenuDesigner : MenuDesigner\n {\n [PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\n protected override void DataBind(BaseDataBoundControl dataBoundControl)\n {\n try\n {\n dataBoundControl.DataBind();\n }\n catch\n {\n base.DataBind(dataBoundControl);\n }\n }\n\n [PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\n public override string GetDesignTimeHtml()\n {\n System.Web.UI.WebControls.Menu menu = (System.Web.UI.WebControls.Menu)ViewControl;\n int oldDisplayLevels = menu.MaximumDynamicDisplayLevels;\n string designTimeHtml = string.Empty;\n\n try\n {\n menu.MaximumDynamicDisplayLevels = 0;\n\n // ASP.NET MenuDesigner has some dynamic/static item trick in design time\n // to show dynamic item in design time. We only want to show preview without\n // dynamic menu items.\n designTimeHtml = base.GetDesignTimeHtml();\n }\n catch (Exception e)\n {\n designTimeHtml = GetErrorDesignTimeHtml(e);\n }\n finally\n {\n menu.MaximumDynamicDisplayLevels = oldDisplayLevels;\n }\n\n return designTimeHtml;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 227724,
"author": "Chuck",
"author_id": 9714,
"author_profile": "https://Stackoverflow.com/users/9714",
"pm_score": 0,
"selected": false,
"text": "<p>The approach we used to accomplish the affect you are looking for was to use the <a href=\"http://www.codeplex.com/cssfriendly\" rel=\"nofollow noreferrer\">CSS Friendly Control Adapters</a>. The adapters change the HTML that is rendered without changing the controls you used on your pages. You may need to tweak the menu adapter a little bit in order to get the layout you want. It only took a few lines of code for us. Once you get that working, you can use CSS to obtain the behavior you describe.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9711/"
]
| I'm trying to configure the Quick Launch menu to only display the ancestors and descendant nodes of the currently select node. The menu also needs to display all the childern of the root node. More simply:
Given a site map of:
**RootSite**
---**SubSite1** = navigation set at "Display the current site, the navigation items below the current site, and the current site's siblings"
-----**Heading1** = navigation set at "Display the same navigation items as the parent site"
-------**Page1** = navigation set at "Display the same navigation items as the parent site"
-------**Page2** = navigation set at "Display the same navigation items as the parent site"
-----**Heading2** = navigation set at "Display the same navigation items as the parent site"
---**SubSite2** = navigation set at "Display the current site, the navigation items below the current site, and the current site's siblings"
-----**Heading1** = navigation set at "Display the same navigation items as the parent site"
SiteMapProvider configuration:
```
<PublishingNavigation:PortalSiteMapDataSource ID="SiteMapDS" Runat="server"
SiteMapProvider="CurrentNavSiteMapProvider" EnableViewState="true"
StartFromCurrentNode="true" ShowStartingNode="false"/>
```
The expected and actual behavior of the Quick Launch menu displayed at SubSite1 is:
---SubSite1
-----Heading1
-------Page1
-------Page2
-----Heading2
---SubSite2
The expected behavior of the menu after navigating to Heading1 of SubSite2:
---SubSite1
---SubSite2
-----Heading1
What I actually see after navigating to Heading1 of SubSite2:
---SubSite1
-----Heading1
-------Page1
-------Page2
-----Heading2
---SubSite2
-----Heading1
This does not match what I expect to see if I set the Heading1 navigation to "Display the
same navigation items as the parent site" and SubSite2 is set to "Display the current site, the navigation items below the current site, and the current site's siblings". I expect
Heading1 to inherit the navigation item of SubSite2 with the SubSite1 items collapsed from view. I've also played with the various
Trim... attributes without success. Any help will be greatly appreciated! | I followed @Nat's guidance into the murky world Sharepoint webparts to achieve the behavior I described above. My approach was to roll my own version of the [MossMenu webpart](http://blogs.msdn.com/ecm/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control-mossmenu-source-code-released.aspx "MossMenu webpart") that Microsoft has released through the ECM Team Blog. This code is based on the native AspMenu control. I used this control to "intercept" the native SiteMapDataSource injected into through DataSourceId attribute in the markup and create a new XML data source to exhibit the desired behavior. I've included the final source code at the end of this wordy answer. Here are the bits from the master page markup:
```
<%@ Register TagPrefix="myCustom" Namespace="YourCompany.CustomWebParts"
Assembly="YourCompany.CustomWebParts, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=9f4da00116c38ec5" %>
...
<myCustom:MossMenu ID="CurrentNav" runat="server" datasourceID="SiteMapDS"
orientation="Vertical" UseCompactMenus="true" StaticDisplayLevels="6"
MaximumDynamicDisplayLevels="0" StaticSubMenuIndent="5" ItemWrap="false"
AccessKey="3" CssClass="leftNav"
SkipLinkText="<%$Resources:cms,masterpages_skiplinktext%>">
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="Nav" />
<asp:MenuItemStyle CssClass="SecNav" />
</LevelMenuItemStyles>
<StaticHoverStyle CssClass="leftNavHover"/>
<StaticSelectedStyle CssClass="leftNavSelected"/>
<DynamicMenuStyle CssClass="leftNavFlyOuts" />
<DynamicMenuItemStyle CssClass="leftNavFlyOutsItem"/>
<DynamicHoverStyle CssClass="leftNavFlyOutsHover"/>
</myCustom:MossMenu>
<PublishingNavigation:PortalSiteMapDataSource ID="SiteMapDS" Runat="server"
SiteMapProvider="CurrentNavSiteMapProvider" EnableViewState="true"
StartFromCurrentNode="true" ShowStartingNode="false"/>
...
```
I followed the excellent step-by-step instructions to create my custom web part in the comments section of the [MossMenu webpart](http://blogs.msdn.com/ecm/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control-mossmenu-source-code-released.aspx "MossMenu webpart") at "Wednesday, September 19, 2007 7:20 AM by Roel". In my googling, I also found something to configure a Sharepoint site to display exceptions in the same lovely way that ASP.NET does by making the web.config changes [here](http://blog.thekid.me.uk/archive/2007/02/15/a-solution-to-quot-an-unexpected-error-has-occurred-quot-in-wss-v3.aspx).
I decided to call my custom behavior a "compact menu" so I created a UseCompactMenus property on the control. If you don't set this attribute in the markup to true, the control will behave identically to an AspMenu control.
My application has the user always starting from the home page at the site map root. I can have the custom control store the initial (complete) site map when the root page is displayed. This is stored in a static string for use in the customizing behavior. If you application doesn't follow this assumption, the control will not work as expected.
On the initial application page, only the direct child pages to the root page are displayed in the menu. Clicking on these menu nodes will open all the child nodes under it but keeps the sibling nodes "closed". If you click on one of the other sibling nodes, it collapses the current node and it opens the newly selected node. That's it, enjoy!!
```
using System;
using System.Text;
using System.ComponentModel;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Design.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Security;
namespace YourCompany.CustomWebParts
{
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
[SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
[Designer(typeof(MossMenuDesigner))]
[ToolboxData("<{0}:MossMenu runat=\"server\" />")]
public class MossMenu : System.Web.UI.WebControls.Menu
{
private string idPrefix;
// a url->menuItem dictionary
private Dictionary<string, System.Web.UI.WebControls.MenuItem> menuItemDictionary =
new Dictionary<string, System.Web.UI.WebControls.MenuItem>(StringComparer.OrdinalIgnoreCase);
private bool customSelectionEnabled = true;
private bool selectStaticItemsOnly = true;
private bool performTargetBinding = true;
//** Variables used for compact menu behavior **//
private bool useCompactMenus = false;
private static bool showStartingNode;
private static string originalSiteMap;
/// <summary>
/// Controls whether or not the control performs compacting of the site map to display only ancestor and child nodes of the selected and first level root childern.
/// </summary>
[Category("Behavior")]
public bool UseCompactMenus
{
get
{
return this.useCompactMenus;
}
set
{
this.useCompactMenus = value;
}
}
/// <summary>
/// Controls whether or not the control performs custom selection/highlighting.
/// </summary>
[Category("Behavior")]
public bool CustomSelectionEnabled
{
get
{
return this.customSelectionEnabled;
}
set
{
this.customSelectionEnabled = value;
}
}
/// <summary>
/// Controls whether only static items may be selected or if
/// dynamic (fly-out) items may be selected too.
/// </summary>
[Category("Behavior")]
public bool SelectStaticItemsOnly
{
get
{
return this.selectStaticItemsOnly;
}
set
{
this.selectStaticItemsOnly = value;
}
}
/// <summary>
/// Controls whether or not to bind the Target property of any menu
/// items to the Target property in the SiteMapNode's Attributes
/// collection.
/// </summary>
[Category("Behavior")]
public bool PerformTargetBinding
{
get
{
return this.performTargetBinding;
}
set
{
this.performTargetBinding = value;
}
}
/// <summary>
/// Gets the ClientID of this control.
/// </summary>
public override string ClientID
{
[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
get
{
if (this.idPrefix == null)
{
this.idPrefix = SPUtility.GetNewIdPrefix(this.Context);
}
return SPUtility.GetShortId(this.idPrefix, this);
}
}
[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
protected override void OnMenuItemDataBound(MenuEventArgs e)
{
base.OnMenuItemDataBound(e);
if (this.customSelectionEnabled)
{
// store in the url->item dictionary
this.menuItemDictionary[e.Item.NavigateUrl] = e.Item;
}
if (this.performTargetBinding)
{
// try to bind to the Target property if the data item is a SiteMapNode
SiteMapNode smn = e.Item.DataItem as SiteMapNode;
if (smn != null)
{
string target = smn["Target"];
if (!string.IsNullOrEmpty(target))
{
e.Item.Target = target;
}
}
}
}
/// <id guid="08e034e7-5872-4a31-a771-84cac1dcd53d" />
/// <owner alias="MarkWal">
/// </owner>
[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
protected override void OnPreRender(System.EventArgs e)
{
SiteMapDataSource dataSource = this.GetDataSource() as SiteMapDataSource;
SiteMapProvider provider = (dataSource != null) ? dataSource.Provider : null;
if (useCompactMenus && dataSource != null && provider != null)
{
showStartingNode = dataSource.ShowStartingNode;
SiteMapNodeCollection rootChildNodes = provider.RootNode.ChildNodes;
if (provider.CurrentNode.Equals(provider.RootNode))
{
//** Store original site map for future use in compacting menus **//
if (originalSiteMap == null)
{
//Store original SiteMapXML for future adjustments:
XmlDocument newSiteMapDoc = new XmlDocument();
newSiteMapDoc.LoadXml("<?xml version='1.0' ?>"
+ "<siteMapNode title='" + provider.RootNode.Title
+ "' url='" + provider.RootNode.Url
+ "' />");
foreach (SiteMapNode node in rootChildNodes)
{
XmlNode newNode = GetXmlSiteMapNode(newSiteMapDoc.DocumentElement, node);
newSiteMapDoc.DocumentElement.AppendChild(newNode);
//Create XML for all the child nodes for selected menu item:
NavigateSiteMap(newNode, node);
}
originalSiteMap = newSiteMapDoc.OuterXml;
}
//This is set to only display the child nodes of the root node on first view:
this.StaticDisplayLevels = 1;
}
else
{
//
//Adjust site map for this page
//
XmlDocument newSiteMapDoc = InitializeNewSiteMapXml(provider, rootChildNodes);
//Clear the current default site map:
this.DataSourceID = null;
//Create the new site map data source
XmlDataSource newSiteMap = new XmlDataSource();
newSiteMap.ID = "XmlDataSource1";
newSiteMap.EnableCaching = false; //Required to prevent redisplay of the previous menu
//Add bindings for dynamic site map:
MenuItemBindingCollection bindings = this.DataBindings;
bindings.Clear();
MenuItemBinding binding = new MenuItemBinding();
binding.DataMember = "siteMapNode";
binding.TextField = "title";
binding.Text = "title";
binding.NavigateUrlField = "url";
binding.NavigateUrl = "url";
binding.ValueField = "url";
binding.Value = "url";
bindings.Add(binding);
//Bind menu to new site map:
this.DataSource = newSiteMap;
//Assign the newly created dynamic site map:
((XmlDataSource)this.DataSource).Data = newSiteMapDoc.OuterXml;
/** this expression removes the root if initialized: **/
if (!showStartingNode)
((XmlDataSource)this.DataSource).XPath = "/siteMapNode/siteMapNode";
/** Re-initialize menu data source with new site map: **/
this.DataBind();
/** Find depth of current node: **/
int depth = 0;
SiteMapNode currNode = provider.CurrentNode;
do
{
depth++;
currNode = currNode.ParentNode;
}
while (currNode != null);
//Set the StaticDisplayLevels to match the current depth:
if (depth >= this.StaticDisplayLevels)
this.StaticDisplayLevels = depth;
}
}
base.OnPreRender(e);
// output some script to override the default menu flyout behaviour; this helps to avoid
// intermittent "Operation Aborted" errors
Page.ClientScript.RegisterStartupScript(
typeof(MossMenu),
"overrideMenu_HoverStatic",
"if (typeof(overrideMenu_HoverStatic) == 'function' && typeof(Menu_HoverStatic) == 'function')\n" +
"{\n" +
"_spBodyOnLoadFunctionNames.push('enableFlyoutsAfterDelay');\n" +
"Menu_HoverStatic = overrideMenu_HoverStatic;\n" +
"}\n",
true);
// output some script to avoid a known issue with SSL Termination and the ASP.NET
// Menu implementation. http://support.microsoft.com/?id=910444
Page.ClientScript.RegisterStartupScript(
typeof(MossMenu),
"MenuHttpsWorkaround_" + this.ClientID,
this.ClientID + "_Data.iframeUrl='/_layouts/images/blank.gif';",
true);
// adjust the fly-out indicator arrow direction for locale if not already set
if (this.Orientation == System.Web.UI.WebControls.Orientation.Vertical &&
((string.IsNullOrEmpty(this.StaticPopOutImageUrl) && this.StaticEnableDefaultPopOutImage) ||
(string.IsNullOrEmpty(this.DynamicPopOutImageUrl) && this.DynamicEnableDefaultPopOutImage)))
{
SPWeb currentWeb = SPContext.Current.Web;
if (currentWeb != null)
{
uint localeId = currentWeb.Language;
bool isBidiWeb = SPUtility.IsRightToLeft(currentWeb, currentWeb.Language);
string arrowUrl = "/_layouts/images/" + (isBidiWeb ? "largearrowleft.gif" : "largearrowright.gif");
if (string.IsNullOrEmpty(this.StaticPopOutImageUrl) && this.StaticEnableDefaultPopOutImage)
{
this.StaticPopOutImageUrl = arrowUrl;
}
if (string.IsNullOrEmpty(this.DynamicPopOutImageUrl) && this.DynamicEnableDefaultPopOutImage)
{
this.DynamicPopOutImageUrl = arrowUrl;
}
}
}
if (provider == null)
{
// if we're not attached to a SiteMapDataSource we'll just leave everything alone
return;
}
else if (this.customSelectionEnabled)
{
MenuItem selectedMenuItem = this.SelectedItem;
SiteMapNode currentNode = provider.CurrentNode;
// if no menu item is presently selected, we need to work our way up from the current
// node until we can find a node in the menu item dictionary
while (selectedMenuItem == null && currentNode != null)
{
this.menuItemDictionary.TryGetValue(currentNode.Url, out selectedMenuItem);
currentNode = currentNode.ParentNode;
}
if (this.selectStaticItemsOnly)
{
// only static items may be selected, keep moving up until we find an item
// that falls within the static range
while (selectedMenuItem != null && selectedMenuItem.Depth >= this.StaticDisplayLevels)
{
selectedMenuItem = selectedMenuItem.Parent;
}
// if we found an item to select, go ahead and select (highlight) it
if (selectedMenuItem != null && selectedMenuItem.Selectable)
{
selectedMenuItem.Selected = true;
}
}
}
}
private XmlDocument InitializeNewSiteMapXml(SiteMapProvider provider, SiteMapNodeCollection rootChildNodes)
{
/** Find the level 1 ancestor node of the current node: **/
SiteMapNode levelOneAncestorOfSelectedNode = null;
SiteMapNode currNode = provider.CurrentNode;
do
{
levelOneAncestorOfSelectedNode = (currNode.ParentNode == null ? levelOneAncestorOfSelectedNode : currNode);
currNode = currNode.ParentNode;
}
while (currNode != null);
/** Initialize base SiteMapXML **/
XmlDocument newSiteMapDoc = new XmlDocument();
newSiteMapDoc.LoadXml(originalSiteMap);
/** Prune out the childern nodes that shouldn't display: **/
currNode = provider.CurrentNode;
do
{
if (currNode.ParentNode != null)
{
SiteMapNodeCollection currNodeSiblings = currNode.ParentNode.ChildNodes;
foreach (SiteMapNode siblingNode in currNodeSiblings)
{
if (siblingNode.HasChildNodes)
{
if (provider.CurrentNode.Equals(siblingNode))
{
//Remove all the childerns child nodes from display:
SiteMapNodeCollection currNodesChildren = siblingNode.ChildNodes;
foreach (SiteMapNode childNode in currNodesChildren)
{
XmlNode currentXmNode = GetCurrentXmlNode(newSiteMapDoc, childNode);
DeleteChildNodes(currentXmNode);
}
}
else if (!provider.CurrentNode.IsDescendantOf(siblingNode)
&& !levelOneAncestorOfSelectedNode.Equals(siblingNode))
{
XmlNode currentXmNode = GetCurrentXmlNode(newSiteMapDoc, siblingNode);
DeleteChildNodes(currentXmNode);
}
}
}
}
currNode = currNode.ParentNode;
}
while (currNode != null);
return newSiteMapDoc;
}
private XmlNode GetCurrentXmlNode(XmlDocument newSiteMapDoc, SiteMapNode node)
{
//Find this node in the original site map:
XmlNode currentXmNode = newSiteMapDoc.DocumentElement.SelectSingleNode(
"//siteMapNode[@url='"
+ node.Url
+ "']");
return currentXmNode;
}
private void DeleteChildNodes(XmlNode currentXmNode)
{
if (currentXmNode != null && currentXmNode.HasChildNodes)
{
//Remove child nodes:
XmlNodeList xmlNodes = currentXmNode.ChildNodes;
int lastNodeIndex = xmlNodes.Count - 1;
for (int i = lastNodeIndex; i >= 0; i--)
{
currentXmNode.RemoveChild(xmlNodes[i]);
}
}
}
private XmlNode GetXmlSiteMapNode(XmlNode currentDocumentNode, SiteMapNode currentNode)
{
XmlElement newNode = currentDocumentNode.OwnerDocument.CreateElement("siteMapNode");
XmlAttribute newAttr = currentDocumentNode.OwnerDocument.CreateAttribute("title");
newAttr.InnerText = currentNode.Title;
newNode.Attributes.Append(newAttr);
newAttr = currentDocumentNode.OwnerDocument.CreateAttribute("url");
newAttr.InnerText = currentNode.Url;
newNode.Attributes.Append(newAttr);
return newNode;
}
private void NavigateSiteMap(XmlNode currentDocumentNode, SiteMapNode currentNode)
{
foreach (SiteMapNode node in currentNode.ChildNodes)
{
//Add this node to structure:
XmlNode newNode = GetXmlSiteMapNode(currentDocumentNode, node);
currentDocumentNode.AppendChild(newNode);
if (node.HasChildNodes)
{
//Make a recursive call to add any child nodes:
NavigateSiteMap(newNode, node);
}
}
}
}
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2117:AptcaTypesShouldOnlyExtendAptcaBaseTypes")]
public sealed class MossMenuDesigner : MenuDesigner
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
protected override void DataBind(BaseDataBoundControl dataBoundControl)
{
try
{
dataBoundControl.DataBind();
}
catch
{
base.DataBind(dataBoundControl);
}
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public override string GetDesignTimeHtml()
{
System.Web.UI.WebControls.Menu menu = (System.Web.UI.WebControls.Menu)ViewControl;
int oldDisplayLevels = menu.MaximumDynamicDisplayLevels;
string designTimeHtml = string.Empty;
try
{
menu.MaximumDynamicDisplayLevels = 0;
// ASP.NET MenuDesigner has some dynamic/static item trick in design time
// to show dynamic item in design time. We only want to show preview without
// dynamic menu items.
designTimeHtml = base.GetDesignTimeHtml();
}
catch (Exception e)
{
designTimeHtml = GetErrorDesignTimeHtml(e);
}
finally
{
menu.MaximumDynamicDisplayLevels = oldDisplayLevels;
}
return designTimeHtml;
}
}
}
``` |
94,161 | <p>I'm working on a project that will be distributed with GNU autoconf/automake, and I have a set of bash scripts which call awk scripts. I would like the bash scripts to end up in the $PATH, but not the awk scripts. How should I insert these into the project? Should they be put in with other binaries?</p>
<p>Also, is there a way to determine the final location of the file after installation? I presume that /usr/local/bin isn't <em>always</em> where the executables end up...</p>
| [
{
"answer_id": 94259,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": true,
"text": "<p>Add something like this to Makefile.am</p>\n\n<pre><code>scriptsdir = $(prefix)/bin\nscripts_DATA = awkscript1 awkscript2\n</code></pre>\n\n<p>In this case it will install awkscript in $(prefix)/bin (you can also use $(bindir)).</p>\n\n<p>Note: Dont forget that the first should be named name + dir (scripts -> scriptsdir) and the second should be name + _DATA (scripts -> scripts_DATA).</p>\n"
},
{
"answer_id": 94273,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>If the awk scripts won't go into the main bin directory (prefix/bin), then you need to place them in an appropriate sub-directory - probably of lib but possibly libexec or share (since the awk scripts are probably platform neutral).</p>\n\n<p>Correct: software won't necessarily end up in /usr/local/bin; on my machine, /usr/local/bin is managed by MIS and all the software I install therefore goes under /usr/gnu/. I use: ./configure --prefix=/usr/gnu to get the software installed where I want it.</p>\n\n<p>You can embed the value of PREFIX in the bash scripts -- effectively, you will 'compile' the scripts to include the install location. Be aware of problems during the build testing - you may need to locate the scripts relative to the current directory first and relative to PREFIX later.</p>\n"
},
{
"answer_id": 156629,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 2,
"selected": false,
"text": "<p>Jonathan, in response to your additional question: if you want to replace the value of prefix at the time of build, you will need to:</p>\n\n<ol>\n<li>rename your script 'myscript' to 'myscript.in'</li>\n<li>add a rule to configure.ac to generate it at the bottom</li>\n<li>use a macro I made called <a href=\"http://autostars.cvs.sourceforge.net/viewvc/*checkout*/autostars/autostars/ac-expand/as-ac-expand.m4\" rel=\"nofollow noreferrer\">AS_AC_EXPAND</a></li>\n<li><p>use it like this:</p>\n\n<p>AS_AC_EXPAND(BINDIR, $bindir)</p></li>\n<li><p>in your 'myscript.in', you can now use @BINDIR@ and it will get expanded to the full path where the script will end up being installed.</p></li>\n</ol>\n\n<p>Note that you shouldn't use PREFIX directly, any of the installation directories can potentially be changed so you really want to use the value passed to configure for bindir and expand that.</p>\n"
},
{
"answer_id": 8995141,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 3,
"selected": false,
"text": "<p>You can just list the scripts that you want to be installed in Makefile.am:</p>\n\n<pre>\nbin_SCRIPTS = foo bar\n</pre>\n\n<p>This will cause foo and bar to be installed during make install. To get the path to their final location, you can use @bindir@ in foo.in and let configure build foo for you. For example, in configure.ac:</p>\n\n<pre>\nAC_CONFIG_FILES([foo bar])\n</pre>\n\n<p>and then in foo.in:</p>\n\n<pre>\n#!/bin/sh\n\nprefix=@prefix@\nexec_prefix=@exec_prefix@\nbindir=@bindir@\necho bindir = $bindir\n</pre>\n\n<p>Keep in mind that the person running configure may specify any of --prefix, --exec_prefix, or\n--bindir, and the installation may be redirected with a DESTDIR. Using the technique described here, DESTDIR will not be taken into account and the script will be installed in a location other than the path that it will echo. This is by design, and is the correct behavior, as usually a DESTDIR installation is used to create a tarball that will eventually be unpacked into the filesystem in such a way that the bindir in the script becomes valid.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17925/"
]
| I'm working on a project that will be distributed with GNU autoconf/automake, and I have a set of bash scripts which call awk scripts. I would like the bash scripts to end up in the $PATH, but not the awk scripts. How should I insert these into the project? Should they be put in with other binaries?
Also, is there a way to determine the final location of the file after installation? I presume that /usr/local/bin isn't *always* where the executables end up... | Add something like this to Makefile.am
```
scriptsdir = $(prefix)/bin
scripts_DATA = awkscript1 awkscript2
```
In this case it will install awkscript in $(prefix)/bin (you can also use $(bindir)).
Note: Dont forget that the first should be named name + dir (scripts -> scriptsdir) and the second should be name + \_DATA (scripts -> scripts\_DATA). |
94,171 | <p>In C#.Net WPF During UserControl.Load -></p>
<p>What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents?</p>
| [
{
"answer_id": 95143,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 5,
"selected": true,
"text": "<p>I generally would create a layout like this:</p>\n\n<pre><code><Grid>\n <Grid x:Name=\"MainContent\" IsEnabled=\"False\">\n ...\n </Grid>\n\n <Grid x:Name=\"LoadingIndicatorPanel\">\n ...\n </Grid>\n</Grid>\n</code></pre>\n\n<p>Then I load the data on a worker thread, and when it's finished I update the UI under the \"MainContent\" grid and enable the grid, then set the LoadingIndicatorPanel's Visibility to Collapsed.</p>\n\n<p>I'm not sure if this is what you were asking or if you wanted to know how to show an animation in the loading label. If it's the animation you're after, please update your question to be more specific.</p>\n"
},
{
"answer_id": 132966,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 3,
"selected": false,
"text": "<p>This is something that I was working on just recently in order to create a loading animation. This xaml will produce an animated ring of circles. </p>\n\n<p>My initial idea was to create an adorner and use this animation as it's content, then to display the loading animation in the adorners layer and grey out the content underneath.</p>\n\n<p>Haven't had the chance to finish it yet, so I thought I would just post the animation for your reference.</p>\n\n<pre><code><Window \n x:Class=\"WpfApplication2.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\"\n Height=\"300\"\n Width=\"300\"\n >\n <Window.Resources>\n <Color x:Key=\"FilledColor\" A=\"255\" B=\"155\" R=\"155\" G=\"155\"/>\n <Color x:Key=\"UnfilledColor\" A=\"0\" B=\"155\" R=\"155\" G=\"155\"/>\n\n <Storyboard x:Key=\"Animation0\" FillBehavior=\"Stop\" BeginTime=\"00:00:00.0\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_00\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation1\" BeginTime=\"00:00:00.2\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_01\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation2\" BeginTime=\"00:00:00.4\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_02\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation3\" BeginTime=\"00:00:00.6\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_03\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation4\" BeginTime=\"00:00:00.8\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_04\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation5\" BeginTime=\"00:00:01.0\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_05\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation6\" BeginTime=\"00:00:01.2\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_06\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation7\" BeginTime=\"00:00:01.4\" RepeatBehavior=\"Forever\">\n <ColorAnimationUsingKeyFrames Storyboard.TargetName=\"_07\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"00:00:00.0\" Value=\"{StaticResource FilledColor}\"/>\n <SplineColorKeyFrame KeyTime=\"00:00:01.6\" Value=\"{StaticResource UnfilledColor}\"/>\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n </Window.Resources>\n\n <Window.Triggers>\n <EventTrigger RoutedEvent=\"FrameworkElement.Loaded\">\n <BeginStoryboard Storyboard=\"{StaticResource Animation0}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation1}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation2}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation3}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation4}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation5}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation6}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation7}\"/>\n </EventTrigger>\n </Window.Triggers>\n\n <Canvas>\n <Canvas Canvas.Left=\"21.75\" Canvas.Top=\"14\" Height=\"81.302\" Width=\"80.197\">\n <Canvas.Resources>\n <Style TargetType=\"Ellipse\">\n <Setter Property=\"Width\" Value=\"15\"/>\n <Setter Property=\"Height\" Value=\"15\" />\n <Setter Property=\"Fill\" Value=\"#FFFFFFFF\" />\n </Style>\n </Canvas.Resources>\n\n <Ellipse x:Name=\"_00\" Canvas.Left=\"24.75\" Canvas.Top=\"50\"/>\n <Ellipse x:Name=\"_01\" Canvas.Top=\"36\" Canvas.Left=\"29.5\"/>\n <Ellipse x:Name=\"_02\" Canvas.Left=\"43.5\" Canvas.Top=\"29.75\"/>\n <Ellipse x:Name=\"_03\" Canvas.Left=\"57.75\" Canvas.Top=\"35.75\"/>\n <Ellipse x:Name=\"_04\" Canvas.Left=\"63.5\" Canvas.Top=\"49.75\" />\n <Ellipse x:Name=\"_05\" Canvas.Left=\"57.75\" Canvas.Top=\"63.5\"/>\n <Ellipse x:Name=\"_06\" Canvas.Left=\"43.75\" Canvas.Top=\"68.75\"/>\n <Ellipse x:Name=\"_07\" Canvas.Top=\"63.25\" Canvas.Left=\"30\" />\n <Ellipse Stroke=\"{x:Null}\" Width=\"39.5\" Height=\"39.5\" Canvas.Left=\"31.75\" Canvas.Top=\"37\" Fill=\"{x:Null}\"/>\n </Canvas>\n </Canvas>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 158113,
"author": "Christopher Scott",
"author_id": 1346,
"author_profile": "https://Stackoverflow.com/users/1346",
"pm_score": 1,
"selected": false,
"text": "<p>If you are running it on Vista, you could also just use the default wait cursor.</p>\n\n<p>this.Cursor = Cursors.Wait;</p>\n"
},
{
"answer_id": 2137422,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 1,
"selected": false,
"text": "<p>Use BusyIndicator. It's a silverlight thing.</p>\n"
},
{
"answer_id": 3882106,
"author": "VadimB",
"author_id": 454741,
"author_profile": "https://Stackoverflow.com/users/454741",
"pm_score": 1,
"selected": false,
"text": "<p>You can show animated gif as loading element</p>\n\n<p><strong>XAML</strong></p>\n\n<pre><code><WindowsFormsHost>\n <winForms:PictureBox x:Name=\"pictureBoxLoading\" />\n</WindowsFormsHost>\n</code></pre>\n\n<p><strong>CODE BEHIND</strong></p>\n\n<pre><code>pictureBoxLoading.Image = System.Drawing.Image.FromFile(\"images/ajax-loader.gif\");\n</code></pre>\n"
},
{
"answer_id": 14692963,
"author": "Sven Hecht",
"author_id": 1168,
"author_profile": "https://Stackoverflow.com/users/1168",
"pm_score": 3,
"selected": false,
"text": "<p>I improved on Ian Oakes Design and build an scalable version of his loading indicator:</p>\n\n<pre><code><UserControl x:Class=\"Mesap.Framework.UI.Controls.BusyIndicator\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n mc:Ignorable=\"d\" Name=\"Root\" Foreground=\"#9b9b9b\"\n d:DesignHeight=\"100\" d:DesignWidth=\"100\">\n <Grid>\n <Grid.Resources>\n <Storyboard x:Key=\"Animation0\" FillBehavior=\"Stop\" BeginTime=\"00:00:00.0\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E00\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation1\" BeginTime=\"00:00:00.2\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E01\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation2\" BeginTime=\"00:00:00.4\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E02\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation3\" BeginTime=\"00:00:00.6\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E03\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation4\" BeginTime=\"00:00:00.8\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E04\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation5\" BeginTime=\"00:00:01.0\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E05\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation6\" BeginTime=\"00:00:01.2\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E06\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Storyboard x:Key=\"Animation7\" BeginTime=\"00:00:01.4\" RepeatBehavior=\"Forever\">\n <DoubleAnimationUsingKeyFrames Storyboard.TargetName=\"E07\" Storyboard.TargetProperty=\"Opacity\">\n <LinearDoubleKeyFrame KeyTime=\"00:00:00.0\" Value=\"1\"/>\n <LinearDoubleKeyFrame KeyTime=\"00:00:01.6\" Value=\"0\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n\n <Style TargetType=\"Ellipse\">\n <Setter Property=\"Fill\" Value=\"{Binding ElementName=Root, Path=Foreground}\"/>\n\n </Style>\n </Grid.Resources>\n <Grid.Triggers>\n <EventTrigger RoutedEvent=\"FrameworkElement.Loaded\">\n <BeginStoryboard Storyboard=\"{StaticResource Animation0}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation1}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation2}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation3}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation4}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation5}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation6}\"/>\n <BeginStoryboard Storyboard=\"{StaticResource Animation7}\"/>\n </EventTrigger>\n </Grid.Triggers>\n\n <Grid.ColumnDefinitions>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n <ColumnDefinition/>\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n <RowDefinition/>\n </Grid.RowDefinitions>\n\n <Ellipse x:Name=\"E00\" Grid.Row=\"4\" Grid.Column=\"0\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\"/>\n <Ellipse x:Name=\"E01\" Grid.Row=\"1\" Grid.Column=\"1\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E02\" Grid.Row=\"0\" Grid.Column=\"4\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E03\" Grid.Row=\"1\" Grid.Column=\"7\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E04\" Grid.Row=\"4\" Grid.Column=\"8\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E05\" Grid.Row=\"7\" Grid.Column=\"7\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E06\" Grid.Row=\"8\" Grid.Column=\"4\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n <Ellipse x:Name=\"E07\" Grid.Row=\"7\" Grid.Column=\"1\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"3\" Width=\"Auto\" Height=\"Auto\" Opacity=\"0\" />\n </Grid>\n</UserControl>\n</code></pre>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/352728/"
]
| In C#.Net WPF During UserControl.Load ->
What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents? | I generally would create a layout like this:
```
<Grid>
<Grid x:Name="MainContent" IsEnabled="False">
...
</Grid>
<Grid x:Name="LoadingIndicatorPanel">
...
</Grid>
</Grid>
```
Then I load the data on a worker thread, and when it's finished I update the UI under the "MainContent" grid and enable the grid, then set the LoadingIndicatorPanel's Visibility to Collapsed.
I'm not sure if this is what you were asking or if you wanted to know how to show an animation in the loading label. If it's the animation you're after, please update your question to be more specific. |
94,177 | <p>I have the following XAML: </p>
<pre><code><TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="TextBlock.Text" Value="item selected"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</code></pre>
<p>The first text block happily changes with SelectedItems.Count, showing 0,1,2, etc. The datatrigger on the second block never seems to fire to change the text.</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 94690,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 5,
"selected": true,
"text": "<p>The DataTrigger is firing but the Text field for your second TextBlock is hard-coded as \"items selected\" so it won't be able to change. To see it firing, you can remove Text=\"items selected\".</p>\n\n<p>Your problem is a good candidate for using a <strong>ValueConverter</strong> instead of <strong>DataTrigger</strong>. Here's how to create and use the ValueConverter to get it to set the Text to what you want. </p>\n\n<p><strong>Create this ValueConverter:</strong></p>\n\n<pre><code>public class CountToSelectedTextConverter : IValueConverter\n{\n #region IValueConverter Members\n\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n if ((int)value == 1)\n return \"item selected\";\n else\n return \"items selected\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\n</code></pre>\n\n<p><strong>Add the namespace reference to your the assembly the converter is located:</strong></p>\n\n<pre><code>xmlns:local=\"clr-namespace:ValueConverterExample\"\n</code></pre>\n\n<p><strong>Add the converter to your resources:</strong></p>\n\n<pre><code><Window.Resources>\n <local:CountToSelectedTextConverter x:Key=\"CountToSelectedTextConverter\"/>\n</Window.Resources>\n</code></pre>\n\n<p><strong>Change your second textblock to:</strong></p>\n\n<pre><code> <TextBlock Text=\"{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}\"/>\n</code></pre>\n"
},
{
"answer_id": 105592,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 5,
"selected": false,
"text": "<p>Alternatively, you could replace your XAML with this:</p>\n\n<pre><code><TextBlock Margin=\"0,0,5,0\" Text=\"{Binding ElementName=EditListBox, Path=SelectedItems.Count}\"/>\n<TextBlock>\n <TextBlock.Style>\n <Style TargetType=\"{x:Type TextBlock}\">\n <Setter Property=\"Text\" Value=\"items selected\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding ElementName=EditListBox, Path=SelectedItems.Count}\" Value=\"1\">\n <Setter Property=\"Text\" Value=\"item selected\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n</TextBlock>\n</code></pre>\n\n<p>Converters can solve a lot of binding problems but having a lot of specialized converters gets very messy.</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2284/"
]
| I have the following XAML:
```
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="TextBlock.Text" Value="item selected"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
```
The first text block happily changes with SelectedItems.Count, showing 0,1,2, etc. The datatrigger on the second block never seems to fire to change the text.
Any thoughts? | The DataTrigger is firing but the Text field for your second TextBlock is hard-coded as "items selected" so it won't be able to change. To see it firing, you can remove Text="items selected".
Your problem is a good candidate for using a **ValueConverter** instead of **DataTrigger**. Here's how to create and use the ValueConverter to get it to set the Text to what you want.
**Create this ValueConverter:**
```
public class CountToSelectedTextConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value == 1)
return "item selected";
else
return "items selected";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
```
**Add the namespace reference to your the assembly the converter is located:**
```
xmlns:local="clr-namespace:ValueConverterExample"
```
**Add the converter to your resources:**
```
<Window.Resources>
<local:CountToSelectedTextConverter x:Key="CountToSelectedTextConverter"/>
</Window.Resources>
```
**Change your second textblock to:**
```
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}"/>
``` |
94,263 | <p>When constructing an ArgumentException, a couple of the overloads take a string that is the invalid argument's parameter name. I figure it would be nice to not have to remember to update this ctor param whenever I change the method's param name. Is there a simple way to do this using reflection?</p>
<p><strong>Update:</strong> thanks to the 2 respondents so far. You both answer the question well, but the solution still leaves me with a maintenance headache. (Okay, a <strong>tiny</strong> headache, but still...) To explain, if I were to <em>reorder</em> the params later -- or remove an earlier param -- I'd have to remember to change my exception-construction code again. Is there a way I can use something along the lines of</p>
<pre><code>Object.ReferenceEquals(myParam, <insert code here>)
</code></pre>
<p>to be sure I'm dealing with the relevant parameter? That way, the compiler would step in to prevent me badly constructing the exception.</p>
<p>That said, I'm starting to suspect that the "simple" part of the original question not that forthcoming. Maybe I should just put up with using string literals. :)</p>
| [
{
"answer_id": 94300,
"author": "Brian",
"author_id": 1750627,
"author_profile": "https://Stackoverflow.com/users/1750627",
"pm_score": 3,
"selected": true,
"text": "<p>You can use either Modules or RSL.</p>\n\n<p>RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.</p>\n\n<p>Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.</p>\n\n<p>Here is some documentation on creating RSLs <a href=\"http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs\" rel=\"nofollow noreferrer\">http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs</a></p>\n"
},
{
"answer_id": 100656,
"author": "Cosma Colanicchia",
"author_id": 11867,
"author_profile": "https://Stackoverflow.com/users/11867",
"pm_score": 0,
"selected": false,
"text": "<p>Note that, currently, loaded RSLs must be compiled against the very same version of the Flex framework.. if you plan for a \"binary\" plugin system, probably you want to wait for the <a href=\"http://opensource.adobe.com/wiki/display/flexsdk/Marshall+Plan\" rel=\"nofollow noreferrer\">Marshall plan</a> feature to be implemented, in the next Flex version.</p>\n"
},
{
"answer_id": 1990923,
"author": "Cambiata",
"author_id": 146400,
"author_profile": "https://Stackoverflow.com/users/146400",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to try a new and alternative approach, this is a application core framework modelled after java OSGi: <a href=\"http://www.potomacframework.org/\" rel=\"nofollow noreferrer\">http://www.potomacframework.org/</a>\nI haven't tried it myself, but it looks really cool!</p>\n"
}
]
| 2008/09/18 | [
"https://Stackoverflow.com/questions/94263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8705/"
]
| When constructing an ArgumentException, a couple of the overloads take a string that is the invalid argument's parameter name. I figure it would be nice to not have to remember to update this ctor param whenever I change the method's param name. Is there a simple way to do this using reflection?
**Update:** thanks to the 2 respondents so far. You both answer the question well, but the solution still leaves me with a maintenance headache. (Okay, a **tiny** headache, but still...) To explain, if I were to *reorder* the params later -- or remove an earlier param -- I'd have to remember to change my exception-construction code again. Is there a way I can use something along the lines of
```
Object.ReferenceEquals(myParam, <insert code here>)
```
to be sure I'm dealing with the relevant parameter? That way, the compiler would step in to prevent me badly constructing the exception.
That said, I'm starting to suspect that the "simple" part of the original question not that forthcoming. Maybe I should just put up with using string literals. :) | You can use either Modules or RSL.
RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.
Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.
Here is some documentation on creating RSLs <http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.