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
|
---|---|---|---|---|---|---|
274,586 |
<p>In ASP.NET MVC, I'm trying to create a link that includes an anchor tag (that is, directing the user to a page, and a specific section of the page).</p>
<p>The URL I am trying to create should look like the following:</p>
<pre><code><a href="/category/subcategory/1#section12">Title for a section on the page</a>
</code></pre>
<p>My routing is set up with the standard: </p>
<pre><code>routes.MapRoute("Default", "{controller}/{action}/{categoryid}");
</code></pre>
<p>The action link syntax that I am using is: </p>
<pre><code><%foreach (Category parent in ViewData.Model) { %>
<h3><%=parent.Name %></h3>
<ul>
<%foreach (Category child in parent.SubCategories) { %>
<li><%=Html.ActionLink<CategoryController>(x => x.Subcategory(parent.ID), child.Name) %></li>
<%} %>
</ul>
<%} %>
</code></pre>
<p>My controller method is as follows:</p>
<pre><code>public ActionResult Subcategory(int categoryID)
{
//return itemList
return View(itemList);
}
</code></pre>
<p>The above correctly returns a URL as follows:</p>
<pre><code><a href="/category/subcategory/1">Title for a section on the page</a>
</code></pre>
<p>I can't figure out how to add the <strong>#section12</strong> part. The "section" word is just the convention I am using to break up the page sections, and the 12 is the ID of the subcategory, i.e., child.ID.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 274637,
"author": "LorenzCK",
"author_id": 3118,
"author_profile": "https://Stackoverflow.com/users/3118",
"pm_score": 8,
"selected": true,
"text": "<p>I would probably build the link manually, like this:</p>\n\n<pre><code><a href=\"<%=Url.Action(\"Subcategory\", \"Category\", new { categoryID = parent.ID }) %>#section12\">link text</a>\n</code></pre>\n"
},
{
"answer_id": 275499,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 8,
"selected": false,
"text": "<p>There are overloads of ActionLink which take a <strong>fragment</strong> parameter. Passing \"section12\" as your fragment will get you the behavior you're after.</p>\n\n<p>For example, calling <a href=\"http://msdn.microsoft.com/en-us/library/dd460522.aspx\" rel=\"noreferrer\">LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object)</a>:</p>\n\n<pre><code><%= Html.ActionLink(\"Link Text\", \"Action\", \"Controller\", null, null, \"section12-the-anchor\", new { categoryid = \"blah\"}, null) %>\n</code></pre>\n"
},
{
"answer_id": 8924942,
"author": "Spikeh",
"author_id": 1081240,
"author_profile": "https://Stackoverflow.com/users/1081240",
"pm_score": 0,
"selected": false,
"text": "<p>My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:</p>\n\n<p><a href=\"http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html\" rel=\"nofollow\">http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html</a></p>\n\n<p>It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.</p>\n\n<p>You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!</p>\n\n<p>Hope it helps :)</p>\n"
},
{
"answer_id": 26088408,
"author": "PussInBoots",
"author_id": 687549,
"author_profile": "https://Stackoverflow.com/users/687549",
"pm_score": 4,
"selected": false,
"text": "<p>I don't remember in which version of ASP.NET MVC (ASP.NET MVC 3+ I believe) / Razor the parameterlabeldeclaration or whatever it's called (parameter: x) feature was introduced, but to me this is definitely the proper way to build a link with an anchor in ASP.NET MVC.</p>\n\n<pre><code>@Html.ActionLink(\"Some link text\", \"MyAction\", \"MyController\", protocol: null, hostName: null, fragment: \"MyAnchor\", routeValues: null, htmlAttributes: null)\n</code></pre>\n\n<p>Not even Ed Blackburns antipattern argument from <a href=\"https://stackoverflow.com/a/274637/687549\">this answer</a> can compete with that.</p>\n"
},
{
"answer_id": 27249511,
"author": "NoWar",
"author_id": 196919,
"author_profile": "https://Stackoverflow.com/users/196919",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the real life example</p>\n\n<pre><code>@Html.Grid(Model).Columns(columns =>\n {\n columns.Add()\n .Encoded(false)\n .Sanitized(false)\n .SetWidth(10)\n .Titled(string.Empty)\n .RenderValueAs(x => @Html.ActionLink(\"Edit\", \"UserDetails\", \"Membership\", null, null, \"discount\", new { @id = @x.Id }, new { @target = \"_blank\" }));\n\n }).WithPaging(200).EmptyText(\"There Are No Items To Display\")\n</code></pre>\n\n<p>And the target page has TABS</p>\n\n<pre><code><ul id=\"myTab\" class=\"nav nav-tabs\" role=\"tablist\">\n\n <li class=\"active\"><a href=\"#discount\" role=\"tab\" data-toggle=\"tab\">Discount</a></li>\n </ul>\n</code></pre>\n"
},
{
"answer_id": 35956305,
"author": "Ahmed Samir",
"author_id": 3209817,
"author_profile": "https://Stackoverflow.com/users/3209817",
"pm_score": 0,
"selected": false,
"text": "<p>I Did that and it works for redirecting to other view \nI think If you add the #sectionLink after It will work</p>\n\n<pre><code><a class=\"btn yellow\" href=\"/users/Create/@Model.Id\" target=\"_blank\">\n Add As User\n </a>\n</code></pre>\n"
},
{
"answer_id": 37894890,
"author": "Zapnologica",
"author_id": 1331971,
"author_profile": "https://Stackoverflow.com/users/1331971",
"pm_score": 4,
"selected": false,
"text": "<p>I just did it like this:</p>\n\n<pre><code><a href=\"@Url.Action(\"Index\",\"Home\")#features\">Features</a>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29092/"
] |
In ASP.NET MVC, I'm trying to create a link that includes an anchor tag (that is, directing the user to a page, and a specific section of the page).
The URL I am trying to create should look like the following:
```
<a href="/category/subcategory/1#section12">Title for a section on the page</a>
```
My routing is set up with the standard:
```
routes.MapRoute("Default", "{controller}/{action}/{categoryid}");
```
The action link syntax that I am using is:
```
<%foreach (Category parent in ViewData.Model) { %>
<h3><%=parent.Name %></h3>
<ul>
<%foreach (Category child in parent.SubCategories) { %>
<li><%=Html.ActionLink<CategoryController>(x => x.Subcategory(parent.ID), child.Name) %></li>
<%} %>
</ul>
<%} %>
```
My controller method is as follows:
```
public ActionResult Subcategory(int categoryID)
{
//return itemList
return View(itemList);
}
```
The above correctly returns a URL as follows:
```
<a href="/category/subcategory/1">Title for a section on the page</a>
```
I can't figure out how to add the **#section12** part. The "section" word is just the convention I am using to break up the page sections, and the 12 is the ID of the subcategory, i.e., child.ID.
How can I do this?
|
I would probably build the link manually, like this:
```
<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>
```
|
274,619 |
<p>My platform: Visual C# 2008 Express Edition with NUnit 2.2.7</p>
<p>I have a solution with my code in one project and my NUnit unit tests in a different project in the same solution.</p>
<p>I have been struggling hard to debug and single-step through the NUnit tests. I found some references online that suggested calling the following:</p>
<pre><code>NUnit.ConsoleRunner.Runner.Main(args);
</code></pre>
<p>But this doesn't even compile - it has the compiler error:</p>
<blockquote>
<p>Error 1 The type or namespace name
'Runner' does not exist in the
namespace 'NUnit.ConsoleRunner' (are
you missing an assembly reference?)</p>
</blockquote>
<p>I've added every assembly reference I could find, to no effect.</p>
<p>Finally, this is what I have hacked together and it works, but perhaps you good readers could suggest a better solution:</p>
<p>1) In my test project, the class name of a test case that I want to debug is MyTestClass. It has a [TestFixtureSetUp] method named Init() and the actual test case is in [Test] function MyTest()</p>
<p>2) In my code project, I have a console program TestProgram.cs which compiles to an EXE.</p>
<p>In TestProgram.cs, I call the test cases in the following way</p>
<pre><code>// First instantiate the test class
MyTestClass tc = new MyTestClass();
// Call the TestFixtureSetup method
tc.Init();
// Now call the actual test
tc.MyTest();
</code></pre>
<p>This works and I can debug and single step through the test cases.</p>
<p>If anyone has any better suggestions using Visual Studio 2008 Express <em>without paying for additional plugins</em>, I appreciate your advice.</p>
|
[
{
"answer_id": 274624,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 0,
"selected": false,
"text": "<p>At my shop, we're doing it exactly as you do. On the downside, this means that setup might not be exactly as NUnit does it. On the upside, it is quite simple to do and allows one to create a minimal environment to reproduce the bug.</p>\n"
},
{
"answer_id": 274628,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "<p>Since you're using an Express version of Visual Studio, you cannot use the free TestDriven.NET add-in. That's unfortunate, because that really is the best tool I've used to debug unit tests.</p>\n\n<p>The <code>Runner</code> class can be found in the <em>nunit-console-runner.dll</em> assembly, so be sure to add a reference to that. I'm not sure there's anything it does that your simple entry point does not, but it is probably best to use it to be safe and for future compatibility.</p>\n\n<p>One other (dirty) option worth mentioning is for your unit test to invoke <code>Debugger.Attach()</code>. I haven't tried this with an express install, but you should be prompted to attach a debugger when your unit test runs. You can then select your existing VS instance and debug with that.</p>\n"
},
{
"answer_id": 274701,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I found some references online that\n suggested calling the following:\n <code>NUnit.ConsoleRunner.Runner.Main(args);</code>\n But this doesn't even compile - it has\n the compiler error:</p>\n</blockquote>\n\n<p>JFYI\nYou need to add a .NET DLL reference to <strong>nunit-console-runner</strong> assembly in the NUnit DLL bundle ( I have 2.2.4.0 )\nSeems like the class has also been renamed but its there if you need it. </p>\n\n<pre><code>NUnit.ConsoleRunner.ConsoleUi.Main(args);\n</code></pre>\n"
},
{
"answer_id": 274707,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p>Jon as a good way but not the more automatic one ;)</p>\n\n<p>Here is what I <a href=\"https://stackoverflow.com/questions/247900/is-there-a-free-visual-studio-addin-for-nunit#247920\">already say on SO</a>:</p>\n\n<p>You can create a blank project (choose console application for example) and in the property of the project you can select DEBUG tag and select <code>Start External Program</code>. Put the path of Nunit. Than, in the start option, the command line arguments select the DLL that contain all your test (mine is always in the nunit\\bin...). Than select <code>Enable unmanaged code debugging</code> and you will be able to start the project inside VS and even use the debugger step-by-step.</p>\n\n<p>This way, you do not need macro or anything to be done every time, it's just a normal F5 :)</p>\n"
},
{
"answer_id": 526421,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 2,
"selected": false,
"text": "<p>Have a look at <a href=\"http://nunit.com/blogs/?p=28\" rel=\"nofollow noreferrer\">http://nunit.com/blogs/?p=28</a></p>\n\n<p>This works a treat.</p>\n"
},
{
"answer_id": 526429,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<p>If you have ReSharper installed it should be able to detect your [Test] fixtures and place an icon to the left of each method to run, and to the left of each test fixture to run all. I prefer this way.</p>\n\n<p>Most of the people at work also have TestDriven.NET, which for some reason isn't on my machine, so they wonder what's going on. It's kinda funny.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18542/"
] |
My platform: Visual C# 2008 Express Edition with NUnit 2.2.7
I have a solution with my code in one project and my NUnit unit tests in a different project in the same solution.
I have been struggling hard to debug and single-step through the NUnit tests. I found some references online that suggested calling the following:
```
NUnit.ConsoleRunner.Runner.Main(args);
```
But this doesn't even compile - it has the compiler error:
>
> Error 1 The type or namespace name
> 'Runner' does not exist in the
> namespace 'NUnit.ConsoleRunner' (are
> you missing an assembly reference?)
>
>
>
I've added every assembly reference I could find, to no effect.
Finally, this is what I have hacked together and it works, but perhaps you good readers could suggest a better solution:
1) In my test project, the class name of a test case that I want to debug is MyTestClass. It has a [TestFixtureSetUp] method named Init() and the actual test case is in [Test] function MyTest()
2) In my code project, I have a console program TestProgram.cs which compiles to an EXE.
In TestProgram.cs, I call the test cases in the following way
```
// First instantiate the test class
MyTestClass tc = new MyTestClass();
// Call the TestFixtureSetup method
tc.Init();
// Now call the actual test
tc.MyTest();
```
This works and I can debug and single step through the test cases.
If anyone has any better suggestions using Visual Studio 2008 Express *without paying for additional plugins*, I appreciate your advice.
|
Since you're using an Express version of Visual Studio, you cannot use the free TestDriven.NET add-in. That's unfortunate, because that really is the best tool I've used to debug unit tests.
The `Runner` class can be found in the *nunit-console-runner.dll* assembly, so be sure to add a reference to that. I'm not sure there's anything it does that your simple entry point does not, but it is probably best to use it to be safe and for future compatibility.
One other (dirty) option worth mentioning is for your unit test to invoke `Debugger.Attach()`. I haven't tried this with an express install, but you should be prompted to attach a debugger when your unit test runs. You can then select your existing VS instance and debug with that.
|
274,626 |
<p>In c++ what is object slicing and when does it occur?</p>
|
[
{
"answer_id": 274630,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 5,
"selected": false,
"text": "<p>Third match in google for \"C++ slicing\" gives me this Wikipedia article <a href=\"http://en.wikipedia.org/wiki/Object_slicing\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Object_slicing</a> and this (heated, but the first few posts define the problem) : <a href=\"http://bytes.com/forum/thread163565.html\" rel=\"noreferrer\">http://bytes.com/forum/thread163565.html</a></p>\n\n<p>So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets \"sliced off\".</p>\n\n<p>If those links don't give enough info for a \"good answer\" please edit your question to let us know what more you're looking for.</p>\n"
},
{
"answer_id": 274634,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 9,
"selected": false,
"text": "<p>\"Slicing\" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is \"sliced\" away.</p>\n\n<p>For example, </p>\n\n<pre><code>class A {\n int foo;\n};\n\nclass B : public A {\n int bar;\n};\n</code></pre>\n\n<p>So an object of type <code>B</code> has two data members, <code>foo</code> and <code>bar</code>.</p>\n\n<p>Then if you were to write this:</p>\n\n<pre><code>B b;\n\nA a = b;\n</code></pre>\n\n<p>Then the information in <code>b</code> about member <code>bar</code> is lost in <code>a</code>.</p>\n"
},
{
"answer_id": 274636,
"author": "Black",
"author_id": 25234,
"author_profile": "https://Stackoverflow.com/users/25234",
"pm_score": 7,
"selected": false,
"text": "<p>If You have a base class <code>A</code> and a derived class <code>B</code>, then You can do the following.</p>\n\n<pre><code>void wantAnA(A myA)\n{\n // work with myA\n}\n\nB derived;\n// work with the object \"derived\"\nwantAnA(derived);\n</code></pre>\n\n<p>Now the method <code>wantAnA</code> needs a copy of <code>derived</code>. However, the object <code>derived</code> cannot be copied completely, as the class <code>B</code> could invent additional member variables which are not in its base class <code>A</code>.</p>\n\n<p>Therefore, to call <code>wantAnA</code>, the compiler will \"slice off\" all additional members of the derived class. The result might be an object you did not want to create, because</p>\n\n<ul>\n<li>it may be incomplete,</li>\n<li>it behaves like an <code>A</code>-object (all special behaviour of the class <code>B</code> is lost).</li>\n</ul>\n"
},
{
"answer_id": 274654,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 5,
"selected": false,
"text": "<p>The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.</p>\n\n<p>Consider class A, and class B derived from A. Memory corruption can happen if the A part has a pointer p, and a B instance that points p to B's additional data. Then, when the additional data gets sliced off, p is pointing to garbage.</p>\n"
},
{
"answer_id": 274977,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 3,
"selected": false,
"text": "<p>So ... Why is losing the derived information bad? ... because the author of the derived class may have changed the representation such that slicing off the extra information changes the value being represented by the object. This can happen if the derived class if used to cache a representation that is more efficient for certain operations, but expensive to transform back to the base representation.</p>\n\n<p>Also thought someone should also mention what you should do to avoid slicing...\nGet a copy of C++ Coding Standards, 101 rules guidlines, and best practices. Dealing with slicing is #54.</p>\n\n<p>It suggests a somewhat sophisticated pattern to fully deal with the issue: have a protected copy constructor, a protected pure virtual DoClone, and a public Clone with an assert which will tell you if a (further) derived class failed to implement DoClone correctly. (The Clone method makes a proper deep copy of the polymorphic object.)</p>\n\n<p>You can also mark the copy constructor on the base explicit which allows for explicit slicing if it is desired.</p>\n"
},
{
"answer_id": 275428,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 3,
"selected": false,
"text": "<p>The slicing problem in C++ arises from the value semantics of its objects, which remained mostly due to compatibility with C structs. You need to use explicit reference or pointer syntax to achieve \"normal\" object behavior found in most other languages that do objects, i.e., objects are always passed around by reference.</p>\n\n<p>The short answers is that you slice the object by assigning a derived object to a base object <em>by value</em>, i.e. the remaining object is only a part of the derived object. In order to preserve value semantics, slicing is a reasonable behavior and has its relatively rare uses, which doesn't exist in most other languages. Some people consider it a feature of C++, while many considered it one of the quirks/misfeatures of C++.</p>\n"
},
{
"answer_id": 1179794,
"author": "Minok",
"author_id": 144719,
"author_profile": "https://Stackoverflow.com/users/144719",
"pm_score": 2,
"selected": false,
"text": "<p>It seems to me, that slicing isn't so much a problem other than when your own classes and program are poorly architected/designed.</p>\n\n<p>If I pass a subclass object in as a parameter to a method, which takes a parameter of type superclass, I should certainly be aware of that and know the internally, the called method will be working with the superclass (aka baseclass) object only.</p>\n\n<p>It seems to me only the unreasonable expectation that providing a subclass where a baseclass is requested, would somehow result in subclass specific results, would cause slicing to be a problem. Its either poor design in the use of the method or a poor subclass implementation. I'm guessing its usually the result of sacrificing good OOP design in favor of expediency or performance gains.</p>\n"
},
{
"answer_id": 9047531,
"author": "haberdar",
"author_id": 1154908,
"author_profile": "https://Stackoverflow.com/users/1154908",
"pm_score": 3,
"selected": false,
"text": "<p><strong>1. THE DEFINITION OF SLICING PROBLEM</strong></p>\n\n<p>If D is a derived class of the base class B, then you can assign an object of type Derived to a variable (or parameter) of type Base. </p>\n\n<p><em>EXAMPLE</em></p>\n\n<pre><code>class Pet\n{\n public:\n string name;\n};\nclass Dog : public Pet\n{\npublic:\n string breed;\n};\n\nint main()\n{ \n Dog dog;\n Pet pet;\n\n dog.name = \"Tommy\";\n dog.breed = \"Kangal Dog\";\n pet = dog;\n cout << pet.breed; //ERROR\n</code></pre>\n\n<p>Although the above assignment is allowed, the value that is assigned to the variable pet loses its breed field. This is called the <strong>slicing problem</strong>.</p>\n\n<p><strong>2. HOW TO FIX THE SLICING PROBLEM</strong></p>\n\n<p>To defeat the problem, we use pointers to dynamic variables.</p>\n\n<p><em>EXAMPLE</em></p>\n\n<pre><code>Pet *ptrP;\nDog *ptrD;\nptrD = new Dog; \nptrD->name = \"Tommy\";\nptrD->breed = \"Kangal Dog\";\nptrP = ptrD;\ncout << ((Dog *)ptrP)->breed; \n</code></pre>\n\n<p>In this case, none of the data members or member functions of the dynamic variable\nbeing pointed to by ptrD (descendant class object) will be lost. In addition, if you need to use functions, the function must be a virtual function.</p>\n"
},
{
"answer_id": 12946588,
"author": "Dude",
"author_id": 1634073,
"author_profile": "https://Stackoverflow.com/users/1634073",
"pm_score": 2,
"selected": false,
"text": "<p>OK, I'll give it a try after reading many posts explaining object slicing but not how it becomes problematic. </p>\n\n<p>The vicious scenario that can result in memory corruption is the following:</p>\n\n<ul>\n<li>Class provides (accidentally, possibly compiler-generated) assignment on a polymorphic base class.</li>\n<li>Client copies and slices an instance of a derived class.</li>\n<li>Client calls a virtual member function that accesses the sliced-off state.</li>\n</ul>\n"
},
{
"answer_id": 13625934,
"author": "quidkid",
"author_id": 1863203,
"author_profile": "https://Stackoverflow.com/users/1863203",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class A \n{ \n int x; \n}; \n\nclass B \n{ \n B( ) : x(1), c('a') { } \n int x; \n char c; \n}; \n\nint main( ) \n{ \n A a; \n B b; \n a = b; // b.c == 'a' is \"sliced\" off\n return 0; \n}\n</code></pre>\n"
},
{
"answer_id": 14461532,
"author": "fgp",
"author_id": 1582403,
"author_profile": "https://Stackoverflow.com/users/1582403",
"pm_score": 9,
"selected": false,
"text": "<p>Most answers here fail to explain what the actual problem with slicing is. They only explain the benign cases of slicing, not the treacherous ones. Assume, like the other answers, that you're dealing with two classes <code>A</code> and <code>B</code>, where <code>B</code> derives (publicly) from <code>A</code>.</p>\n\n<p>In this situation, C++ lets you pass an instance of <code>B</code> to <code>A</code>'s assignment operator (and also to the copy constructor). This works because an instance of <code>B</code> can be converted to a <code>const A&</code>, which is what assignment operators and copy-constructors expect their arguments to be.</p>\n\n<h3>The benign case</h3>\n\n<pre><code>B b;\nA a = b;\n</code></pre>\n\n<p>Nothing bad happens there - you asked for an instance of <code>A</code> which is a copy of <code>B</code>, and that's exactly what you get. Sure, <code>a</code> won't contain some of <code>b</code>'s members, but how should it? It's an <code>A</code>, after all, not a <code>B</code>, so it hasn't even <em>heard</em> about these members, let alone would be able to store them.</p>\n\n<h3>The treacherous case</h3>\n\n<pre><code>B b1;\nB b2;\nA& a_ref = b2;\na_ref = b1;\n//b2 now contains a mixture of b1 and b2!\n</code></pre>\n\n<p>You might think that <code>b2</code> will be a copy of <code>b1</code> afterward. But, alas, it's <strong>not</strong>! If you inspect it, you'll discover that <code>b2</code> is a Frankensteinian creature, made from some chunks of <code>b1</code> (the chunks that <code>B</code> inherits from <code>A</code>), and some chunks of <code>b2</code> (the chunks that only <code>B</code> contains). Ouch!</p>\n\n<p>What happened? Well, C++ by default doesn't treat assignment operators as <code>virtual</code>. Thus, the line <code>a_ref = b1</code> will call the assignment operator of <code>A</code>, not that of <code>B</code>. This is because, for non-virtual functions, the <strong>declared</strong> (formally: <em>static</em>) type (which is <code>A&</code>) determines which function is called, as opposed to the <strong>actual</strong> (formally: <em>dynamic</em>) type (which would be <code>B</code>, since <code>a_ref</code> references an instance of <code>B</code>). Now, <code>A</code>'s assignment operator obviously knows only about the members declared in <code>A</code>, so it will copy only those, leaving the members added in <code>B</code> unchanged.</p>\n\n<h3>A solution</h3>\n\n<p>Assigning only to parts of an object usually makes little sense, yet C++, unfortunately, provides no built-in way to forbid this. You can, however, roll your own. The first step is making the assignment operator <em>virtual</em>. This will guarantee that it's always the <strong>actual</strong> type's assignment operator which is called, not the <strong>declared</strong> type's. The second step is to use <code>dynamic_cast</code> to verify that the assigned object has a compatible type. The third step is to do the actual assignment in a (protected!) member <code>assign()</code>, since <code>B</code>'s <code>assign()</code> will probably want to use <code>A</code>'s <code>assign()</code> to copy <code>A</code>'s, members.</p>\n\n<pre><code>class A {\npublic:\n virtual A& operator= (const A& a) {\n assign(a);\n return *this;\n }\n\nprotected:\n void assign(const A& a) {\n // copy members of A from a to this\n }\n};\n\nclass B : public A {\npublic:\n virtual B& operator= (const A& a) {\n if (const B* b = dynamic_cast<const B*>(&a))\n assign(*b);\n else\n throw bad_assignment();\n return *this;\n }\n\nprotected:\n void assign(const B& b) {\n A::assign(b); // Let A's assign() copy members of A from b to this\n // copy members of B from b to this\n }\n};\n</code></pre>\n\n<p>Note that, for pure convenience, <code>B</code>'s <code>operator=</code> covariantly overrides the return type, since it <strong>knows</strong> that it's returning an instance of <code>B</code>.</p>\n"
},
{
"answer_id": 22360211,
"author": "Santosh",
"author_id": 3240133,
"author_profile": "https://Stackoverflow.com/users/3240133",
"pm_score": 2,
"selected": false,
"text": "<p>Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object. </p>\n\n<p><strong>Explanation:</strong>\nConsider the following class declaration:</p>\n\n<pre><code> class baseclass\n {\n ...\n baseclass & operator =(const baseclass&);\n baseclass(const baseclass&);\n }\n void function( )\n {\n baseclass obj1=m;\n obj1=m;\n }\n</code></pre>\n\n<p>As baseclass copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. </p>\n"
},
{
"answer_id": 25453490,
"author": "geh",
"author_id": 2916579,
"author_profile": "https://Stackoverflow.com/users/2916579",
"pm_score": 6,
"selected": false,
"text": "<p>These are all good answers. I would just like to add an execution example when passing objects by value vs by reference:</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\n// Base class\nclass A {\npublic:\n A() {}\n A(const A& a) {\n cout << \"'A' copy constructor\" << endl;\n }\n virtual void run() const { cout << \"I am an 'A'\" << endl; }\n};\n\n// Derived class\nclass B: public A {\npublic:\n B():A() {}\n B(const B& a):A(a) {\n cout << \"'B' copy constructor\" << endl;\n }\n virtual void run() const { cout << \"I am a 'B'\" << endl; }\n};\n\nvoid g(const A & a) {\n a.run();\n}\n\nvoid h(const A a) {\n a.run();\n}\n\nint main() {\n cout << \"Call by reference\" << endl;\n g(B());\n cout << endl << \"Call by copy\" << endl;\n h(B());\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>Call by reference\nI am a 'B'\n\nCall by copy\n'A' copy constructor\nI am an 'A'\n</code></pre>\n"
},
{
"answer_id": 37156090,
"author": "Varun Kumar",
"author_id": 3514002,
"author_profile": "https://Stackoverflow.com/users/3514002",
"pm_score": -1,
"selected": false,
"text": "<p>when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off (discard) form the base class object.</p>\n\n<pre><code>class Base { \nint x;\n };\n\nclass Derived : public Base { \n int z; \n };\n\n int main() \n{\nDerived d;\nBase b = d; // Object Slicing, z of d is sliced off\n}\n</code></pre>\n"
},
{
"answer_id": 45184425,
"author": "Ghulam Moinul Quadir",
"author_id": 7857932,
"author_profile": "https://Stackoverflow.com/users/7857932",
"pm_score": -1,
"selected": false,
"text": "<p>When a Derived class Object is assigned to Base class Object, all the members of derived class object is copied to base class object except the members which are not present in the base class. These members are Sliced away by the compiler.\nThis is called Object Slicing.</p>\n\n<p><strong>Here is an Example:</strong> </p>\n\n<pre><code>#include<bits/stdc++.h>\nusing namespace std;\nclass Base\n{\n public:\n int a;\n int b;\n int c;\n Base()\n {\n a=10;\n b=20;\n c=30;\n }\n};\nclass Derived : public Base\n{\n public:\n int d;\n int e;\n Derived()\n {\n d=40;\n e=50;\n }\n};\nint main()\n{\n Derived d;\n cout<<d.a<<\"\\n\";\n cout<<d.b<<\"\\n\";\n cout<<d.c<<\"\\n\";\n cout<<d.d<<\"\\n\";\n cout<<d.e<<\"\\n\";\n\n\n Base b = d;\n cout<<b.a<<\"\\n\";\n cout<<b.b<<\"\\n\";\n cout<<b.c<<\"\\n\";\n cout<<b.d<<\"\\n\";\n cout<<b.e<<\"\\n\";\n return 0;\n}\n</code></pre>\n\n<p><strong>It will generate:</strong></p>\n\n<pre><code>[Error] 'class Base' has no member named 'd'\n[Error] 'class Base' has no member named 'e'\n</code></pre>\n"
},
{
"answer_id": 46725480,
"author": "Martin B.",
"author_id": 7917910,
"author_profile": "https://Stackoverflow.com/users/7917910",
"pm_score": -1,
"selected": false,
"text": "<p>I just ran across the slicing problem and promptly landed here. So let me add my two cents to this.</p>\n\n<p>Let's have an example from \"production code\" (or something that comes kind of close):</p>\n\n<hr>\n\n<p>Let's say we have something that dispatches actions. A control center UI for example.<br>\nThis UI needs to get a list of things that are currently able to be dispatched. So we define a class that contains the dispatch-information. Let's call it <code>Action</code>. So an <code>Action</code> has some member variables. For simplicity we just have 2, being a <code>std::string name</code> and a <code>std::function<void()> f</code>. Then it has an <code>void activate()</code> which just executes the <code>f</code> member.</p>\n\n<p>So the UI gets a <code>std::vector<Action></code> supplied. Imagine some functions like:</p>\n\n<pre><code>void push_back(Action toAdd);\n</code></pre>\n\n<hr>\n\n<p>Now we have established how it looks from the UI's perspective. No problem so far. But some other guy who works on this project suddenly decides that there are specialized actions that need more information in the <code>Action</code> object. For what reason ever. That could also be solved with lambda captures. This example is not taken 1-1 from the code.</p>\n\n<p>So the guy derives from <code>Action</code> to add his own flavour.<br>\nHe passes an instance of his home-brewed class to the <code>push_back</code> but then the program goes haywire.</p>\n\n<p>So what happened?<br>\nAs you <em>might</em> have guessed: the object has been sliced.</p>\n\n<p>The extra information from the instance has been lost, and <code>f</code> is now prone to undefined behaviour.</p>\n\n<hr>\n\n<p>I hope this example brings light about for those people who can't really imagine things when talking about <code>A</code>s and <code>B</code>s being derived in some manner.</p>\n"
},
{
"answer_id": 49148511,
"author": "Kartik Maheshwari",
"author_id": 5213931,
"author_profile": "https://Stackoverflow.com/users/5213931",
"pm_score": 4,
"selected": false,
"text": "<p>In C++, a derived class object can be assigned to a base class object, but the other way is not possible.</p>\n\n<pre><code>class Base { int x, y; };\n\nclass Derived : public Base { int z, w; };\n\nint main() \n{\n Derived d;\n Base b = d; // Object Slicing, z and w of d are sliced off\n}\n</code></pre>\n\n<p>Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.</p>\n"
},
{
"answer_id": 63859829,
"author": "Sorush",
"author_id": 2543510,
"author_profile": "https://Stackoverflow.com/users/2543510",
"pm_score": 4,
"selected": false,
"text": "<p>I see all the answers mention when object slicing happens when data members are sliced. Here I give an example that the methods are not overridden:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class A{\npublic:\n virtual void Say(){\n std::cout<<"I am A"<<std::endl;\n }\n};\n\nclass B: public A{\npublic:\n void Say() override{\n std::cout<<"I am B"<<std::endl;\n }\n};\n\nint main(){\n B b;\n A a1;\n A a2=b;\n\n b.Say(); // I am B\n a1.Say(); // I am A\n a2.Say(); // I am A why???\n}\n</code></pre>\n<p>B (object b) is derived from A (object a1 and a2). b and a1, as we expect, call their member function. But from polymorphism viewpoint we don’t expect a2, which is assigned by b, to not be overridden. Basically, a2 only saves A-class part of b and that is object slicing in C++.</p>\n<p>To solve this problem, a reference or pointer should be used</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> A& a2=b;\n a2.Say(); // I am B\n</code></pre>\n<p>or</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>A* a2 = &b;\na2->Say(); // I am B\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35737/"
] |
In c++ what is object slicing and when does it occur?
|
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
For example,
```
class A {
int foo;
};
class B : public A {
int bar;
};
```
So an object of type `B` has two data members, `foo` and `bar`.
Then if you were to write this:
```
B b;
A a = b;
```
Then the information in `b` about member `bar` is lost in `a`.
|
274,646 |
<p>I am getting the following error while loading a page.</p>
<p>[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]</p>
<p>No idea what to do ? Can anyone help me ?</p>
|
[
{
"answer_id": 274688,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 2,
"selected": false,
"text": "<p>I'm guessing you have done something like this:</p>\n\n<pre><code>Response.Redirect(\"../SomePage.aspx\");\n</code></pre>\n\n<p>When using relative paths, you can only navigate to pages that are in the same Virtual Directory as the one the page making the request is in. What you have done is called this from a page that is at the top of the Virtual Directory tree. So you have some options:</p>\n\n<ol>\n<li>Correct your url so that it does not point to a higher level. ie: remove the <code>../</code></li>\n<li>Use a full url. ie: <code>http://www.example.com/SomePage.aspx</code></li>\n<li>Use IIS to set the Virtual Directory at a higher level.</li>\n</ol>\n\n<p>For Option 3: </p>\n\n<ol>\n<li>Open up IIS manager. </li>\n<li>Go to the directory that the page is in and right click/properties. </li>\n<li>On the Virtual Directory tab select Remove.</li>\n<li>Close the dialogue and right click/properties on the directory you do want to be the root.</li>\n<li>On the Virtual Directory tab select Add</li>\n</ol>\n"
},
{
"answer_id": 274729,
"author": "PhilPursglove",
"author_id": 1738,
"author_profile": "https://Stackoverflow.com/users/1738",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on your circumstances this may or may not help but I had this error last week. The solution for me was to change the Web settings in My Project to use the local IIS server instead of the Visual Studio web server.</p>\n"
},
{
"answer_id": 868972,
"author": "Mafti",
"author_id": 15981,
"author_profile": "https://Stackoverflow.com/users/15981",
"pm_score": 1,
"selected": false,
"text": "<p>Most likely a googlebot or some other bots are killing your website.</p>\n\n<p><a href=\"http://www.kowitz.net/archive/2006/12/11/asp.net-2.0-mozilla-browser-detection-hole.aspx\" rel=\"nofollow noreferrer\">http://www.kowitz.net/archive/2006/12/11/asp.net-2.0-mozilla-browser-detection-hole.aspx</a></p>\n\n<p><a href=\"http://todotnet.com/post/2006/07/01/Get-GoogleBot-to-crash-your-NET-20-site.aspx\" rel=\"nofollow noreferrer\">http://todotnet.com/post/2006/07/01/Get-GoogleBot-to-crash-your-NET-20-site.aspx</a></p>\n\n<p>solution is to add .browser files in the app_browser folder of your website.</p>\n"
},
{
"answer_id": 932170,
"author": "salle55",
"author_id": 39636,
"author_profile": "https://Stackoverflow.com/users/39636",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to solve this problem by setting the cookieless-attribute on the forms-tag in web.config:</p>\n\n<pre><code><authentication>\n <forms cookieless=\"UseCookies\" />\n</authentication>\n</code></pre>\n"
},
{
"answer_id": 1834747,
"author": "personaelit",
"author_id": 42574,
"author_profile": "https://Stackoverflow.com/users/42574",
"pm_score": 1,
"selected": false,
"text": "<p>I realize this is as old as sin, but what caused it for me was that I had a relative link for an image in the db set with a ../. When my page tried to load the ImageUrl for the image in the root directory it worked fine but in sub-directories it wigged out.</p>\n\n<p>Changing it to a ~ fixed the problem. </p>\n"
},
{
"answer_id": 10507277,
"author": "PerryM",
"author_id": 69097,
"author_profile": "https://Stackoverflow.com/users/69097",
"pm_score": 0,
"selected": false,
"text": "<p>Apologies as this is very old, but I have had this problem for a few days now on an MVC3 app. \nI kept going into my _Layout.cshtml file and deleting any reference to css files or javascript (I was using JQuery in this app) to find the dreaded ../ reference. I couldn't find one. Then I tried to bypass my issue by just dropping a redirect into my application's root directory. That failed too. The stack track on the YellowScreenOfDeath gave me a clue:</p>\n\n<p><code>[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]\n System.Web.Util.UrlPath.ReduceVirtualPath(String path) +11496719\n System.Web.Util.UrlPath.Reduce(String path) +171\n System.Web.Configuration.**AuthenticationConfig**.GetCompleteLoginUrl(HttpContext context, String loginUrl) +218\n System.Web.Security.FormsAuthenticationModule.OnEnter(Object source, EventArgs eventArgs) +156\n System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80\n System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270</code></p>\n\n<p>Bottom line, I had this in my web.config with a \"../\" Deleting this or changing the up reference fixed my issue.</p>\n\n<pre><code> <authentication mode=\"Forms\">\n <forms loginUrl=\"../home.aspx\" timeout=\"2880\" />\n </authentication>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29982/"
] |
I am getting the following error while loading a page.
[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]
No idea what to do ? Can anyone help me ?
|
I'm guessing you have done something like this:
```
Response.Redirect("../SomePage.aspx");
```
When using relative paths, you can only navigate to pages that are in the same Virtual Directory as the one the page making the request is in. What you have done is called this from a page that is at the top of the Virtual Directory tree. So you have some options:
1. Correct your url so that it does not point to a higher level. ie: remove the `../`
2. Use a full url. ie: `http://www.example.com/SomePage.aspx`
3. Use IIS to set the Virtual Directory at a higher level.
For Option 3:
1. Open up IIS manager.
2. Go to the directory that the page is in and right click/properties.
3. On the Virtual Directory tab select Remove.
4. Close the dialogue and right click/properties on the directory you do want to be the root.
5. On the Virtual Directory tab select Add
|
274,656 |
<p>I've been trying to build subversion (on a limited account) for a long time but without any luck :(</p>
<p>The instructions I'm following: <a href="http://wiki.dreamhost.com/Subversion_Installation" rel="nofollow noreferrer">http://wiki.dreamhost.com/Subversion_Installation</a></p>
<p>Running this:</p>
<pre><code>./configure --prefix=${RUN} --without-berkeley-db --with-ssl --with-zlib --enable-shared
</code></pre>
<p>Gives me this error:</p>
<pre><code>checking for library containing RSA_new... not found
configure: error: could not find library containing RSA_new
configure failed for neon
</code></pre>
<p>Can someone explain to me:</p>
<ol>
<li>Possible reasons for this</li>
<li>Possible ways to circumvent it</li>
<li>Optional: What these modules are and what their purpose is (Neon/RSA_new)</li>
</ol>
<p>Thanks!</p>
<h2>Log file contents:</h2>
<p>Trying to find interesting bits from the neon config.log file:</p>
<pre><code>configure:27693: gcc -o conftest -g -O2 conftest.c >&5
/tmp/ccazXdJz.o: In function `main':
/home/stpinst/soft/subversion-1.5.4/neon/conftest.c:93: undefined reference to `RSA_new'
collect2: ld returned 1 exit status
configure:27699: $? = 1
configure: failed program was:
...
| int
| main ()
| {
| RSA_new();
| ;
| return 0;
| }
configure:27742: gcc -o conftest -g -O2 conftest.c -lcrypto -lz >&5
/usr/bin/ld: cannot find -lcrypto
collect2: ld returned 1 exit status
configure:27748: $? = 1
</code></pre>
<p>--</p>
|
[
{
"answer_id": 274661,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>you don't have libcrypto.a and libcrypto.so on your system</li>\n<li>you need to install install libcrypto, which is in the libssl-dev package (<code>aptitude install libssl-dev</code>)</li>\n<li>Neon is the WebDAV library included in subversion; WebDAV being one of the wire protocols that subversion supports (http:). RSA is an encryption algorithm. Neon doesn't actually need it itself - it's just that configure uses it to determine whether libcrypto is available.</li>\n</ol>\n"
},
{
"answer_id": 274666,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>did you check <a href=\"http://blogs.oracle.com/rama/entry/compiling_subversion_with_ssl_support\" rel=\"nofollow noreferrer\">Compiling Subversion with SSL Support</a>, where the following varaibles were needed to complete the process ?</p>\n\n<pre><code>setenv CC \"gcc -I/usr/local/ssl/include -L/usr/local/ssl/lib\"\nsetenv CFLAGS \"-O2 -g -I/usr/local/ssl/include\"\nsetenv LDFLAGS \"-L/usr/local/ssl/lib\"\nsetenv CPP \"gcc -E -I/usr/local/ssl/include\"\n</code></pre>\n\n<p>And the post <a href=\"http://svn.haxx.se/users/archive-2006-05/0483.shtml\" rel=\"nofollow noreferrer\">could not find library containing RSA_new</a>, recommend to made sure the headers were also installed on the system (Debian-Ubuntu-Dapper-Beta2: \"apt-get install libssl-dev\"), or as <a href=\"https://stackoverflow.com/questions/274656/building-subversion-154-on-debian-could-not-find-library-containing-rsanew#274661\">Martin says</a>: aptitude install libssl-dev.</p>\n\n<p>In short, either the headers are not there, or they are not in the proper path during the configure process.</p>\n"
},
{
"answer_id": 274889,
"author": "AtliB",
"author_id": 18274,
"author_profile": "https://Stackoverflow.com/users/18274",
"pm_score": 0,
"selected": false,
"text": "<p>NB: I'm using a <strong>shared host</strong> so I'm not able to do some things.</p>\n\n<p>Calling </p>\n\n<pre><code>apt-get install libssl-dev\n</code></pre>\n\n<p>gives me this error:</p>\n\n<pre><code>E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)\nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root?\n</code></pre>\n\n<p>Calling \n aptitude install libssl-dev</p>\n\n<p>gives me this error: </p>\n\n<pre><code>E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied) \nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root\n</code></pre>\n\n<p>As you can perhaps see, I'm totally lost so any further hand-holding would be greatly appreciated! :)</p>\n"
},
{
"answer_id": 274902,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>You either need to install OpenSSL first, or configure --without-ssl (or just omit the --with-ssl option if you have been following the instructions literally).</p>\n"
},
{
"answer_id": 274936,
"author": "AtliB",
"author_id": 18274,
"author_profile": "https://Stackoverflow.com/users/18274",
"pm_score": 1,
"selected": false,
"text": "<p>If I skip the SSL:</p>\n\n<pre><code>./configure --prefix=${RUN} --without-ssl\n</code></pre>\n\n<p>I get this error:</p>\n\n<pre><code>checking for openssl/opensslv.h... no\nconfigure: error: We require OpenSSL; try --with-openssl\nconfigure failed for serf\n</code></pre>\n\n<p>If i do:</p>\n\n<pre><code> ./configure --prefix=${RUN} --with-openssl\n</code></pre>\n\n<p>I get a warning:</p>\n\n<pre><code>configure: WARNING: Unrecognized options: --with-openssl\n...\nconfigure: error: '--with-openssl requires a path to a directory'\nconfigure failed for serf\n</code></pre>\n\n<p>:-s</p>\n"
},
{
"answer_id": 275296,
"author": "AtliB",
"author_id": 18274,
"author_profile": "https://Stackoverflow.com/users/18274",
"pm_score": 0,
"selected": false,
"text": "<p>I think I've finally got the \"configure\" part to work.</p>\n\n<p>First, I retrieved openssl locally:</p>\n\n<pre><code>wget http://www.openssl.org/source/openssl-0.9.8a.tar.gz\ntar zxvf openssl-0.9.8a.tar.gz\ncd openssl-0.9.8a\n./configure --prefix=${RUN}\nmake\nmake install\n</code></pre>\n\n<p>Then I built subversion with a reference to that folder:</p>\n\n<pre><code>./configure --prefix=${RUN} --without-berkeley-db --with-openssl=$HOME/soft/openssl-0.9.8a\n</code></pre>\n\n<p>I actually got this warning:</p>\n\n<pre><code>configure: WARNING: Unrecognized options: --with-openssl\n</code></pre>\n\n<p>Now that I though I had it all covered, it compiles for a few minutes but then gives me this error:</p>\n\n<pre><code>link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libsqlite 3.la' seems to be moved\nlibtool: link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libsqlite .la' seems to be moved\nlibtool: link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libexpat. la' seems to be moved\n/usr/bin/ld: cannot find -lssl\ncollect2: ld returned 1 exit status\nmake[1]: *** [libserf-0.la] Error 1\nmake[1]: Leaving directory `/mnt/local/home/stpinst/soft/subversion-1.5.4/serf'\nmake: *** [external-all] Error 1\n</code></pre>\n\n<p>This seems to be the neverending story... can I somewhere just download the latest binaries?</p>\n"
},
{
"answer_id": 330062,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 3,
"selected": true,
"text": "<p>Check out my response over <a href=\"https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account#330061\">here</a>.</p>\n"
},
{
"answer_id": 2044428,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 2,
"selected": false,
"text": "<p>Finally got it to work.\nHow:\ndownload openssl-0.x.x.tar.gz, unpack, cd into it</p>\n\n<p>install it somewhere, like (for me)</p>\n\n<pre><code>$ ./config shared --prefix=$HOME/installs && make clean && make && make install\n\n$ export CFLAGS= \"-O2 -g -I/root/installs/include\"\n$ export CFLAGS=\"-O2 -g -I/root/installs/include\"\n$ export LDFLAGS=\"-L/root/installs/lib\"\n$ export CPP=\"gcc -E -I/root/installs/include\"\n</code></pre>\n\n<p>unpack the subversion + its deps</p>\n\n<p>go into the neon subdirectory</p>\n\n<pre><code>$ ./configure --with-ssl=openssl --prefix=$HOME/installs && make clean && make && make install\n</code></pre>\n\n<p>delete the neon directory</p>\n\n<p>go into the subversion directory</p>\n\n<pre><code>$ ./configure --with-ssl --prefix=$HOME/installs --with-neon=/root/installs/bin/neon-config && make clean && make && make install\n</code></pre>\n\n<p>Note: you might be able to get away without all the exports by using --with-ssl=/root/installs or something along those lines.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18274/"
] |
I've been trying to build subversion (on a limited account) for a long time but without any luck :(
The instructions I'm following: <http://wiki.dreamhost.com/Subversion_Installation>
Running this:
```
./configure --prefix=${RUN} --without-berkeley-db --with-ssl --with-zlib --enable-shared
```
Gives me this error:
```
checking for library containing RSA_new... not found
configure: error: could not find library containing RSA_new
configure failed for neon
```
Can someone explain to me:
1. Possible reasons for this
2. Possible ways to circumvent it
3. Optional: What these modules are and what their purpose is (Neon/RSA\_new)
Thanks!
Log file contents:
------------------
Trying to find interesting bits from the neon config.log file:
```
configure:27693: gcc -o conftest -g -O2 conftest.c >&5
/tmp/ccazXdJz.o: In function `main':
/home/stpinst/soft/subversion-1.5.4/neon/conftest.c:93: undefined reference to `RSA_new'
collect2: ld returned 1 exit status
configure:27699: $? = 1
configure: failed program was:
...
| int
| main ()
| {
| RSA_new();
| ;
| return 0;
| }
configure:27742: gcc -o conftest -g -O2 conftest.c -lcrypto -lz >&5
/usr/bin/ld: cannot find -lcrypto
collect2: ld returned 1 exit status
configure:27748: $? = 1
```
--
|
Check out my response over [here](https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account#330061).
|
274,718 |
<p>I'm attempting to create an audio filter using the JavaSound API to read and write the audio files. Currently my code is structured as follows:</p>
<pre><code> ByteArrayOutputStream b_out = new ByteArrayOutputStream();
// Read a frame from the file.
while (audioInputStream.read(audioBytes) != -1) {
//Do stuff here....
b_out.write(outputvalue);
}
// Hook output stream to output file
ByteArrayInputStream b_in = new ByteArrayInputStream(b_out.toByteArray());
AudioInputStream ais = new AudioInputStream(b_in, format, length);
AudioSystem.write(ais, inFileFormat.getType(), outputFile);
</code></pre>
<p>This reads the input file as a stream, processes it and writes it to a bytearrayoutputstream, but it waits until the entire file has been processed before writing to disk. Ideally, I would like it to write each sample to disk as it's processed. I've tried several combinations of stream constructs but can't find a way of doing it as AudioSystem.write() takes an input stream. Any ideas?</p>
|
[
{
"answer_id": 274811,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": 1,
"selected": false,
"text": "<p>Some audio formats require metadata describing the length of the stream (or the number of chunks) in their header, thus making it impossible to start writing the data before the entire dataset is present. Inorder for the Java sound API to handle all formats with the same API, I suspect they have had to impose this limit on purpose.</p>\n\n<p>There are however many audio formats that can easily be streamed. Many of them have open library implementations for java, so if you are willing to add an external lib it shouldn't be that hard to accomplish.</p>\n"
},
{
"answer_id": 394262,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 2,
"selected": false,
"text": "<p>kasperjj's answer is right. You are probably working with WAV files. Look at <a href=\"http://ccrma.stanford.edu/CCRMA/Courses/422/projects/WaveFormat/\" rel=\"nofollow noreferrer\">this</a>\nfor the layout of a wave file. Note that the size of the entire WAV file is encoded in its header.</p>\n\n<p>I don't know if this is applicable in your case, but to process WAV samples as you described, you can use a \"regular\" non-audio Java output stream. You could use a FileOutputStream for example to write them to a temp file, and after processing you can convert the temp file into a valid WAV file.</p>\n"
},
{
"answer_id": 39190132,
"author": "Kanaris007",
"author_id": 5685534,
"author_profile": "https://Stackoverflow.com/users/5685534",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to solve the issue if you reimplement AudioSystem.write method. It doesn't work with stream and WAVE format. You should read data from AudioInputStream, cache it in byte array, process the array and record to wave file. I would recommend you to check classes from the example: <a href=\"http://privateblog.by/kak-zapisat-zvuk-na-java-v-byte-massiv\" rel=\"nofollow noreferrer\">How to record audio to byte array</a></p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12226/"
] |
I'm attempting to create an audio filter using the JavaSound API to read and write the audio files. Currently my code is structured as follows:
```
ByteArrayOutputStream b_out = new ByteArrayOutputStream();
// Read a frame from the file.
while (audioInputStream.read(audioBytes) != -1) {
//Do stuff here....
b_out.write(outputvalue);
}
// Hook output stream to output file
ByteArrayInputStream b_in = new ByteArrayInputStream(b_out.toByteArray());
AudioInputStream ais = new AudioInputStream(b_in, format, length);
AudioSystem.write(ais, inFileFormat.getType(), outputFile);
```
This reads the input file as a stream, processes it and writes it to a bytearrayoutputstream, but it waits until the entire file has been processed before writing to disk. Ideally, I would like it to write each sample to disk as it's processed. I've tried several combinations of stream constructs but can't find a way of doing it as AudioSystem.write() takes an input stream. Any ideas?
|
kasperjj's answer is right. You are probably working with WAV files. Look at [this](http://ccrma.stanford.edu/CCRMA/Courses/422/projects/WaveFormat/)
for the layout of a wave file. Note that the size of the entire WAV file is encoded in its header.
I don't know if this is applicable in your case, but to process WAV samples as you described, you can use a "regular" non-audio Java output stream. You could use a FileOutputStream for example to write them to a temp file, and after processing you can convert the temp file into a valid WAV file.
|
274,753 |
<p>There seem to be 3 ways of telling GCC to weak link a symbol:</p>
<ul>
<li><code>__attribute__((weak_import))</code></li>
<li><code>__attribute__((weak))</code></li>
<li><code>#pragma weak symbol_name</code></li>
</ul>
<p>None of these work for me:</p>
<pre><code>#pragma weak asdf
extern void asdf(void) __attribute__((weak_import, weak));
...
{
if(asdf != NULL) asdf();
}
</code></pre>
<p>I always get a link error like this:</p>
<pre>Undefined symbols:
"_asdf", referenced from:
_asdf$non_lazy_ptr in ccFA05kN.o
ld: symbol(s) not found
collect2: ld returned 1 exit status</pre>
<p>I am using GCC 4.0.1 on OS X 10.5.5. What am I doing wrong?</p>
|
[
{
"answer_id": 274808,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 1,
"selected": false,
"text": "<p>From the gcc doc manual:</p>\n\n<p><strong>weak</strong></p>\n\n<blockquote>\n <p>The weak attribute causes the declaration to be emitted as a weak\n symbol rather than a global. This is primarily useful in defining\n library functions which can be overridden in user code, though it\n can also be used with non-function declarations. Weak symbols are\n supported for ELF targets, and also for a.out targets when using\n the GNU assembler and linker.</p>\n</blockquote>\n\n<p>which means that an object is legitimated to overwrite a weak symbol (defined in another object/library) without getting errors at link time. What is unclear is whether you are linking the library with the <em>weak</em> symbol or not. It's seems that both you have not defined the symbol and the library is not properly linked.</p>\n"
},
{
"answer_id": 274834,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>You need to set the MACOSX_DEPLOYMENT_TARGET variable to 10.2 or later. See <a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html\" rel=\"nofollow noreferrer\">Apple's documentation</a> and their <a href=\"http://developer.apple.com/technotes/tn2002/tn2064.html\" rel=\"nofollow noreferrer\">technote</a> on weak linking.</p>\n"
},
{
"answer_id": 730267,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Add <code>-Wl,-flat_namespace,-undefined,dynamic_lookup</code> to the gcc compiler line that you use to do the final link.</p>\n"
},
{
"answer_id": 3749780,
"author": "Jeffrey Scofield",
"author_id": 452488,
"author_profile": "https://Stackoverflow.com/users/452488",
"pm_score": 5,
"selected": false,
"text": "<p>I just looked into this and thought some others might be interested in my findings.</p>\n\n<p>Weak linking with weak_import really only works well with dynamic libraries. You can get it to work with static linking (by specifying -undefined dynamic_lookup as suggested above) but this isn't such a hot idea. It means that no undefined symbols will be detected until runtime. This is something I would avoid in production code, personally.</p>\n\n<p>Here is a Mac OS X Terminal session showing how to make it work:</p>\n\n<p>Here is f.c</p>\n\n<pre><code>int f(int n)\n{\n return n * 7;\n}\n</code></pre>\n\n<p>Here is whatnof.c</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nextern int f (int) __attribute__((weak_import));\n\nint main() {\n if(f == NULL)\n printf(\"what, no f?\\n\");\n else\n printf(\"f(8) is %d\\n\", f(8));\n exit(0);\n}\n</code></pre>\n\n<p>Make a dynamic library from f.c:</p>\n\n<pre><code>$ cc -dynamiclib -o f.dylib f.c\n</code></pre>\n\n<p>Compile and link against the dynamic lib, list dynamic libs.</p>\n\n<pre><code>$ cc -o whatnof whatnof.c f.dylib\n$ otool -L whatnof\nwhatnof:\n f.dylib (compatibility version 0.0.0, current version 0.0.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)\n</code></pre>\n\n<p>Run whatnof to see what happens:</p>\n\n<pre><code>$ whatnof\nf(8) is 56\n</code></pre>\n\n<p>Now replace f.dylib with an empty library (no symbols):</p>\n\n<pre><code>$ mv f.dylib f.dylib.real\n$ touch null.c\n$ cc -dynamiclib -o f.dylib null.c\n</code></pre>\n\n<p>Run same whatnof to see what happens:</p>\n\n<pre><code>$ whatnof\nwhat, no f?\n</code></pre>\n\n<p>The basic idea (or \"use case\") for weak_import is that it lets you link against a set of dynamic (shared) libraries, but then run the same code against earlier versions of the same libraries. You can check functions against NULL to see if they're supported in the particular dynamic library that the code is currently running against. This seems to be part of the basic development model supported by Xcode. I hope this example is useful; it has helped put my mind at ease about this part of the Xcode design.</p>\n"
},
{
"answer_id": 54601464,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Minimal runnable Linux example</strong></p>\n\n<p>main.c</p>\n\n<pre><code>#include <stdio.h>\n\nint my_weak_var __attribute__((weak)) = 1;\n\nint main(void) {\n printf(\"%d\\n\", my_weak_var);\n}\n</code></pre>\n\n<p>notmain.c</p>\n\n<pre><code>int my_weak_var = 2;\n</code></pre>\n\n<p>Compile and run with both objects:</p>\n\n<pre><code>gcc -c -std=c99 -Wall -Wextra -pedantic -o main.o main.c\ngcc -c -std=c99 -Wall -Wextra -pedantic -o notmain.o notmain.c\ngcc -std=c99 -Wall -Wextra -pedantic -o main.out main.o notmain.o\n./main.out\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2\n</code></pre>\n\n<p>Compile and run without <code>notmain.o</code>:</p>\n\n<pre><code>gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.o\n./main.out\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1\n</code></pre>\n\n<p><a href=\"https://github.com/cirosantilli/cpp-cheat/tree/46db754b0f327ac03ba8d28b1c9fe019b964e987/gcc/weak\" rel=\"noreferrer\">GitHub upstream</a>.</p>\n\n<p>So we see that if given on <code>notmain.o</code>, then the non-weak symbol takes precedence as expected.</p>\n\n<p>We can analyze the <a href=\"https://stackoverflow.com/questions/26294034/how-to-make-an-executable-elf-file-in-linux-using-a-hex-editor/30648229#30648229\">ELF object file</a> symbols with:</p>\n\n<pre><code>nm main.o notmain.o\n</code></pre>\n\n<p>which gives:</p>\n\n<pre><code>main.o:\n U _GLOBAL_OFFSET_TABLE_\n0000000000000000 T main\n0000000000000000 V my_weak_var\n U printf\n\nnotmain.o:\n0000000000000000 D my_weak_var\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>man nm\n</code></pre>\n\n<p>contains:</p>\n\n<blockquote>\n <p>The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external). There are however a few lowercase symbols that are shown for special global symbols (\"u\", \"v\" and \"w\").</p>\n \n <p>\"D\"<br>\n \"d\" The symbol is in the initialized data section.</p>\n \n <p>\"V\"<br>\n \"v\" The symbol is a weak object. When a weak defined symbol is linked with a normal defined symbol, the normal defined symbol is used with no error. When a weak undefined symbol is linked and the symbol is not defined, the value of the weak symbol becomes zero with no error. On some systems, uppercase indicates that a default value has been specified.</p>\n</blockquote>\n\n<p>If dealing with <code>.a</code> static libraries however, you might have to use <code>-Wl,--whole-archive</code> as explained at: <a href=\"https://stackoverflow.com/questions/13089166/how-to-make-gcc-link-strong-symbol-in-static-library-to-overwrite-weak-symbol\">How to make gcc link strong symbol in static library to overwrite weak symbol?</a></p>\n\n<p>Weak symbols can also be left undefined, which in Binutils leads to \"platform specific behaviour\", see: <a href=\"https://stackoverflow.com/questions/31203402/gcc-behavior-for-unresolved-weak-functions/54602008#54602008\">GCC behavior for unresolved weak functions</a></p>\n\n<p>Tested on Ubuntu 18.10, GCC 8.2.0.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
There seem to be 3 ways of telling GCC to weak link a symbol:
* `__attribute__((weak_import))`
* `__attribute__((weak))`
* `#pragma weak symbol_name`
None of these work for me:
```
#pragma weak asdf
extern void asdf(void) __attribute__((weak_import, weak));
...
{
if(asdf != NULL) asdf();
}
```
I always get a link error like this:
```
Undefined symbols:
"_asdf", referenced from:
_asdf$non_lazy_ptr in ccFA05kN.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
```
I am using GCC 4.0.1 on OS X 10.5.5. What am I doing wrong?
|
I just looked into this and thought some others might be interested in my findings.
Weak linking with weak\_import really only works well with dynamic libraries. You can get it to work with static linking (by specifying -undefined dynamic\_lookup as suggested above) but this isn't such a hot idea. It means that no undefined symbols will be detected until runtime. This is something I would avoid in production code, personally.
Here is a Mac OS X Terminal session showing how to make it work:
Here is f.c
```
int f(int n)
{
return n * 7;
}
```
Here is whatnof.c
```
#include <stdio.h>
#include <stdlib.h>
extern int f (int) __attribute__((weak_import));
int main() {
if(f == NULL)
printf("what, no f?\n");
else
printf("f(8) is %d\n", f(8));
exit(0);
}
```
Make a dynamic library from f.c:
```
$ cc -dynamiclib -o f.dylib f.c
```
Compile and link against the dynamic lib, list dynamic libs.
```
$ cc -o whatnof whatnof.c f.dylib
$ otool -L whatnof
whatnof:
f.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
```
Run whatnof to see what happens:
```
$ whatnof
f(8) is 56
```
Now replace f.dylib with an empty library (no symbols):
```
$ mv f.dylib f.dylib.real
$ touch null.c
$ cc -dynamiclib -o f.dylib null.c
```
Run same whatnof to see what happens:
```
$ whatnof
what, no f?
```
The basic idea (or "use case") for weak\_import is that it lets you link against a set of dynamic (shared) libraries, but then run the same code against earlier versions of the same libraries. You can check functions against NULL to see if they're supported in the particular dynamic library that the code is currently running against. This seems to be part of the basic development model supported by Xcode. I hope this example is useful; it has helped put my mind at ease about this part of the Xcode design.
|
274,755 |
<p>I've seen (and used) on various projects this layout, with a group of fields followed by a group of properties:</p>
<pre><code>private int MyIntField;
private string MyStringField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
</code></pre>
<p>And I've also encountered this layout with fields next to their property:</p>
<pre><code>private int MyIntField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
private string MyStringField;
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
</code></pre>
<p>Is there a reason to consider one better than the other? I think most coding standards recommend Option #1, but sometimes it's handy having the field next to the property that operates on it.</p>
<p><em>Note: I'm assuming non-trivial properties that can't use auto-implemented properties.</em></p>
|
[
{
"answer_id": 274759,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 4,
"selected": true,
"text": "<p>I think it is whatever the team feels comfortable with. Settle on a standard for the project/company/language and stick to it. I prefer the private variables all together, the methods/interfaces together, the private members....I think you get the point.</p>\n"
},
{
"answer_id": 274760,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p>I group them at the top of the class.</p>\n\n<p>In fact the only thing that is over my private attribute is all constant of the class.</p>\n"
},
{
"answer_id": 274761,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "<p>I'd do the latter approach, since it's a convention that helps me to see at a glance whether a private member has a public getter/setter or not. Not a huge deal either way, though.</p>\n"
},
{
"answer_id": 274763,
"author": "Scott Wegner",
"author_id": 33791,
"author_profile": "https://Stackoverflow.com/users/33791",
"pm_score": 1,
"selected": false,
"text": "<p>To reiterate what Kenny said above, it's really all about the coding standards of your organization. It's hard to objectively classify one style over the other, although everyone seems to have their own opinion.</p>\n\n<p>I generally tend to prefer having data and methods groups by access modifier, and so in this case would prefer Option #1. This is to emphasize the interface, not the design. That is, I could transparently change the implementation of the MyInt modifier in the future (maybe I don't really need to store a backing variable).</p>\n"
},
{
"answer_id": 274790,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 2,
"selected": false,
"text": "<p>I kinda like to have the fields grouped at the top and the properties somewhere else. This is also what <a href=\"http://blogs.msdn.com/sourceanalysis/\" rel=\"nofollow noreferrer\" title=\"Official Microsoft StyleCop Blog\">Microsoft StyleCop</a> recommends.</p>\n"
},
{
"answer_id": 274845,
"author": "JaredCacurak",
"author_id": 16254,
"author_profile": "https://Stackoverflow.com/users/16254",
"pm_score": 1,
"selected": false,
"text": "<p>As a side note where do auto properties fit in?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9304/c-30-auto-properties-useful-or-not\">C# 3.0 auto-properties - useful or not?</a></p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] |
I've seen (and used) on various projects this layout, with a group of fields followed by a group of properties:
```
private int MyIntField;
private string MyStringField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
```
And I've also encountered this layout with fields next to their property:
```
private int MyIntField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
private string MyStringField;
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
```
Is there a reason to consider one better than the other? I think most coding standards recommend Option #1, but sometimes it's handy having the field next to the property that operates on it.
*Note: I'm assuming non-trivial properties that can't use auto-implemented properties.*
|
I think it is whatever the team feels comfortable with. Settle on a standard for the project/company/language and stick to it. I prefer the private variables all together, the methods/interfaces together, the private members....I think you get the point.
|
274,796 |
<p>I have the following code which plays a video clip but when it is finished it does not release the form but instead leaves the last frame of the video. how do I get it to clear when playback ends so that I can see the orignal contents of the form it took over to play the video?</p>
<pre><code>_video = new Video("video.wmv");
_video.Owner = frmVideoWindow;
_video.Play();
</code></pre>
|
[
{
"answer_id": 274803,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>Release the form you mean to close it? You might want to check for an event in your Video object that will raise when the video is done and you will need to use this.close(); to close the form. Is it what you desire?</p>\n"
},
{
"answer_id": 274847,
"author": "user38275",
"author_id": 38275,
"author_profile": "https://Stackoverflow.com/users/38275",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/13913/daok\">Daok</a> pointed me in the correct direction. An event handler on the video ending and then setting the Owner of the Video object to null.</p>\n\n<pre><code>_video.Ending += new System.EventHandler(this.video_stopped);\n\nprivate void video_stopped(object sender, EventArgs e)\n{\n _video.Owner = null;\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38275/"
] |
I have the following code which plays a video clip but when it is finished it does not release the form but instead leaves the last frame of the video. how do I get it to clear when playback ends so that I can see the orignal contents of the form it took over to play the video?
```
_video = new Video("video.wmv");
_video.Owner = frmVideoWindow;
_video.Play();
```
|
[Daok](https://stackoverflow.com/users/13913/daok) pointed me in the correct direction. An event handler on the video ending and then setting the Owner of the Video object to null.
```
_video.Ending += new System.EventHandler(this.video_stopped);
private void video_stopped(object sender, EventArgs e)
{
_video.Owner = null;
}
```
|
274,814 |
<p>How do I get a list of all the headings in a word document by using VBA?</p>
|
[
{
"answer_id": 274830,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "<p>You mean like this <a href=\"http://msdn.microsoft.com/en-us/library/bb960898.aspx\" rel=\"nofollow noreferrer\">createOutline</a> function (which actually copy all headings from a source word document into a new word document):</p>\n<p>(I believe the <code>astrHeadings = docSource.<strong><a href=\"http://msdn.microsoft.com/en-us/library/aa201500(office.10).aspx\" rel=\"nofollow noreferrer\">GetCrossReferenceItems</a></strong>(wdRefTypeHeading)</code> function is the key in this program, and should allow you to retrieve what you are asking for)</p>\n<pre><code>Public Sub CreateOutline()\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n \n Dim astrHeadings As Variant\n Dim strText As String\n Dim intLevel As Integer\n Dim intItem As Integer\n \n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n \n ' Content returns only the main body of the document, not the headers/footer. \n Set rng = docOutline.Content\n ' GetCrossReferenceItems(wdRefTypeHeading) returns an array with references to all headings in the document\n astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)\n \n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n \n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n \n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = "Heading " & intLevel\n rng.Collapse wdCollapseEnd\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' Return the heading level of a header from the\n ' array returned by Word.\n \n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n \n Dim strTemp As String\n Dim strOriginal As String\n Dim intDiff As Integer\n \n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n \n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n \n ' Subtract to find the number of\n ' leading spaces in the original string.\n intDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (intDiff / 2) + 1\nEnd Function\n</code></pre>\n<p><strong>UPDATE by @kol on March 6, 2018</strong></p>\n<p>Although <code>astrHeadings</code> is an array (<code>IsArray</code> returns <code>True</code>, and <code>TypeName</code> returns <code>String()</code>) I get a <code>type mismatch</code> error when I try to access its elements in VBScript (v5.8.16384 on Windows 10 Pro 1709 16299.248). This must be a VBScript-specific problem, because I can access the elements if I run the same code in Word's VBA editor. I ended up iterating the lines of the TOC, because it works even from VBScript:</p>\n<pre><code>For Each Paragraph In Doc.TablesOfContents(1).Range.Paragraphs\n WScript.Echo Paragraph.Range.Text\nNext\n</code></pre>\n"
},
{
"answer_id": 276397,
"author": "JonnyGold",
"author_id": 2665,
"author_profile": "https://Stackoverflow.com/users/2665",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest way to get a list of headings, is to loop through the paragraphs in the document, for example:</p>\n\n<pre><code> Sub ReadPara()\n\n Dim DocPara As Paragraph\n\n For Each DocPara In ActiveDocument.Paragraphs\n\n If Left(DocPara.Range.Style, Len(\"Heading\")) = \"Heading\" Then\n\n Debug.Print DocPara.Range.Text\n\n End If\n\n Next\n\n\nEnd Sub\n</code></pre>\n\n<p>By the way, I find it is a good idea to remove the final character of the paragraph range. Otherwise, if you send the string to a message box or a document, Word displays an extra control character. For example:</p>\n\n<pre><code>Left(DocPara.Range.Text, len(DocPara.Range.Text)-1)\n</code></pre>\n"
},
{
"answer_id": 9486115,
"author": "JoeK",
"author_id": 282798,
"author_profile": "https://Stackoverflow.com/users/282798",
"pm_score": 0,
"selected": false,
"text": "<p>You can also create a Table of Contents in the doc and copy that. This separates out the para ref from the title, which is handy if you need to present that in another context.\nIf you do not want the ToC in your doc, just delete that after the Copy n Paste. JK.</p>\n"
},
{
"answer_id": 11839209,
"author": "joshoff",
"author_id": 1420823,
"author_profile": "https://Stackoverflow.com/users/1420823",
"pm_score": 2,
"selected": false,
"text": "<p>This macro worked beautifully for me (Word 2010). I've extended the functionality slightly: now it prompts the user to enter a minimum level, and supresses subheadings below that level.</p>\n\n<pre><code>Public Sub CreateOutline()\n' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n\n Dim astrHeadings As Variant\n Dim strText As String\n Dim intLevel As Integer\n Dim intItem As Integer\n Dim minLevel As Integer\n\n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n\n minLevel = 1 'levels above this value won't be copied.\n minLevel = CInt(InputBox(\"This macro will generate a new document that contains only the headers from the existing document. What is the lowest level heading you want?\", \"2\"))\n\n ' Content returns only the\n ' main body of the document, not\n ' the headers and footer.\n Set rng = docOutline.Content\n astrHeadings = _\n docSource.GetCrossReferenceItems(wdRefTypeHeading)\n\n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n\n If intLevel <= minLevel Then\n\n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n\n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = \"Heading \" & intLevel\n rng.Collapse wdCollapseEnd\n End If\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document\n ' Return the heading level of a header from the\n ' array returned by Word.\n\n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n\n Dim strTemp As String\n Dim strOriginal As String\n Dim intDiff As Integer\n\n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n\n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n\n ' Subtract to find the number of\n ' leading spaces in the original string.\n intDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (intDiff / 2) + 1\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 21383033,
"author": "dxc",
"author_id": 2804729,
"author_profile": "https://Stackoverflow.com/users/2804729",
"pm_score": 1,
"selected": false,
"text": "<p>Fastest method for extracting of all headings (to LEVEL5).</p>\n\n<pre><code>Sub EXTRACT_HDNGS()\nDim WDApp As Word.Application 'WORD APP\nDim WDDoc As Word.Document 'WORD DOC\n\nSet WDApp = Word.Application\nSet WDDoc = WDApp.ActiveDocument\n\nFor Head_n = 1 To 5\nHead = (\"Heading \" & Head_n)\nWDApp.Selection.HomeKey wdStory, wdMove\n\n Do\n With WDApp.selection\n .MoveStart Unit:=wdLine, Count:=1 \n .Collapse Direction:=wdCollapseEnd\n End with\n With WDApp.Selection.Find\n .ClearFormatting: .text = \"\": \n .MatchWildcards = False: .Forward = True\n .Style = WDDoc.Styles(Head)\n If .Execute = False Then GoTo Level_exit\n .ClearFormatting\n End With\n\n Heading_txt = RemoveSpecialChar(WDApp.Selection.Range.text, 1): Debug.Print Heading_txt\n Heading_lvl = WDApp.Selection.Range.ListFormat.ListLevelNumber: Debug.Print Heading_lvl\n Heading_lne = WDDoc.Range(0, WDApp.Selection.Range.End).Paragraphs.Count: Debug.Print Heading_lne\n Heading_pge = WDApp.Selection.Information(wdActiveEndPageNumber): Debug.Print Heading_pge\n\n If Wdapp.Selection.Style = \"Heading 1\" Then GoTo Level_exit\n Wdapp.Selection.Collapse Direction:=wdCollapseStart\n Loop\nLevel_exit:\nNext Head_n\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 28363925,
"author": "MagTun",
"author_id": 3154274,
"author_profile": "https://Stackoverflow.com/users/3154274",
"pm_score": 1,
"selected": false,
"text": "<p>Following Wikis comment on VonC answer, here is the code that worked for me. It makes the function faster.</p>\n\n<pre><code>Public Sub CopyHeadingsInNewDoc()\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n\n Dim astrHeadings As Variant\n Dim strText As String\n Dim longLevel As Integer\n Dim longItem As Integer\n\n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n\n ' Content returns only the\n ' main body of the document, not\n ' the headers and footer.\n Set rng = docOutline.Content\n astrHeadings = _\n docSource.GetCrossReferenceItems(wdRefTypeHeading)\n\n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n\n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n\n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = \"Heading \" & intLevel\n rng.Collapse wdCollapseEnd\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' Return the heading level of a header from the\n ' array returned by Word.\n\n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n\n Dim strTemp As String\n Dim strOriginal As String\n Dim longDiff As Integer\n\n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n\n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n\n ' Subtract to find the number of\n ' leading spaces in the original string.\n longDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (longDiff / 2) + 1\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 41630198,
"author": "jumpjack",
"author_id": 1635670,
"author_profile": "https://Stackoverflow.com/users/1635670",
"pm_score": 1,
"selected": false,
"text": "<p>Why reinventing the wheel so many times?!?</p>\n\n<p>A \"list of all headings\" is just the standard Word index of document!</p>\n\n<p>This is what I got by recording a macro while adding index to the document:</p>\n\n<pre><code>Sub Macro1()\n ActiveDocument.TablesOfContents.Add Range:=Selection.Range, _\n RightAlignPageNumbers:=True, _\n UseHeadingStyles:=True, _\n UpperHeadingLevel:=1, _\n LowerHeadingLevel:=5, _\n IncludePageNumbers:=True, _\n AddedStyles:=\"\", _\n UseHyperlinks:=True, _\n HidePageNumbersInWeb:=True, _\n UseOutlineLevels:=True\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35762/"
] |
How do I get a list of all the headings in a word document by using VBA?
|
You mean like this [createOutline](http://msdn.microsoft.com/en-us/library/bb960898.aspx) function (which actually copy all headings from a source word document into a new word document):
(I believe the `astrHeadings = docSource.**[GetCrossReferenceItems](http://msdn.microsoft.com/en-us/library/aa201500(office.10).aspx)**(wdRefTypeHeading)` function is the key in this program, and should allow you to retrieve what you are asking for)
```
Public Sub CreateOutline()
Dim docOutline As Word.Document
Dim docSource As Word.Document
Dim rng As Word.Range
Dim astrHeadings As Variant
Dim strText As String
Dim intLevel As Integer
Dim intItem As Integer
Set docSource = ActiveDocument
Set docOutline = Documents.Add
' Content returns only the main body of the document, not the headers/footer.
Set rng = docOutline.Content
' GetCrossReferenceItems(wdRefTypeHeading) returns an array with references to all headings in the document
astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)
For intItem = LBound(astrHeadings) To UBound(astrHeadings)
' Get the text and the level.
strText = Trim$(astrHeadings(intItem))
intLevel = GetLevel(CStr(astrHeadings(intItem)))
' Add the text to the document.
rng.InsertAfter strText & vbNewLine
' Set the style of the selected range and
' then collapse the range for the next entry.
rng.Style = "Heading " & intLevel
rng.Collapse wdCollapseEnd
Next intItem
End Sub
Private Function GetLevel(strItem As String) As Integer
' Return the heading level of a header from the
' array returned by Word.
' The number of leading spaces indicates the
' outline level (2 spaces per level: H1 has
' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.
Dim strTemp As String
Dim strOriginal As String
Dim intDiff As Integer
' Get rid of all trailing spaces.
strOriginal = RTrim$(strItem)
' Trim leading spaces, and then compare with
' the original.
strTemp = LTrim$(strOriginal)
' Subtract to find the number of
' leading spaces in the original string.
intDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (intDiff / 2) + 1
End Function
```
**UPDATE by @kol on March 6, 2018**
Although `astrHeadings` is an array (`IsArray` returns `True`, and `TypeName` returns `String()`) I get a `type mismatch` error when I try to access its elements in VBScript (v5.8.16384 on Windows 10 Pro 1709 16299.248). This must be a VBScript-specific problem, because I can access the elements if I run the same code in Word's VBA editor. I ended up iterating the lines of the TOC, because it works even from VBScript:
```
For Each Paragraph In Doc.TablesOfContents(1).Range.Paragraphs
WScript.Echo Paragraph.Range.Text
Next
```
|
274,840 |
<p>I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux? I have found references to JPL but it doesn’t appear to be maintained anymore.</p>
|
[
{
"answer_id": 274849,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://search.cpan.org/~patl/Inline-Java-0.52/Java.pod\" rel=\"noreferrer\">Inline-Java</a> is the usual library to call java from Perl, and this <a href=\"http://www.piersharding.com/blog/archives/2004/04/calling_perl_fr.html\" rel=\"noreferrer\">post propose a <strong>org.perl.java</strong></a> module which should allow calling Perl from Java, as asked.</p>\n\n<p>However, because of the unpredictability of the JNI implementations for different\nJVMs it is difficult to say what combinations of JVM and Perl will work. Typically, what is required is Perl with MULTIPLICITY, and threads compiled in. That means he uses a custom built Perl.</p>\n\n<p>Otherwise, <strong><a href=\"http://linux.wareseeker.com/Programming/inline-java-callback-0.52.zip/326355\" rel=\"noreferrer\">Inline::Java::Callback</a></strong> allows you to call Perl functions from Java. To do this you need to create an <code><strong>org.perl.inline.java.InlinePerlCaller</strong></code> object. Here is a example of a typical use:</p>\n\n<pre><code>use Inline Java => <<END ;\nimport java.util.* ;\nimport org.perl.inline.java.* ;\n\nclass Pod_regexp extends InlineJavaPerlCaller {\n public Pod_regexp() throws InlineJavaException {\n }\n\n public boolean match(String target, String pattern)\n throws InlineJavaException {\n try {\n String m = (String)CallPerlSub(\"main::regexp\",\n new Object [] {target, pattern}) ;\n\n if (m.equals(\"1\")){\n return true ;\n }\n }\n catch (InlineJavaPerlException pe){\n // $@ is in pe.GetObject()\n }\n\n return false ;\n }\n}\nEND\n\nmy $re = new Pod_regexp() ;\nmy $match = $re->match(\"Inline::Java\", \"^Inline\") ;\nprint($match . \"n\") ; # prints 1\n\nsub regexp {\n my $target = shift ;\n my $pattern = shift ;\n\n return ($target =~ /$pattern/) ;\n} \n</code></pre>\n"
},
{
"answer_id": 274877,
"author": "Geo",
"author_id": 31610,
"author_profile": "https://Stackoverflow.com/users/31610",
"pm_score": -1,
"selected": false,
"text": "<p>I don't know how stable will that be ,or how well maintained it is, so, another option would be to write a script that does something your application will need and then execute that script from Java. Not the most elegant way, but it works.</p>\n"
},
{
"answer_id": 274886,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 3,
"selected": false,
"text": "<p>Is this not what Runtime.exec() is for?</p>\n\n<pre><code>Runtime.getRuntime().exec(\"/usr/bin/perl myPerl.pl\");\n</code></pre>\n\n<p>Or am I misunderstanding the question?</p>\n"
},
{
"answer_id": 275356,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 2,
"selected": false,
"text": "<p>I've used Inline::Java a bit, and found it a bit fiddly, if I had my time over, I'd probably reimplement using web services and call the perl code that way.</p>\n"
},
{
"answer_id": 280711,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I found an implementation on JavaWorld by Robert Lawson, which uses XML-RPC to call Perl routines from your Java code: <a href=\"http://www.javaworld.com/javaworld/jw-10-2004/jw-1011-xmlrpc.html\" rel=\"nofollow noreferrer\">Call Perl routines from Java</a></p>\n"
},
{
"answer_id": 2989683,
"author": "Sarel Botha",
"author_id": 35264,
"author_profile": "https://Stackoverflow.com/users/35264",
"pm_score": 2,
"selected": false,
"text": "<p>Sleep is a scripting language with an interpreter that runs in the JVM. From what I understand the Sleep language is basically Perl with some extensions. Your code may be able to run in Sleep. If it does you can instantiate the interpreter, run the code and retrieve the result.</p>\n"
},
{
"answer_id": 6824368,
"author": "wulfgarpro",
"author_id": 512994,
"author_profile": "https://Stackoverflow.com/users/512994",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is old, but I recently came across the same needs. I found <a href=\"http://www.javainc.com/projects/jperl/\" rel=\"nofollow\">JPerl</a> more convenient then <code>Inline::Java::PerlInterpreter</code>.</p>\n"
},
{
"answer_id": 6828143,
"author": "Øyvind Skaar",
"author_id": 268539,
"author_profile": "https://Stackoverflow.com/users/268539",
"pm_score": 0,
"selected": false,
"text": "<p>Guess it really depends on what your perl code is, and what you're trying to do.. </p>\n\n<p>If just using exec() is too simple, something like <a href=\"http://gearman.org/index.php#introduction\" rel=\"nofollow\">gearman</a> could be helpful </p>\n"
},
{
"answer_id": 17956150,
"author": "sventechie",
"author_id": 151261,
"author_profile": "https://Stackoverflow.com/users/151261",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://rakudo.org/\" rel=\"nofollow noreferrer\">Rakudo</a> allows you to run Perl6 inside a JVM, and there is a <a href=\"https://github.com/rakudo-p5/v5/\" rel=\"nofollow noreferrer\">Perl5 add-on</a> that allows you to run most old code, although no XS of course. There is also <a href=\"https://github.com/behnaaz/jerl\" rel=\"nofollow noreferrer\">JERL</a> that runs current microperl inside the JVM. It depends a lot on what you're looking to do, but those are worth checking out.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
] |
I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux? I have found references to JPL but it doesn’t appear to be maintained anymore.
|
[Inline-Java](http://search.cpan.org/~patl/Inline-Java-0.52/Java.pod) is the usual library to call java from Perl, and this [post propose a **org.perl.java**](http://www.piersharding.com/blog/archives/2004/04/calling_perl_fr.html) module which should allow calling Perl from Java, as asked.
However, because of the unpredictability of the JNI implementations for different
JVMs it is difficult to say what combinations of JVM and Perl will work. Typically, what is required is Perl with MULTIPLICITY, and threads compiled in. That means he uses a custom built Perl.
Otherwise, **[Inline::Java::Callback](http://linux.wareseeker.com/Programming/inline-java-callback-0.52.zip/326355)** allows you to call Perl functions from Java. To do this you need to create an `**org.perl.inline.java.InlinePerlCaller**` object. Here is a example of a typical use:
```
use Inline Java => <<END ;
import java.util.* ;
import org.perl.inline.java.* ;
class Pod_regexp extends InlineJavaPerlCaller {
public Pod_regexp() throws InlineJavaException {
}
public boolean match(String target, String pattern)
throws InlineJavaException {
try {
String m = (String)CallPerlSub("main::regexp",
new Object [] {target, pattern}) ;
if (m.equals("1")){
return true ;
}
}
catch (InlineJavaPerlException pe){
// $@ is in pe.GetObject()
}
return false ;
}
}
END
my $re = new Pod_regexp() ;
my $match = $re->match("Inline::Java", "^Inline") ;
print($match . "n") ; # prints 1
sub regexp {
my $target = shift ;
my $pattern = shift ;
return ($target =~ /$pattern/) ;
}
```
|
274,841 |
<p>I am writing multi-thread socket chat in C++Builder 2009.<br>
It is almost complete in accordance with what I need to do but I have a little problem.
I need to pass the TMemo* pointer into CreateThread WinAPI function which upcasts it to void*.</p>
<p>I tryed this way:<br></p>
<pre><code>HANDLE xxx = MemoChat->Handle;
hNetThread = CreateThread(NULL, 0, NetThread, xxx, 0, &dwNetThreadId);
//...
</code></pre>
<p>and then, in NetThread function,</p>
<pre><code>TMemo* MyMemo((HANDLE)lpParam);
TMemo* MyMemo((TMemo*)lpParam);
</code></pre>
<p>but it didn`t work:(</p>
<p>The question is how I can really downcast it correctly so I can use my Memo Component in this new thread?</p>
|
[
{
"answer_id": 274856,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>Please understand that a HANDLE is <strong>not</strong> a pointer, but a concept of the Win32 API. So the first line casts the LPVOID to HANDLE - this is correct, as the parameter of the thread routine really is given as a handle (xxx). However, it then goes on converting the HANDLE to a MyMemo object; this treats the bits in the handle as if they would form an address - which they aren't.</p>\n\n<p>The second line does exactly the same conversion - it treats a handle as if it were a pointer directly.</p>\n\n<p>I wonder why you aren't passing MemoChat itself to the thread:</p>\n\n<pre><code>hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);\n</code></pre>\n"
},
{
"answer_id": 275036,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": true,
"text": "<p>Call:</p>\n\n<pre><code>TMemo* MemoChat = // You defined that somewhere I assume\nHANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);\n</code></pre>\n\n<p>What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That's fine it does not change it it just loses the type information as the system does not know anything about your object. </p>\n\n<p>The new Thread Start point:</p>\n\n<pre><code>DWORD NetThread(LPVOID lpParameter)\n{\n TMemo* MemoChat = reinterpret_cast<TMemo*>(lpParameter);\n // Do your thread stuff here.\n}\n</code></pre>\n\n<p>Once your thread start method is called. Just convert the void pointer back into the correct type and you should be able to start using it again.</p>\n\n<p>Just to clear up other misconceptions.</p>\n\n<p>A <b>HANDLE is a pointer</b>.<br>\nAnd you could have passed it as the parameter to the NetThread().</p>\n\n<p>A HANDLE is a pointer to pointer under system control which points at the object you are using. So why the double indirection. It allows the system to move the object (and update its pointer) without finding all owners of the object. The owners all have handles that point at the pointer that was just updated.</p>\n\n<p>It is an old fashioned computer science concept that is used infrequently in modern computers because of the OS/Hardware ability to swap main memory into secondary storage. but for certain resource they are still useful. Nowadays when handles are required they are hidden inside objects away from the user. </p>\n"
},
{
"answer_id": 275365,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 0,
"selected": false,
"text": "<p>This is more to try and clarify the handle vs. pointer thing, because I don't think Martin has it exactly right.</p>\n\n<p>A \"pointer to a pointer\" is indeed called a HANDLE, and is a common CS approach to allowing the operating system to physically move heap-allocated memory blocks around without the explicit knowledge of an application layer, which always accesses them via handles. Classic 68K Mac OS works in this way. OS'es that work in this way typically allow user code to allocate memory via handles as well as directly off the heap. This approach is used on machines that don't have proper memory-management hardware.</p>\n\n<p>However,there are other uses of the word HANDLE which borrow the some of the abstraction of the previous use, but with different implementations. Opaque pointers (pointers to datastructures of which the user has no knowledge - PIMPL idiom) are also commonly called HANDLES. </p>\n\n<p>Also, the term HANDLE can be used simply to denote a \"reference\" to an object - maybe an index into an array. Unix File Handles (= file descriptors) are a good example of this. stdin=0,stdout=1,...</p>\n\n<p>So, which of the above are Windows API HANDLES? I've seen conflicting reports. <a href=\"http://www.stanford.edu/class/cs193w/handouts/h04-naming.pdf\" rel=\"nofollow noreferrer\">This document</a> says:</p>\n\n<blockquote>\n <p>Handles in Win32 are numbers used to\n identify resources or windows. They\n are not pointers or pointers to\n pointers. Think of them as ID numbers.</p>\n</blockquote>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
I am writing multi-thread socket chat in C++Builder 2009.
It is almost complete in accordance with what I need to do but I have a little problem.
I need to pass the TMemo\* pointer into CreateThread WinAPI function which upcasts it to void\*.
I tryed this way:
```
HANDLE xxx = MemoChat->Handle;
hNetThread = CreateThread(NULL, 0, NetThread, xxx, 0, &dwNetThreadId);
//...
```
and then, in NetThread function,
```
TMemo* MyMemo((HANDLE)lpParam);
TMemo* MyMemo((TMemo*)lpParam);
```
but it didn`t work:(
The question is how I can really downcast it correctly so I can use my Memo Component in this new thread?
|
Call:
```
TMemo* MemoChat = // You defined that somewhere I assume
HANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);
```
What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That's fine it does not change it it just loses the type information as the system does not know anything about your object.
The new Thread Start point:
```
DWORD NetThread(LPVOID lpParameter)
{
TMemo* MemoChat = reinterpret_cast<TMemo*>(lpParameter);
// Do your thread stuff here.
}
```
Once your thread start method is called. Just convert the void pointer back into the correct type and you should be able to start using it again.
Just to clear up other misconceptions.
A **HANDLE is a pointer**.
And you could have passed it as the parameter to the NetThread().
A HANDLE is a pointer to pointer under system control which points at the object you are using. So why the double indirection. It allows the system to move the object (and update its pointer) without finding all owners of the object. The owners all have handles that point at the pointer that was just updated.
It is an old fashioned computer science concept that is used infrequently in modern computers because of the OS/Hardware ability to swap main memory into secondary storage. but for certain resource they are still useful. Nowadays when handles are required they are hidden inside objects away from the user.
|
274,843 |
<p>I have some elements on a page which are draggable. These same elements have a click event which navigates to another page. I'm trying to determine the best way of preventing the click event from firing if the user is dragging but still allow the click event if not dragging. Anyone have any ideas of the best way to accomplish this?</p>
|
[
{
"answer_id": 274875,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>Something like the following might do the trick (and prevent the click event to be fired up)</p>\n\n<pre><code>new Draggable('tag', \n {\n revert:function()\n {\n $('tag').onclick = function(){return false;};\n setTimeout('$(\\'tag\\').onclick = function(){return true;}','500'); \n return true;\n }\n }\n);\n</code></pre>\n"
},
{
"answer_id": 276080,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 2,
"selected": true,
"text": "<p>I solved this by using something like the following:</p>\n\n<pre><code>new Draggable('id', {\n onStart: function() {\n dPhoto = $('id');\n Event.stopObserving('id', 'click');\n },\n onEnd : function() {\n setTimeout(\"Event.observe('id', 'click', function() { location.href = 'url'; });\", 500);\n },\n revert: true\n});\n</code></pre>\n"
},
{
"answer_id": 364164,
"author": "Tony",
"author_id": 45849,
"author_profile": "https://Stackoverflow.com/users/45849",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var click_func;\nfunction onDragStart(drgObj,mouseEvent){\n click_func = mouseEvent.target.onclick;\n\n mouseEvent.target.onclick = function(e){\n mouseEvent.target.onclick = click_func;\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2675063,
"author": "Stanley85",
"author_id": 321286,
"author_profile": "https://Stackoverflow.com/users/321286",
"pm_score": 0,
"selected": false,
"text": "<p>You can also do this another way. On your startDrag you stop observing the object. Then you observe the click again which leads to an enddrag function which recreates the first eventhandler.</p>\n\n<pre><code>function onDragStart() {\n Event.stopObserving(this.OBJECT,'click');\n Event.observe(this.OBJECT,'click',this.onDragEnd.bindAsEventListener(this));\n}\n\nfunction onDragEnd() {\n Event.stopObserving(this.OBJECT,'click');\n Event.observe(this.OBJECT,'click',this.PREVIOUSFUNCTION.bindAsEventListener(this));\n}\n</code></pre>\n\n<p>This will catch the leftover click event which is still active after the enddrag to just recreate the original handler. I hope this helps somebody out there :)</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22436/"
] |
I have some elements on a page which are draggable. These same elements have a click event which navigates to another page. I'm trying to determine the best way of preventing the click event from firing if the user is dragging but still allow the click event if not dragging. Anyone have any ideas of the best way to accomplish this?
|
I solved this by using something like the following:
```
new Draggable('id', {
onStart: function() {
dPhoto = $('id');
Event.stopObserving('id', 'click');
},
onEnd : function() {
setTimeout("Event.observe('id', 'click', function() { location.href = 'url'; });", 500);
},
revert: true
});
```
|
274,857 |
<p>is there an easy way to reset ALL text fields in an asp.net form - like the reset button for html controls?</p>
|
[
{
"answer_id": 274862,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": false,
"text": "<p>Some solutions are listed here:</p>\n\n<p><a href=\"http://www.webdeveloper.com/forum/archive/index.php/t-42337.html\" rel=\"nofollow noreferrer\">Clear a form in ASP.Net</a></p>\n\n<blockquote>\n <p>I was looking for the same solution in ASP.Net to clear my form on the click and I landed on this post. I looked at all the comments and replies. I decided to use the plain old input tag and created a HTML reset button .It worked like a charm, no postbacks, not javascripts. If there is any catch, I couldn't find it...</p>\n</blockquote>\n"
},
{
"answer_id": 274866,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Using javascript you can do:</p>\n\n<pre><code>document.forms[0].reset();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>theForm.reset(); // at least with ASP.NET 2.0\n</code></pre>\n\n<p>As in</p>\n\n<pre><code><input type='button' id='resetButton' value='Reset' onclick='theForm.reset();return false;' //>\n</code></pre>\n"
},
{
"answer_id": 274871,
"author": "aanund",
"author_id": 7335,
"author_profile": "https://Stackoverflow.com/users/7335",
"pm_score": 3,
"selected": false,
"text": "<p>Depends on your definition of reset. A trivial way to do something like this could be a button with codebehind:</p>\n\n<pre><code>Response.Redirect(Request.Url.PathAndQuery, true);\n</code></pre>\n\n<p>Or a variation thereof.</p>\n"
},
{
"answer_id": 274929,
"author": "Stefan",
"author_id": 30604,
"author_profile": "https://Stackoverflow.com/users/30604",
"pm_score": 0,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>function resetForm() \n{ \n var inputs = document.getElementsByTagName('input'); \n for(var i=0;i<inputs.length;i++) \n { \n if(input[i].type == 'text')\n input[i].value = \"\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11346965,
"author": "Dubs",
"author_id": 2842,
"author_profile": "https://Stackoverflow.com/users/2842",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest way to clear all controls in your form on a submit is:</p>\n\n<pre><code>form1.Controls.Clear()\n</code></pre>\n"
},
{
"answer_id": 13510529,
"author": "ocean4dream",
"author_id": 1550794,
"author_profile": "https://Stackoverflow.com/users/1550794",
"pm_score": 3,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code><asp:Button ID=\"btnReset\" runat=\"server\" Text=\"Reset\" \nOnClientClick=\"this.form.reset();return false;\" />\n</code></pre>\n"
},
{
"answer_id": 14347701,
"author": "Bat_Programmer",
"author_id": 475709,
"author_profile": "https://Stackoverflow.com/users/475709",
"pm_score": 3,
"selected": false,
"text": "<pre><code><input type=\"reset\" value=\"Clear\" />\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
is there an easy way to reset ALL text fields in an asp.net form - like the reset button for html controls?
|
Depends on your definition of reset. A trivial way to do something like this could be a button with codebehind:
```
Response.Redirect(Request.Url.PathAndQuery, true);
```
Or a variation thereof.
|
274,861 |
<p>If I have a date, how do I calculate the week number for that date within that year?</p>
<p>For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.</p>
<p>An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.</p>
<h3>Related:</h3>
<blockquote>
<p><a href="https://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005">Getting week number off a date in MS SQL Server 2005?</a></p>
</blockquote>
|
[
{
"answer_id": 274913,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 6,
"selected": true,
"text": "<p>Pseudocode:</p>\n\n<pre><code>int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...\nint dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...\nint dowJan1 = getDayOfWeek(\"1/1/\" + thisYear) // find out first of year's day\n// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)\nint weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.)\nif (dow < dowJan1) // adjust for being after Saturday of week #1\n ++weekNum;\nreturn (weekNum)\n</code></pre>\n\n<p>To clarify, this algorithm assumes you number your weeks like this:</p>\n\n<pre><code>S M T W R F S\n 1 2 3 <-- week #1\n4 5 6 7 8 9 10 <-- week #2\n[etc.]\n</code></pre>\n\n<p>getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.</p>\n\n<p>If you're going to implement your own date counting routines, remember that years that are divisible by 100 are <strong>NOT</strong> leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see <a href=\"http://en.wikipedia.org/wiki/Calendar_reform\" rel=\"noreferrer\">Wikipedia</a> for loads of info on that.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/datetime/datetimedisc.aspx\" rel=\"noreferrer\">This link</a> talks about date/time functions in Windows/C++ in greater detail.</p>\n"
},
{
"answer_id": 274914,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<p>Use gmtime or localtime to calculate days since Sunday (that is, day of the week) and days since January 1 (note that Jan 1 is \"0\" in the latter).</p>\n\n<p>The arbitrary bit is deciding what day of the year Week 1 starts on: usually it only depends what day of the week Jan 1 was, which of course you can calculate from the two pieces of information from gmtime. Then use a table lookup for the 7 possibilities, it's probably easier than coding the rules.</p>\n\n<p>For example, I think Outlook uses the standard that Week 1 is the first week containing a Thursday. So if Jan 1 is a Sunday, then the first day of Week 1 is Jan 1, or day 0. The remaining possibilities are Monday, -1; Tuesday, -2; Wednesday, -3; Thursday, -4; Friday, 2; Saturday, 1.</p>\n\n<p>Note the negative numbers: \"Sunday of week 1\" doesn't actually exist in 4 out of 7 cases, but if we pretend it was a day back in the previous year, we'll get the right answer out.</p>\n\n<p>Once you have that, the number of days between it and your date tells you the week number: divide by 7 and add 1.</p>\n\n<p>That said, I imagine there's a Windows API somewhere that will give you the same week number that Outlook uses. I just don't know what it is, and of course if your Week 1 rules are different from Outlook's then it's probably not much use.</p>\n\n<p>Untested code:</p>\n\n<pre><code>int firstdays[7] = { 0, -1, -2, -3, -4, 2, 1 }; // or some other Week 1 rule\nstruct tm breakdown;\ntime_t target = time_you_care_about();\n_gmtime_s(&breakdown,&target);\nint dayofweek = breakdown.tm_wday;\nint dayofyear = breakdown.tm_yday;\n\nint jan1wday = (dayofweek - dayofyear) % 7;\nif (jan1wday < 0) jan1wday += 7;\n\nint week1first = firstdays[jan1wday];\nif (dayofyear < week1first) return 0;\nreturn ((dayofyear - week1first)/7) + 1;\n</code></pre>\n\n<p>Something like that, anyway.</p>\n"
},
{
"answer_id": 275024,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>Be aware that while your definition of <em>nth</em> week of the year is tenable, it is also not 'the' standard one.</p>\n\n<p>ISO 8601 defines a standard for the representation of dates, times and time zones. It defines weeks that start on a Monday. It also says Week 1 of a year is the one which contains at least 4 days from the given year. Consequently, the 29th, 30th and 31st of December 20xx could be in week 1 of 20xy (where xy = xx + 1), and the 1st, 2nd and 3rd of January 20xy could all be in the last week of 20xx. Further, there can be a week 53.</p>\n\n<p>[<em>Added</em>: note that the C standard and the `strftime() function provides for weeks that start on Sunday as well as weeks that start on Monday. It is not clear that the C standard provides for the year number of week 0 for Sunday-based weeks. See also the answer from Emerick Rogul.]</p>\n\n<p>Then comes the interesting testing phase -- when do you get week 53?\nOne answer is on Friday 1st January 2010, which is in 2009-W53 (as,\nindeed, is Sunday 3rd January 2010). Similarly, Saturday 1st January\n2005 is in 2004-W53, but Sunday 1st January 2006 is in 2005-W52.</p>\n\n<p>That is an extract from a comment in the following code, which is actually in Informix SPL (Stored Procedure Language), but is readable - though probably not writable - without much further explanation. The '||' operator is the SQL string concatenation operation, and Sunday is day 0, Monday is day 1, ... Saturday is day 6 of the week. There are extensive notes in the comments, including relevant text from the standard. One line comments start '<code>--</code>'; possibly multiline comments start with '<code>{</code>' and end at the next '<code>}</code>'.</p>\n\n<pre><code>-- @(#)$Id: iso8601_weekday.spl,v 1.1 2001/04/03 19:34:43 jleffler Exp $\n--\n-- Calculate ISO 8601 Week Number for given date\n-- Defines procedure: iso8601_weekday().\n-- Uses procedure: iso8601_weeknum().\n\n{\nAccording to a summary of the ISO 8601:1988 standard \"Data Elements and\nInterchange Formats -- Information Interchange -- Representation of\ndates and times\":\n\n The week notation can also be extended by a number indicating the\n day of the week. For example the day 1996-12-31 which is the\n Tuesday (day 2) of the first week of 1997 can also be written as\n\n 1997-W01-2 or 1997W012\n\n for applications like industrial planning where many things like\n shift rotations are organized per week and knowing the week number\n and the day of the week is more handy than knowing the day of the\n month.\n\nThis procedure uses iso8601_weeknum() to format the YYYY-Www part of the\ndate, and appends '-d' to the result, allowing for Informix's coding of\nSunday as day 0 rather than day 7 as required by ISO 8601.\n}\n\nCREATE PROCEDURE iso8601_weekday(dateval DATE DEFAULT TODAY) RETURNING CHAR(10);\n DEFINE rv CHAR(10);\n DEFINE dw CHAR(4);\n LET dw = WEEKDAY(dateval);\n IF dw = 0 THEN\n LET dw = 7;\n END IF;\n RETURN iso8601_weeknum(dateval) || '-' || dw;\nEND PROCEDURE;\n-- @(#)$Id: iso8601_weeknum.spl,v 1.1 2001/02/27 20:36:25 jleffler Exp $\n--\n-- Calculate ISO 8601 Week Number for given date\n-- Defines procedures: day_one_week_one() and iso8601_weeknum().\n\n{\nAccording to a summary of the ISO 8601:1988 standard \"Data Elements and\nInterchange Formats -- Information Interchange -- Representation of\ndates and times\":\n\n In commercial and industrial applications (delivery times,\n production plans, etc.), especially in Europe, it is often required\n to refer to a week of a year. Week 01 of a year is per definition\n the first week which has the Thursday in this year, which is\n equivalent to the week which contains the fourth day of January. In\n other words, the first week of a new year is the week which has the\n majority of its days in the new year. Week 01 might also contain\n days from the previous year and the week before week 01 of a year is\n the last week (52 or 53) of the previous year even if it contains\n days from the new year. A week starts with Monday (day 1) and ends\n with Sunday (day 7). For example, the first week of the year 1997\n lasts from 1996-12-30 to 1997-01-05 and can be written in standard\n notation as\n\n 1997-W01 or 1997W01\n\n The week notation can also be extended by a number indicating the\n day of the week. For example the day 1996-12-31 which is the\n Tuesday (day 2) of the first week of 1997 can also be written as\n\n 1997-W01-2 or 1997W012\n\n for applications like industrial planning where many things like\n shift rotations are organized per week and knowing the week number\n and the day of the week is more handy than knowing the day of the\n month.\n\nReferring to the standard itself, section 3.17 defines a calendar week:\n\n week, calendar: A seven day period within a calendar year, starting\n on a Monday and identified by its ordinal number within the year;\n the first calendar week of the year is the one that includes the\n first Thursday of that year. In the Gregorian calendar, this is\n equivalent to the week which includes 4 January.\n\nSection 5.2.3 \"Date identified by Calendar week and day numbers\" states:\n\n Calendar week is represented by two numeric digits. The first\n calendar week of a year shall be identified as 01 [...]\n\n Day of the week is represented by one decimal digit. Monday\n shall be identified as day 1 of any calendar week [...]\n\nSection 5.2.3.1 \"Complete representation\" states:\n\n When the application clearly identifies the need for a complete\n representation of a date identified by calendar week and day\n numbers, it shall be one of the alphanumeric representations as\n follows, where CCYY represents a calendar year, W is the week\n designator, ww represents the ordinal number of a calendar week\n within the year, and D represents the ordinal number within the\n calendar week.\n\n Basic format: CCYYWwwD\n Example: 1985W155\n Extended format: CCYY-Www-D\n Example: 1985-W15-5\n\nBoth the summary and the formal definition are intuitively clear, but it\nis not obvious how to translate it into an algorithm. However, we can\ndeal with the problem by exhaustively enumerating the seven options for\nthe day of the week on which 1st January falls (with actual year values\nfor concreteness):\n\n 1st January 2001 is Monday => Week 1 starts on 2001-01-01\n 1st January 2002 is Tuesday => Week 1 starts on 2001-12-31\n 1st January 2003 is Wednesday => Week 1 starts on 2002-12-30\n 1st January 2004 is Thursday => Week 1 starts on 2003-12-29\n 1st January 2010 is Friday => Week 1 starts on 2010-01-04\n 1st January 2005 is Saturday => Week 1 starts on 2005-01-03\n 1st January 2006 is Sunday => Week 1 starts on 2006-01-02\n\n(Cross-check: 1st January 1997 was a Wednesday; the summary notes state\nthat week 1 of 1997 started on 1996-12-30, which is consistent with the\ntable derived for dates in the first decade of the third millennium\nabove).\n\nWhen working with the Informix DATE types, bear in mind that Informix\nuses WEEKDAY values 0 = Sunday, 1 = Monday, 6 = Saturday. When the\nweekday of the first of January has the value in the LH column, you need\nto add the value in the RH column to the 1st of January to obtain the\ndate of the first day of the first week of the year.\n\n Weekday Offset to\n 1st January 1st day of week 1\n\n 0 +1\n 1 0\n 2 -1\n 3 -2\n 4 -3\n 5 +3\n 6 +2\n\nThis can be written as MOD(11-w,7)-3 where w is the (Informix encoding\nof the) weekday of 1st January and the value 11 is used to ensure that\nno negative values are presented to the MOD operator. Hence, the\nexpression for the date corresponding to the 1st day (Monday) of the 1st\nweek of a given year, yyyy, is:\n\n d1w1 = MDY(1, 1, yyyy) + MOD(11 - WEEKDAY(MDY(1,1,yyyy)), 7) - 3\n\nThis expression is encapsulated in stored procedure day_one_week_one:\n}\n\nCREATE PROCEDURE day_one_week_one(yyyy INTEGER) RETURNING DATE;\n DEFINE jan1 DATE;\n LET jan1 = MDY(1, 1, yyyy);\n RETURN jan1 + MOD(11 - WEEKDAY(jan1), 7) - 3;\nEND PROCEDURE;\n\n{\nGiven this date d1w1, we can calculate the week number of any other date\nin the same year as:\n\n TRUNC((dateval - d1w1) / 7) + 1\n\nThe residual issues are ensuring that the wraparounds are correct. If\nthe given date is earlier than the start of the first week of the year\nthat contains it, then the date belongs to the last week of the previous\nyear. If the given date is on or after the start of the first week of\nthe next year, then the date belongs to the first week of the next year.\n\nGiven these observations, we can write iso8601_weeknum as shown below.\n(Beware: iso8601_week_number() is too long for servers with the\n18-character limit; so is day_one_of_week_one()).\n\nThen comes the interesting testing phase -- when do you get week 53?\nOne answer is on Friday 1st January 2010, which is in 2009-W53 (as,\nindeed, is Sunday 3rd January 2010). Similarly, Saturday 1st January\n2005 is in 2004-W53, but Sunday 1st January 2006 is in 2005-W52.\n}\n\nCREATE PROCEDURE iso8601_weeknum(dateval DATE DEFAULT TODAY) RETURNING CHAR(8);\n DEFINE rv CHAR(8);\n DEFINE yyyy CHAR(4);\n DEFINE ww CHAR(2);\n DEFINE d1w1 DATE;\n DEFINE tv DATE;\n DEFINE wn INTEGER;\n DEFINE yn INTEGER;\n -- Calculate year and week number.\n LET yn = YEAR(dateval);\n LET d1w1 = day_one_week_one(yn);\n IF dateval < d1w1 THEN\n -- Date is in early January and is in last week of prior year\n LET yn = yn - 1;\n LET d1w1 = day_one_week_one(yn);\n ELSE\n LET tv = day_one_week_one(yn + 1);\n IF dateval >= tv THEN\n -- Date is in late December and is in the first week of next year\n LET yn = yn + 1;\n LET d1w1 = tv;\n END IF;\n END IF;\n LET wn = TRUNC((dateval - d1w1) / 7) + 1;\n -- Calculation complete: yn is year number and wn is week number.\n -- Format result.\n LET yyyy = yn;\n IF wn < 10 THEN\n LET ww = '0' || wn;\n ELSE\n LET ww = wn;\n END IF\n LET rv = yyyy || '-W' || ww;\n RETURN rv;\nEND PROCEDURE;\n</code></pre>\n\n<hr>\n\n<p>For completeness, the inverse function is also easy to write with the <code>day_one_week_one()</code> function above:</p>\n\n<pre><code>-- @(#)$Id: ywd_date.spl,v 1.1 2012/12/29 05:13:27 jleffler Exp $\n-- @(#)Create ywd_date() and ywdstr_date() stored procedures\n\n-- Convert a date in format year, week, day (ISO 8601) to DATE.\n-- Two variants:\n-- ywd_date(yyyy SMALLINT, ww SMALLINT, dd SMALLINT) RETURNING DATE;\n-- ywdstr_date(ywd CHAR(10)) RETURNING DATE;\n\n-- NB: If week 53 is supplied, there is no check that the year had week\n-- 53 (GIGO).\n-- NB: If year yyyy is a leap year and yyyy-01-01 falls on Wed (3) or\n-- Thu (4), there are 53 weeks in the year.\n-- NB: If year yyyy is not a leap year and yyyy-01-01 falls on Thu (4),\n-- there are 53 weeks in the year.\n\nCREATE PROCEDURE ywd_date(yyyy SMALLINT, ww SMALLINT, dd SMALLINT) RETURNING DATE AS date;\n DEFINE d DATE;\n -- Check ranges\n IF yyyy < 1 OR yyyy > 9999 OR ww < 1 OR ww > 53 OR dd < 1 OR dd > 7 THEN\n RETURN NULL;\n END IF;\n LET d = day_one_week_one(yyyy);\n LET d = d + (ww - 1) * 7 + (dd - 1);\n RETURN d;\nEND PROCEDURE;\n\n-- Input: 2012-W52-5\nCREATE PROCEDURE ywdstr_date(ywd CHAR(10)) RETURNING DATE AS date;\n DEFINE yyyy SMALLINT;\n DEFINE ww SMALLINT;\n DEFINE dd SMALLINT;\n LET yyyy = SUBSTR(ywd, 1, 4);\n LET ww = SUBSTR(ywd, 7, 2);\n LET dd = SUBSTR(ywd, 10, 1);\n RETURN ywd_date(yyyy, ww, dd);\nEND PROCEDURE;\n\nCREATE TEMP TABLE test_dates(d DATE);\nINSERT INTO test_dates VALUES('2011-12-28');\nINSERT INTO test_dates VALUES('2011-12-29');\nINSERT INTO test_dates VALUES('2011-12-30');\nINSERT INTO test_dates VALUES('2011-12-31');\nINSERT INTO test_dates VALUES('2012-01-01');\nINSERT INTO test_dates VALUES('2012-01-02');\nINSERT INTO test_dates VALUES('2012-01-03');\nINSERT INTO test_dates VALUES('2012-01-04');\nINSERT INTO test_dates VALUES('2012-01-05');\nINSERT INTO test_dates VALUES('2012-01-06');\nINSERT INTO test_dates VALUES('2012-01-07');\n\nSELECT d, iso8601_weeknum(d), iso8601_weekday(d), ywdstr_date(iso8601_weekday(d))\n FROM test_dates\n ORDER BY d;\n</code></pre>\n\n<p>As noted in the comments, the code will accept a week 53 date even if the year should only accept 52 weeks.</p>\n"
},
{
"answer_id": 275067,
"author": "Emerick Rogul",
"author_id": 33837,
"author_profile": "https://Stackoverflow.com/users/33837",
"pm_score": 3,
"selected": false,
"text": "<p>I strongly recommend using the C Standard Library's time functions to calculate the week number. Specifically, the <code>strftime</code> function has specifiers to print the week number (among many other values) given a date in broken-down (<code>struct tm</code>) format. Here's a small sample program that illustrates this:</p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nint\nmain(void)\n{\n struct tm tm;\n char timebuf[64];\n\n // Zero out struct tm\n memset(&tm, 0, sizeof tm);\n\n // November 4, 2008 11:00 pm\n tm.tm_sec = 0;\n tm.tm_min = 0;\n tm.tm_hour = 23;\n tm.tm_mday = 4;\n tm.tm_mon = 10;\n tm.tm_year = 108;\n tm.tm_isdst = -1;\n\n // Call mktime to recompute tm.tm_wday and tm.tm_yday\n mktime(&tm);\n\n if (strftime(timebuf, sizeof timebuf, \"%W\", &tm) != 0) {\n printf(\"Week number is: %s\\n\", timebuf);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>The output from this program (compiled with GCC on Linux and Microsoft Visual Studio 2005 SP1 on Windows) is:</p>\n\n<blockquote>\n<pre><code>Week number is: 44\n</code></pre>\n</blockquote>\n\n<p>You can learn more about strftime <a href=\"http://msdn.microsoft.com/en-us/library/fe06s4ak(VS.80).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 275093,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 2,
"selected": false,
"text": "<p>struct tm is used to represent \"broken down time\" and has at least the following fields:</p>\n\n<pre>\nint tm_sec Seconds [0,60]. \nint tm_min Minutes [0,59]. \nint tm_hour Hour [0,23]. \nint tm_mday Day of month [1,31]. \nint tm_mon Month of year [0,11]. \nint tm_year Years since 1900. \nint tm_wday Day of week [0,6] (Sunday =0). \nint tm_yday Day of year [0,365]. \nint tm_isdst Daylight Savings flag. \n</pre>\n\n<p>You can create a struct tm from a time_t with the localtime() function.</p>\n\n<p>You can create a time_t from a struct tm with the mktime() function.</p>\n\n<p>The best part about struct tm is that you can do things like add 24 to the month of year member and when you call mktime() you'll get a time_t thats 2 years in the future (this works with any of its members, so you can, for example, increment the hour by 1000 and then get a time_t 41 days in the future)...</p>\n"
},
{
"answer_id": 565195,
"author": "danio",
"author_id": 12663,
"author_profile": "https://Stackoverflow.com/users/12663",
"pm_score": 0,
"selected": false,
"text": "<p>Boost provides gregorian::date::week_number()\nsee <a href=\"http://www.boost.org/doc/libs/1_38_0/doc/html/boost/gregorian/date.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_38_0/doc/html/boost/gregorian/date.html</a> and \n<a href=\"http://www.boost.org/doc/libs/1_38_0/boost/date_time/gregorian/greg_date.hpp\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_38_0/boost/date_time/gregorian/greg_date.hpp</a>.</p>\n\n<p>However I cannot see a way to get the year number which matches the week number (which may be different to the calendar year for that date).</p>\n"
},
{
"answer_id": 1017188,
"author": "Pascalo",
"author_id": 121941,
"author_profile": "https://Stackoverflow.com/users/121941",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry, i'm new here and cant comment on the answer itself but the pseudo code from the answer with the checkmark isnt compeltey correct.</p>\n\n<blockquote>\n <p>Pseudocode:</p>\n</blockquote>\n\n<pre><code>int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...\nint dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...\nint dowJan1 = getDayOfWeek(\"1/1/\" + thisYear) // find out first of year's day\nint weekNum = (julian / 7) + 1 // Get our week#\nif (dow < dowJan1) // adjust for being after Saturday of week #1\n ++weekNum;\nreturn (weekNum)\n</code></pre>\n\n<p>you should not look for the \"first of year's day\", but for the last day of last year. </p>\n\n<pre><code>getDayOfWeek(\"12/31/\" + thisYear-1)\n</code></pre>\n\n<p>would be correct instead of </p>\n\n<pre><code>getDayOfWeek(\"1/1/\" + thisYear) \n</code></pre>\n\n<p>If you don't do this, the last weekday of last year (like Monday) would always be one week ahead.</p>\n"
},
{
"answer_id": 2814420,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 1,
"selected": false,
"text": "<p>My definition which is non-ISO 8601 (good enough for my purposes and fast):</p>\n\n<pre><code>// week number of the year\n// (Monday as the first day of the week) as a decimal number [00,53].\n// All days in a new year preceding the first Monday are considered to be in week 0.\nint GetWeek(const struct tm& ts)\n{\n return (ts.tm_yday + 7 - (ts.tm_wday ? (ts.tm_wday - 1) : 6)) / 7;\n}\n</code></pre>\n"
},
{
"answer_id": 12608103,
"author": "pasx",
"author_id": 683319,
"author_profile": "https://Stackoverflow.com/users/683319",
"pm_score": 0,
"selected": false,
"text": "<p>My assumption was that the first week on the year may contain up to 7 day as illustrated in Olie's answer.\nThe code does not handle the cultures where the week starts on another day than Sunday and that is a large part of the world.</p>\n\n<pre><code>tm t = ... //the date on which to find week of year\n\nint wy = -1;\n\nstruct tm t1;\nt1.tm_year = t.tm_year;\nt1.tm_mday = t1.tm_mon = 1; //set to 1st of January\ntime_t tt = mktime(&t1); //compute tm\n\n//remove days for 1st week\nint yd = t.tm_yday - (7 - t1.tm_wday);\nif(yd <= 0 ) //first week is now negative\n wy = 0;\nelse\n wy = (int)std::ceil( (double) ( yd/7) ); //second week will be 1 \n</code></pre>\n"
},
{
"answer_id": 16536256,
"author": "raghu",
"author_id": 2380353,
"author_profile": "https://Stackoverflow.com/users/2380353",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public int GetWeekOfYear(DateTime todayDate)\n{\n int days = todayDate.DayOfYear;\n float result = days / 7;\n result=result+1;\n Response.Write(result.ToString());\n return Convert.ToInt32(result);\n}\n</code></pre>\n\n<p>Just pass the current date as the parameter to this function.\nThen you will get the current week number.\nHope it solves ur problem. Any suggestions are greatly welcome.</p>\n"
},
{
"answer_id": 24907972,
"author": "MINH_NV",
"author_id": 3458028,
"author_profile": "https://Stackoverflow.com/users/3458028",
"pm_score": 0,
"selected": false,
"text": "<pre><code>time_t t = time(NULL);\ntm* timePtr = localtime(&t);\ndouble day_of_year=timePtr->tm_yday +1 ; // 1-365\nint week_of_year =(int) ceill(day_of_year/7.0);\n</code></pre>\n"
},
{
"answer_id": 34437838,
"author": "Leslie Satenstein",
"author_id": 1445782,
"author_profile": "https://Stackoverflow.com/users/1445782",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/**\n * @brief WeekNo\n * @param yr\n * @param mon\n * @param day\n * @param iso\n * @return\n *\n * Given a date, return the week number\n * Note. The first week of the year begins on the Monday\n * following the previous Thursday\n * Follows ISO 8601\n *\n * Mutually equivalent definitions for week 01 are:\n *\n * the week with the year's first Thursday in it (the ISO 8601 definition)\n * the week with the Thursday in the period 1 – 7 January\n * the week starting with the Monday in the period 29 December – 4 January\n * the week starting with the Monday which is nearest in time to 1 January\n * the week ending with the Sunday in the period 4 – 10 January\n * the week with 4 January in it\n * the first week with the majority (four or more) of its days in the starting year\n * If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01.\n * If 1 January is on a Friday, Saturday or Sunday, it is part of week 52 or 53 of the previous year.\n * the week with the year's first working day in it (if Saturdays, Sundays, and 1 January are not working days).\n *** strftime has a conversion of struct tm to weeknumber. strptime fills in tm struct**\n * Code uses strptime, strftime functions.\n */\n\nint WeekNo( int yr,int mon, int day, int iso)\n{\n struct tm tm;\n char format[32];\n //memset(tm,0,sizeof(tm));\n sprintf(format,\"%d-%02d-%02d\",yr,mon,day);\n strptime(format, \"%Y-%m-%d\", &tm);\n // structure tm is now filled in for strftime\n\n strftime(format, sizeof(format), iso? \"%V\":\"%U\", &tm);\n\n //puts(format);\n return atoi(format);\n}\n</code></pre>\n\n<p>invoke as Weekno(2015,12,23,1); //For ISO week number.\n Weekno(2015,12,23,0) //For non ISO week number</p>\n"
},
{
"answer_id": 49425030,
"author": "Arun Rao",
"author_id": 9533750,
"author_profile": "https://Stackoverflow.com/users/9533750",
"pm_score": 1,
"selected": false,
"text": "<p>This is my solution but it's not in C++</p>\n\n<pre><code>NoOfDays = (CurrentDate - YearStartDate)+1\nIF NoOfDays MOD 7 = 0 Then\n WeekNo = INT(NoOfDays/7)\nELSE\n WeekNo = INT(NoOfDays/7)+1\nEND \n</code></pre>\n"
},
{
"answer_id": 55987057,
"author": "Remis",
"author_id": 3737891,
"author_profile": "https://Stackoverflow.com/users/3737891",
"pm_score": 1,
"selected": false,
"text": "<p>Using <code>iso_week.h</code> from <a href=\"http://howardhinnant.github.io/iso_week.html\" rel=\"nofollow noreferrer\">howardhinnant.github.io/iso_week.html</a> this is easily achievable:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include \"iso_week.h\"\n\nint main() {\n using namespace iso_week;\n using namespace std::chrono;\n // Get the current time_point and floor to convert to the sys_days:\n auto today = floor<days>(system_clock::now());\n // Convert from sys_days to iso_week::year_weeknum_weekday format\n auto yww = year_weeknum_weekday{today};\n // Print current week number of the year\n std::cout << \"The current week of \" << yww.year() << \" is: \" \n << yww.weeknum() << std::endl;\n\n // Set any day\n auto any_day = 2014_y/9/28;\n // Get week of `any_day`\n std::cout << \"The week of \" << any_day.year() << \" on `any day` was: \" \n << any_day.weeknum() << std::endl; \n}\n</code></pre>\n\n<p>and the output is:</p>\n\n<pre><code>The current week of 2019 is: W18\nThe week in 2014 on `any day` was: W09\n</code></pre>\n"
},
{
"answer_id": 60531141,
"author": "afull",
"author_id": 13007429,
"author_profile": "https://Stackoverflow.com/users/13007429",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/**********************************************************************************\nFunction Name: rtcCalcYearWeek\nDescription : Function to calculate the working week of the year (changing on a Monday)\nArguments : IN iYear - The year 2000...\n IN iMonth - The month 1..12\n IN iDay - The day 1..31\n IN iWeekDay - The week day 0 = Monday ... 6 = Sunday\nReturn Value : The year week 1..52\n***********************************************************************************/\nint rtcCalcYearWeek(int iYear, int iMonth, int iDay, int iWeekDay)\n{\n int iLeap = 0;\n static const int ppiYearDays[2][13] =\n {\n /* Normal year */\n {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},\n /* Leap year */\n {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}\n };\n /* Check for leap year */\n if (((iYear % 4) == 0) && (((iYear % 100) != 0) || ((iYear % 400) == 0)))\n {\n iLeap = 1;\n }\n /* Calculate the year week */\n return (((ppiYearDays[iLeap][iMonth] + iDay) - (iWeekDay + 7) % 7 + 7) / 7) + 1;\n}\n/***********************************************************************************\nEnd of function rtcCalcYearWeek\n***********************************************************************************/\n\n/**********************************************************************************\n* Function Name: rtcCalcWeekDay\n* Description : Function to calculate the week day for a given date from 2000\n* to 2099.\n* Arguments : IN iDay - The day 1..31\n* IN iMonth - The month 1..12\n* IN iYear - The year 2000..2099\n* Return Value : The weekday 0 = Monday ... 6 = Sunday\n***********************************************************************************/\nint rtcCalcWeekDay(int iDay, int iMonth, int iYear)\n{\n if (iMonth < 3)\n {\n iMonth += 12;\n iYear -= 1;\n }\n return (iDay + (2 * iMonth) + (6 * (iMonth + 1) / 10) + iYear \n + (iYear / 4)- (iYear / 100) + (iYear / 400)) % 7;\n}\n/***********************************************************************************\nEnd of function rtcCalcWeekDay\n***********************************************************************************/\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15669/"
] |
If I have a date, how do I calculate the week number for that date within that year?
For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.
An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.
### Related:
>
> [Getting week number off a date in MS SQL Server 2005?](https://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005)
>
>
>
|
Pseudocode:
```
int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day
// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)
int weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.)
if (dow < dowJan1) // adjust for being after Saturday of week #1
++weekNum;
return (weekNum)
```
To clarify, this algorithm assumes you number your weeks like this:
```
S M T W R F S
1 2 3 <-- week #1
4 5 6 7 8 9 10 <-- week #2
[etc.]
```
getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.
If you're going to implement your own date counting routines, remember that years that are divisible by 100 are **NOT** leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see [Wikipedia](http://en.wikipedia.org/wiki/Calendar_reform) for loads of info on that.
[This link](http://www.codeproject.com/KB/datetime/datetimedisc.aspx) talks about date/time functions in Windows/C++ in greater detail.
|
274,865 |
<p>I am modifying some code and came across a declaration that I am having trouble understanding:</p>
<pre><code>int *userMask[3][4] = {0};
</code></pre>
<p>What exactly is this pointing to? Is it a matrix where every element is a pointer? Or is it pointing to a matrix of size [3][4]?</p>
<p>Thanks</p>
<hr>
<p>I guess my question is how <code>userMask[2][maskElement][user]</code> can work when it is declared as <code>int</code>. Wouldn't userMask have to be <code>int[]</code> for that to work properly? I must not be understanding this right...</p>
<p>On a side note, thanks for your suggestion about cdecl Robert. However, does anyone know how to use it in an XP command prompt? All I can get is syntax error :(</p>
|
[
{
"answer_id": 274869,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 4,
"selected": false,
"text": "<p>This is a two-dimensional array where each element is a pointer to an <code>int</code>, and all the pointers are initialised to zero.</p>\n\n<p>In your follow-up, you show that the array is used like this:</p>\n\n<pre><code>if(userMask[2][maskElement][user] && blah)\n result = true;\n</code></pre>\n\n<p>In this case, each element in <code>userMask</code> should actually point to an array of <code>int</code>s. (An <code>int*</code> can point to a single <code>int</code> or an array of <code>int</code>s). To determine this, check the code that assigns values to <code>userMask</code>. For example, it is possible to write:</p>\n\n<pre><code>int userArray[2] = { 10, 20 };\n\nuserMask[0][0] = userArray; // userMask[0][0] points to the\n // first element of userArray.\n</code></pre>\n\n<p>Then the following code indexes into <code>userArray</code>:</p>\n\n<pre><code>int value = userMask[0][0][1]; // sets value = userArray[1], giving 20.\n</code></pre>\n"
},
{
"answer_id": 274874,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": -1,
"selected": false,
"text": "<p>It is a matrix where every element is a pointer.</p>\n\n<p>If it was pointing to a matrix of size [3][4] the code would have been </p>\n\n<pre><code>int userMask[3][4]={0};\n</code></pre>\n"
},
{
"answer_id": 274878,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "<pre><code>int *userMask[3][4] = {0};\n</code></pre>\n\n<p>is a 2-dimensional array where each member is a pointer to int. Additionally, all members are initialized to null pointers.</p>\n\n<pre><code>int (*userMask)[3][4];\n</code></pre>\n\n<p>would be a pointer to a 2-dimensional array of ints. Brackets in C bind tighter than * so the parenthesis are needed to create a pointer to an array.</p>\n\n<p><code>cdecl</code> is a simple utility you can download to explain complex declarations:</p>\n\n<pre><code>cdecl> explain int *userMask[3][4]\ndeclare userMask as array 3 of array 4 of pointer to int\n</code></pre>\n\n<p>It can also do the opposite:</p>\n\n<pre><code>cdecl> declare userMask as pointer to array 3 of array 4 of int\nint (*userMask)[3][4]\n</code></pre>\n"
},
{
"answer_id": 274891,
"author": "Cameron",
"author_id": 21475,
"author_profile": "https://Stackoverflow.com/users/21475",
"pm_score": 0,
"selected": false,
"text": "<p>I think that statement accesses the third row of the usermask array, then accesses the maskElement'th pointer in that row, and since that is an int pointer, it can point to the beginning of an int array (think character strings), which I assume it is doing, and that array is sub-indexed by user.</p>\n"
},
{
"answer_id": 274897,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 0,
"selected": false,
"text": "<p><code>userMask[2]</code> is of type <code>int*[]</code>,<br>\n<code>userMask[2][maskElement]</code> is of type <code>int*</code>,<br>\nand so <code>userMask[2][maskElement][user]</code> is of type <code>int</code>.</p>\n\n<p>The declaration</p>\n\n<pre><code>int *userMask[3][4] = {0};\n</code></pre>\n\n<p>is shorthand for </p>\n\n<pre><code>int *userMask[3][4] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};\n</code></pre>\n\n<p>where each of the zeros is implicitly converted to <code>(int*)0</code>. </p>\n"
},
{
"answer_id": 274943,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "<h2>Short answer</h2>\n\n<p>Given userMask is declared as </p>\n\n<pre><code>int *userMask[3][4];\n</code></pre>\n\n<p>then <code>userMask</code> has type <code>int*[3][4]</code>. It's a 2d array of pointers to int. The size of the outer dimension is 3, the size of the inner dimension is 4. Really that is nothing more than a 3-element 1d array which element type is another 4-element 1d array which element type is <code>int*</code>.</p>\n\n<h2>Steps explained</h2>\n\n<p>So if you do</p>\n\n<pre><code>userMask[2][maskElement][user]\n</code></pre>\n\n<p>then essentially with the first two indices you pick the particular pointer out of the 2d array:</p>\n\n<pre><code>int * p = userMask[2][maskElement];\n</code></pre>\n\n<p>then you pick an int somewhere offset from that pointer by doing</p>\n\n<pre><code>p[user]\n</code></pre>\n\n<p>now that code is all in <code>userMask[2][maskElement][user]</code>. </p>\n\n<h2>Valid C Code</h2>\n\n<p>To do it step by step with valid c code (don't worry if you don't understand everything yet in the following):</p>\n\n<pre><code>int * userMask[3][4] = { { 0 } };\nint ** pa = userMask[2]; /* int*[4] becomes int** implicitly */\nint * pi = pa[maskElement];\nint i = pi[user];\n\nassert(i == userMask[2][maskElement][user]);\n</code></pre>\n\n<h2>Difference between Arrays and Pointers</h2>\n\n<p>So i think i show you something important. The array above does <em>not</em> contain pointers to arrays. Lets look how different they behave, which many c programmers don't expect:</p>\n\n<pre><code>int array[5][4][3];\n/* int[4][3] implicitly converts to int(*)[3] (pointer to first element) */\nint (*parray)[3] = array[0]; \nint ** pint = (int**) array[0]; /* wrong!! */\n</code></pre>\n\n<p>Now, what will happen if we do <code>parray[1]</code> and <code>pint[1]</code> ? The first will advance parray by <code>sizeof(int[3])</code> bytes (<code>3 * sizeof(int)</code>), the second will advance by only <code>sizeof( int* )</code> bytes. So actually while the first gives you the correct array <code>array[0][1]</code>, the second will give you <code>( char * )array[0] + sizeof( int* )</code>, which is somewhere we don't really want it to be. But grabbing the wrong offset is not all about it. Because it doesn't know an array is accessed, it will try to interpret what is at <code>pint[1]</code> as an <code>int*</code>. Say your array was initialized with <code>0x00</code>. Then it will do the next index step based off address 0x00 (Doing <code>pint[1][0]</code> for example). Oh noes - utterly undefined behavior! So it's really important to stress the difference.</p>\n\n<h2>Conclusion</h2>\n\n<p>This was more than you asked for, but I think it's quite important to know these details. Especially if you want to pass 2d arrays to functions then this knowledge is really useful. </p>\n"
},
{
"answer_id": 274944,
"author": "tabdamage",
"author_id": 28022,
"author_profile": "https://Stackoverflow.com/users/28022",
"pm_score": 0,
"selected": false,
"text": "<p>it helps if you read it like this:</p>\n\n<pre><code>type variablename[array_spec];\n</code></pre>\n\n<p>in this case:\n int* usermask[3][4];</p>\n\n<p>so its a matrix of int*.</p>\n\n<p>now, since c does not differentiate between pointer and arrays, you can use array indexing on pointers.</p>\n\n<pre><code>int* i;\nint the_int_behind_i = *(i+1);\nint also_the_int_behind_i = i[1];\n</code></pre>\n\n<p>This needs i to point to an area where several ints are lined up behind each other, of course, like an array.</p>\n\n<p>Note that the index operator[] used in the last examples looks like the array_spec in the first, but the two are quite different.</p>\n\n<p>So: userMask[2][maskElement][user]</p>\n\n<p>picks the usermask pointer stored at [2][maskElement], and evaluates it for the user <em>user</em></p>\n"
},
{
"answer_id": 274971,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 2,
"selected": false,
"text": "<p>Apply the inside-out rule.</p>\n\n<pre><code>int *userMask[3][4] = {0};\n</code></pre>\n\n<p>Starting at the innerpost part of the declaration,</p>\n\n<pre><code>userMask\n</code></pre>\n\n<p>is the name</p>\n\n<pre><code>userMask[3] \n</code></pre>\n\n<p>allocates space for (is a vector of) 3 of them</p>\n\n<pre><code>userMask[3][4] \n</code></pre>\n\n<p>allocates space for 4 <code>userMask[3]</code>'s</p>\n\n<pre><code>int *\n</code></pre>\n\n<p>tells us that <code>userMask</code> items are type pointer to <code>int</code></p>\n\n<p>and then <code>= {0}</code> is an initializer where all elements are <code>0</code>. So </p>\n\n<pre><code>int *userMask[3][4] = {0};\n</code></pre>\n\n<p>is a 3x4 array of int *, initialized to 0.</p>\n"
},
{
"answer_id": 274985,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if(userMask[2][maskElement][user] && blah)\n result = true;\n</code></pre>\n\n<p>The second part here is that there are no arrays in C; there is only pointer arithmetic. By definition, <code>p[i]</code> is always equivalent to <code>*(p+i)</code> so</p>\n\n<pre><code>userMask[2][maskElement][user]\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>*((userMask[2][maskElement])+user)\n</code></pre>\n\n<p>The code is somewhere assigning a vector (I'd bet money it's from a malloc(3c) or a similar call) to the pointer in that array; now your if is saying</p>\n\n<p><strong>IF</strong> the user-th element of the vector at userMask[2][maskElement] is non-zero</p>\n\n<p><strong>THEN IF</strong> blah is non-zero <em>(because of &&'s short circuit evaluation, the second conjunct doesn't get evaluated if the first conjunct is 0)</em></p>\n\n<p><strong>THEN</strong> set result = true.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35767/"
] |
I am modifying some code and came across a declaration that I am having trouble understanding:
```
int *userMask[3][4] = {0};
```
What exactly is this pointing to? Is it a matrix where every element is a pointer? Or is it pointing to a matrix of size [3][4]?
Thanks
---
I guess my question is how `userMask[2][maskElement][user]` can work when it is declared as `int`. Wouldn't userMask have to be `int[]` for that to work properly? I must not be understanding this right...
On a side note, thanks for your suggestion about cdecl Robert. However, does anyone know how to use it in an XP command prompt? All I can get is syntax error :(
|
Short answer
------------
Given userMask is declared as
```
int *userMask[3][4];
```
then `userMask` has type `int*[3][4]`. It's a 2d array of pointers to int. The size of the outer dimension is 3, the size of the inner dimension is 4. Really that is nothing more than a 3-element 1d array which element type is another 4-element 1d array which element type is `int*`.
Steps explained
---------------
So if you do
```
userMask[2][maskElement][user]
```
then essentially with the first two indices you pick the particular pointer out of the 2d array:
```
int * p = userMask[2][maskElement];
```
then you pick an int somewhere offset from that pointer by doing
```
p[user]
```
now that code is all in `userMask[2][maskElement][user]`.
Valid C Code
------------
To do it step by step with valid c code (don't worry if you don't understand everything yet in the following):
```
int * userMask[3][4] = { { 0 } };
int ** pa = userMask[2]; /* int*[4] becomes int** implicitly */
int * pi = pa[maskElement];
int i = pi[user];
assert(i == userMask[2][maskElement][user]);
```
Difference between Arrays and Pointers
--------------------------------------
So i think i show you something important. The array above does *not* contain pointers to arrays. Lets look how different they behave, which many c programmers don't expect:
```
int array[5][4][3];
/* int[4][3] implicitly converts to int(*)[3] (pointer to first element) */
int (*parray)[3] = array[0];
int ** pint = (int**) array[0]; /* wrong!! */
```
Now, what will happen if we do `parray[1]` and `pint[1]` ? The first will advance parray by `sizeof(int[3])` bytes (`3 * sizeof(int)`), the second will advance by only `sizeof( int* )` bytes. So actually while the first gives you the correct array `array[0][1]`, the second will give you `( char * )array[0] + sizeof( int* )`, which is somewhere we don't really want it to be. But grabbing the wrong offset is not all about it. Because it doesn't know an array is accessed, it will try to interpret what is at `pint[1]` as an `int*`. Say your array was initialized with `0x00`. Then it will do the next index step based off address 0x00 (Doing `pint[1][0]` for example). Oh noes - utterly undefined behavior! So it's really important to stress the difference.
Conclusion
----------
This was more than you asked for, but I think it's quite important to know these details. Especially if you want to pass 2d arrays to functions then this knowledge is really useful.
|
274,892 |
<p>I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.</p>
<p>I know how to connect to a single database using:</p>
<pre><code>$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
</code></pre>
<p>However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.</p>
|
[
{
"answer_id": 274919,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 9,
"selected": true,
"text": "<p><strong>Warning :</strong> <code>mysql_xx</code> functions are deprecated since php 5.5 and removed since php 7.0 (see <a href=\"http://php.net/manual/intro.mysql.php\" rel=\"noreferrer\">http://php.net/manual/intro.mysql.php</a>), use <code>mysqli_xx</code> functions or see the answer below from @Troelskn</p>\n\n<hr>\n\n<p>You can make multiple calls to <code>mysql_connect()</code>, but if the parameters are the same you need to pass true for the '<code>$new_link</code>' (fourth) parameter, otherwise the same connection is reused. For example:</p>\n\n<pre><code>$dbh1 = mysql_connect($hostname, $username, $password); \n$dbh2 = mysql_connect($hostname, $username, $password, true); \n\nmysql_select_db('database1', $dbh1);\nmysql_select_db('database2', $dbh2);\n</code></pre>\n\n<p>Then to query database 1 pass the first link identifier:</p>\n\n<pre><code>mysql_query('select * from tablename', $dbh1);\n</code></pre>\n\n<p>and for database 2 pass the second:</p>\n\n<pre><code>mysql_query('select * from tablename', $dbh2);\n</code></pre>\n\n<p>If you do not pass a link identifier then the last connection created is used (in this case the one represented by <code>$dbh2</code>) e.g.: </p>\n\n<pre><code>mysql_query('select * from tablename');\n</code></pre>\n\n<p><strong>Other options</strong></p>\n\n<p>If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:</p>\n\n<ul>\n<li>Keep one connection open and call <code>mysql_select_db()</code> to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.</li>\n<li>Specify the database name when you reference tables within your queries (e.g. <code>SELECT * FROM database2.tablename</code>). This is likely to be a pain to implement.</li>\n</ul>\n\n<p>Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.</p>\n"
},
{
"answer_id": 275013,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 7,
"selected": false,
"text": "<p>If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use <a href=\"http://docs.php.net/manual/en/book.pdo.php\" rel=\"noreferrer\">PDO</a>, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.</p>\n\n<p>You would connect through PDO, like this:</p>\n\n<pre><code>try {\n $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');\n} catch (PDOException $ex) {\n echo 'Connection failed: ' . $ex->getMessage();\n}\n</code></pre>\n\n<p>(Of course replace databasename, username and password above)</p>\n\n<p>You can then query the database like this:</p>\n\n<pre><code>$result = $db->query(\"select * from tablename\");\nforeach ($result as $row) {\n echo $row['foo'] . \"\\n\";\n}\n</code></pre>\n\n<p>Or, if you have variables:</p>\n\n<pre><code>$stmt = $db->prepare(\"select * from tablename where id = :id\");\n$stmt->execute(array(':id' => 42));\n$row = $stmt->fetch();\n</code></pre>\n\n<p>If you need multiple connections open at once, you can simply create multiple instances of PDO:</p>\n\n<pre><code>try {\n $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');\n $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');\n} catch (PDOException $ex) {\n echo 'Connection failed: ' . $ex->getMessage();\n}\n</code></pre>\n"
},
{
"answer_id": 11681005,
"author": "Michael Ratcliffe",
"author_id": 1233967,
"author_profile": "https://Stackoverflow.com/users/1233967",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you really need to have more than one instance of a PDO object in play, consider the following:</p>\n\n<pre><code>$con = new PDO('mysql:host=localhost', $username, $password, \n array(PDO::ATTR_PERSISTENT => true));\n</code></pre>\n\n<p>Notice the absence of <code>dbname=</code> in the construction arguments. </p>\n\n<p>When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the <code>USE dbname</code> statement via the <code>PDO::exec()</code> method.</p>\n\n<pre><code>$con->exec(\"USE someDatabase\");\n$con->exec(\"USE anotherDatabase\");\n</code></pre>\n\n<p>Of course you may want to wrap this in a catch try statement.</p>\n"
},
{
"answer_id": 15000921,
"author": "Paks",
"author_id": 2095172,
"author_profile": "https://Stackoverflow.com/users/2095172",
"pm_score": 3,
"selected": false,
"text": "<p>Try below code:</p>\n\n<pre><code> $conn = mysql_connect(\"hostname\",\"username\",\"password\");\n mysql_select_db(\"db1\",$conn);\n mysql_select_db(\"db2\",$conn);\n\n $query1 = \"SELECT * FROM db1.table\";\n $query2 = \"SELECT * FROM db2.table\";\n</code></pre>\n\n<p>You can fetch data of above query from both database as below</p>\n\n<pre><code>$rs = mysql_query($query1);\nwhile($row = mysql_fetch_assoc($rs)) {\n $data1[] = $row;\n}\n\n$rs = mysql_query($query2);\nwhile($row = mysql_fetch_assoc($rs)) {\n $data2[] = $row;\n}\n\nprint_r($data1);\nprint_r($data2);\n</code></pre>\n"
},
{
"answer_id": 18506596,
"author": "Lazy Fellow",
"author_id": 1578851,
"author_profile": "https://Stackoverflow.com/users/1578851",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$dbh1 = mysql_connect($hostname, $username, $password); \n$dbh2 = mysql_connect($hostname, $username, $password, true); \n\nmysql_select_db('database1', $dbh1); \nmysql_select_db('database2',$dbh2); \n\nmysql_query('select * from tablename', $dbh1);\nmysql_query('select * from tablename', $dbh2);\n</code></pre>\n\n<p>This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.</p>\n"
},
{
"answer_id": 19010747,
"author": "Ihsan Kusasi",
"author_id": 2720077,
"author_profile": "https://Stackoverflow.com/users/2720077",
"pm_score": 3,
"selected": false,
"text": "<p>I just made my life simple:</p>\n\n<pre><code>CREATE VIEW another_table AS SELECT * FROM another_database.another_table;\n</code></pre>\n\n<p>hope it is helpful... cheers...</p>\n"
},
{
"answer_id": 25114222,
"author": "user3857891",
"author_id": 3857891,
"author_profile": "https://Stackoverflow.com/users/3857891",
"pm_score": 2,
"selected": false,
"text": "<p>You might be able to use MySQLi syntax, which would allow you to handle it better.</p>\n\n<p>Define the database connections, then whenever you want to query one of the database, specify the right connection.</p>\n\n<p>E.g.:</p>\n\n<pre><code>$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection \n$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection\n</code></pre>\n\n<p>Then to query them on the same page, use something like:</p>\n\n<pre><code>$query = $Db1->query(\"select * from tablename\")\n$query2 = $Db2->query(\"select * from tablename\")\ndie(\"$Db1->error\");\n</code></pre>\n\n<p>Changing to MySQLi in this way will help you.</p>\n"
},
{
"answer_id": 29739049,
"author": "kaushik",
"author_id": 2206657,
"author_profile": "https://Stackoverflow.com/users/2206657",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of <a href=\"http://php.net/mysql_connect\" rel=\"nofollow\">mysql_connect</a> use <a href=\"http://php.net/mysqli_connect\" rel=\"nofollow\">mysqli_connect</a>.</p>\n\n<p>mysqli is provide a functionality for connect multiple database at a time.</p>\n\n<pre><code>$Db1 = new mysqli($hostname,$username,$password,$db_name1); \n// this is connection 1 for DB 1\n\n$Db2 = new mysqli($hostname,$username,$password,$db_name2); \n// this is connection 2 for DB 2\n</code></pre>\n"
},
{
"answer_id": 42818799,
"author": "Kamal Bunkar",
"author_id": 1302648,
"author_profile": "https://Stackoverflow.com/users/1302648",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using mysqli and have two db_connection file. like\nfirst one is</p>\n\n<pre><code>define('HOST','localhost');\ndefine('USER','user');\ndefine('PASS','passs');\ndefine('**DB1**','database_name1');\n\n$connMitra = new mysqli(HOST, USER, PASS, **DB1**);\n</code></pre>\n\n<p>second one is</p>\n\n<pre><code> define('HOST','localhost');\n define('USER','user');\n define('PASS','passs');\n define(**'DB2**','database_name1');\n\n $connMitra = new mysqli(HOST, USER, PASS, **DB2**);\n</code></pre>\n\n<p>SO just change the name of parameter pass in mysqli like DB1 and DB2.\n if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function </p>\n"
},
{
"answer_id": 45688265,
"author": "Nagibaba",
"author_id": 6170191,
"author_profile": "https://Stackoverflow.com/users/6170191",
"pm_score": 2,
"selected": false,
"text": "<p>You don't actually need <code>select_db</code>. You can send a query to two databases at the same time. First, give a grant to <code>DB1</code> to select from <code>DB2</code> by <code>GRANT select ON DB2.* TO DB1@localhost;</code>. Then, <code>FLUSH PRIVILEGES;</code>. Finally, you are able to do 'multiple-database query' like <code>SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2</code> etc. (Don't forget that you need 'root' access to use grant command)</p>\n"
},
{
"answer_id": 55899580,
"author": "htngapi",
"author_id": 4010310,
"author_profile": "https://Stackoverflow.com/users/4010310",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n // Sapan Mohanty\n // Skype:sapan.mohannty\n //***********************************\n $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');\n echo mysql_error();\n $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');\n echo mysql_error();\n mysql_select_db('OLDDBNAME', $oldData );\n mysql_select_db('NEWDBNAME', $NewData );\n $getAllTablesName = \"SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'\";\n $getAllTablesNameExe = mysql_query($getAllTablesName);\n //echo mysql_error();\n while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {\n\n $oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);\n $oldDataCountResult = mysql_fetch_object($oldDataCount);\n\n\n $newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);\n $newDataCountResult = mysql_fetch_object($newDataCount);\n\n if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {\n echo \"<br/><b>\" . $dataTableName->table_name . \"</b>\";\n echo \" | Old: \" . $oldDataCountResult->noOfRecord;\n echo \" | New: \" . $newDataCountResult->noOfRecord;\n\n if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {\n echo \" | <font color='green'>*</font>\";\n\n } else {\n echo \" | <font color='red'>*</font>\";\n }\n\n echo \"<br/>----------------------------------------\";\n\n } \n\n }\n ?>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33194/"
] |
I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
I know how to connect to a single database using:
```
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
```
However, can I just use multiple "mysql\_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
|
**Warning :** `mysql_xx` functions are deprecated since php 5.5 and removed since php 7.0 (see <http://php.net/manual/intro.mysql.php>), use `mysqli_xx` functions or see the answer below from @Troelskn
---
You can make multiple calls to `mysql_connect()`, but if the parameters are the same you need to pass true for the '`$new_link`' (fourth) parameter, otherwise the same connection is reused. For example:
```
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
```
Then to query database 1 pass the first link identifier:
```
mysql_query('select * from tablename', $dbh1);
```
and for database 2 pass the second:
```
mysql_query('select * from tablename', $dbh2);
```
If you do not pass a link identifier then the last connection created is used (in this case the one represented by `$dbh2`) e.g.:
```
mysql_query('select * from tablename');
```
**Other options**
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
* Keep one connection open and call `mysql_select_db()` to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
* Specify the database name when you reference tables within your queries (e.g. `SELECT * FROM database2.tablename`). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
|
274,899 |
<p>How have you guys handled working with jQuery includes </p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
</code></pre>
<p>in Asp.Net MVC when working with partial views/view controls? Basically, I don't want to make the jquery include in the master page because I am not using jquery in all of my views, but I also want an easy way for a user control to be able to create the jquery include in the right location ('head') without creating duplicate jquery includes.</p>
<p>The best way would be to use a ScriptManaager, but I do not want to rely on ASP.Net Ajax for this in my application. Is there a 'lightweight' ScriptManager that I could use that would also allow the newly released intellisense for jquery? </p>
<p>I've created a WebControl that provides this functionality, but I don't get the intellisense support for VS2008, which I would really like.</p>
<p>Hope this makes sense.</p>
|
[
{
"answer_id": 274906,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>You could always do this:</p>\n\n<p>make a lightweight util.js that is in every page, in it you could put various common stuff, plus this:</p>\n\n<pre><code>function loadJSInclude(scriptPath, callback)\n{\n var scriptNode = document.createElement('SCRIPT');\n scriptNode.type = 'text/javascript';\n scriptNode.src = scriptPath;\n\n var headNode = document.getElementsByTagName('HEAD');\n if (headNode[0] != null)\n headNode[0].appendChild(scriptNode);\n\n if (callback != null) \n {\n scriptNode.onreadystagechange = callback; \n scriptNode.onload = callback;\n }\n}\n</code></pre>\n\n<p>Then, in your view, just place:</p>\n\n<pre><code><script type='text/javascript'>\n if(typeof(someJqueryObject) == \"undefined\") \n loadJSInclude('jquery.js', doYourStuff); \n else \n doYourStuff();\n\n function doYourStuff()\n {\n // jQuery will be loaded now, so you can do your stuff here.\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 274907,
"author": "Chad Moran",
"author_id": 25416,
"author_profile": "https://Stackoverflow.com/users/25416",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure how to do this with only partial views though you could do it on a page-by-page basis with existing technology.</p>\n\n<p>You could create a ContentPlaceHolder in your master page inside of the head tag. Than in your user controls just put the jQuery include in the ContentPlaceHolder content area of your pages.</p>\n"
},
{
"answer_id": 275522,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 5,
"selected": true,
"text": "<p>If you use JQuery in a high percentage of your pages, I'd just put it in the master page. It's only going to be downloaded once at which point it's cached on the browser and will have negligible impact on perf for rendering your page.</p>\n"
},
{
"answer_id": 4465079,
"author": "Sean",
"author_id": 545305,
"author_profile": "https://Stackoverflow.com/users/545305",
"pm_score": 1,
"selected": false,
"text": "<p>Ahh trying to post this is driving me nuts cause it's being treated as part of the page... but </p>\n\n<pre><code><script src=\"<%=Url.Content(\"~/Content/js/jquery-1.2.3.min.js\") %>\" type=\"text/javascript\"></script>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8534/"
] |
How have you guys handled working with jQuery includes
```
<script type="text/javascript" src="jquery.js"></script>
```
in Asp.Net MVC when working with partial views/view controls? Basically, I don't want to make the jquery include in the master page because I am not using jquery in all of my views, but I also want an easy way for a user control to be able to create the jquery include in the right location ('head') without creating duplicate jquery includes.
The best way would be to use a ScriptManaager, but I do not want to rely on ASP.Net Ajax for this in my application. Is there a 'lightweight' ScriptManager that I could use that would also allow the newly released intellisense for jquery?
I've created a WebControl that provides this functionality, but I don't get the intellisense support for VS2008, which I would really like.
Hope this makes sense.
|
If you use JQuery in a high percentage of your pages, I'd just put it in the master page. It's only going to be downloaded once at which point it's cached on the browser and will have negligible impact on perf for rendering your page.
|
274,915 |
<p>What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?</p>
|
[
{
"answer_id": 274916,
"author": "Jared",
"author_id": 14744,
"author_profile": "https://Stackoverflow.com/users/14744",
"pm_score": 2,
"selected": false,
"text": "<p>Use Swig, it allows you to generate code for multiple languages that calls any C/C++ functions.\n<a href=\"http://www.swig.org/\" rel=\"nofollow noreferrer\">http://www.swig.org/</a></p>\n"
},
{
"answer_id": 274921,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": 2,
"selected": false,
"text": "<p>That really depends on the language... some languages can bind directly to c/c++ libraries, others such as java needs to have explicit interfaces written. If you are trying to solve a specific problem, I would suggest that you provide more details about what you are trying to do.</p>\n"
},
{
"answer_id": 274924,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "<p>It's going to depend on the language and what sort of integration you want.</p>\n\n<p>All of those languages will let you execute an system command, so you could build your C into an executable, and invoke it like a command. In Python:</p>\n\n<pre><code>os.system(\"myccode -v args etc\")\n</code></pre>\n\n<p>The downside of this method is that you don't share any memory state, or return much information, and you have the overhead of spinning up a process. On the plus side, it's usable everywhere, and very low-tech.</p>\n\n<p>Each language has their own mechanism for invoking C within the same process. Python for example has C API, and you can build your C code into a Python extension. This allows for a very tight integration, but is more work, both in learning the C API, and in carefully writing the code to not leak memory.</p>\n\n<p>Python also provides <a href=\"http://www.python.org/doc/2.5.2/lib/module-ctypes.html\" rel=\"nofollow noreferrer\">ctypes</a>, which can invoke C DLLs. This is a bit easier than a full C extension, but doesn't provide all the same opportunities for integration.</p>\n"
},
{
"answer_id": 274979,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<h2>From Perl</h2>\n<p><a href=\"http://search.cpan.org/perldoc?Inline::C\" rel=\"nofollow noreferrer\">Inline::C</a><br>\n<a href=\"http://search.cpan.org/perldoc?Inline::CPP\" rel=\"nofollow noreferrer\">Inline::CPP</a><br>\n<a href=\"http://search.cpan.org/perldoc?Inline::Java\" rel=\"nofollow noreferrer\">Inline::Java</a><br>\n<a href=\"http://search.cpan.org/perldoc?Inline::Python\" rel=\"nofollow noreferrer\">Inline::Python</a><br>\n<a href=\"http://search.cpan.org/perldoc?Inline::Lua\" rel=\"nofollow noreferrer\">Inline::Lua</a></p>\n<p>excerpt from <a href=\"http://search.cpan.org/dist/Inline/C/C-Cookbook.pod\" rel=\"nofollow noreferrer\">Inline::C-Cookbook</a>:</p>\n<pre><code>use Inline C => <<'END_C';\n\n void greet() {\n printf("Hello, world\\n");\n }\nEND_C\n\ngreet;\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
] |
What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?
|
From Perl
---------
[Inline::C](http://search.cpan.org/perldoc?Inline::C)
[Inline::CPP](http://search.cpan.org/perldoc?Inline::CPP)
[Inline::Java](http://search.cpan.org/perldoc?Inline::Java)
[Inline::Python](http://search.cpan.org/perldoc?Inline::Python)
[Inline::Lua](http://search.cpan.org/perldoc?Inline::Lua)
excerpt from [Inline::C-Cookbook](http://search.cpan.org/dist/Inline/C/C-Cookbook.pod):
```
use Inline C => <<'END_C';
void greet() {
printf("Hello, world\n");
}
END_C
greet;
```
|
274,918 |
<p>The CSS Friendly Control Adapters for ASP.NET are great for creating markup that is easy to style. A big benefit of the GridView adapter is that it generates THEAD, TBODY, and TFOOT tags, which allow you to do some really great things with libraries like jQuery - for instance, <a href="http://tablesorter.com/docs/" rel="nofollow noreferrer">Tablesorter</a> for client-side table sorting.</p>
<p>The problem is that it seems to be a global on/off for the adapters through the CSSFriendlyAdapters.browser file. What do I do if I already have a slew of GridViews currently in production and only want to use the CSS Friendly Adapters for a new one?</p>
<p>So I would be interested in two types of solutions:</p>
<p>1) A way to extend or modify GridView (a new tag is acceptable) to output THEAD and TBODY tags.</p>
<p>2) A way to conditionally apply or disable CSS Friendly Control Adapters.</p>
|
[
{
"answer_id": 276469,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>CSS Friendly...</p>\n\n<blockquote>\n <p>Disabling Adapters</p>\n \n <p>If you explicitly add\n AdapterEnabled=\"false\" to your\n server-side tag, these sample adapters\n will attempt to use the ASP.NET\n framework's native rendering for the\n control. Beware: this is not supported\n and often does not work well.\n Fundamentally, the framework does not\n support disabling adapters on a per\n control basis. The AdapterEnabled\n attribute is only intended to be used\n experimentally.</p>\n</blockquote>\n\n<p><a href=\"http://www.asp.net/cssadapters/WhitePaper.aspx#Samples\" rel=\"nofollow noreferrer\">Source</a></p>\n\n<p>Alternatively, you can create a class that derives from GridView and overrides the RenderChildren method. It may take some experimentation to figure out how to make this work. I haven't looked at how the controls are presented in the GridView to give you any ideas in this regard. Presumably, you'll just need to figure out which rows are header/foot and render / around them and around the others.</p>\n"
},
{
"answer_id": 279464,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 0,
"selected": false,
"text": "<p>I found a method of creating the THEAD and TBODY tags:</p>\n\n<p>Source: <a href=\"http://www.codeproject.com/KB/aspnet/SortableGridViewjQuery.aspx\" rel=\"nofollow noreferrer\">Sortable GridView using jQuery's TableSorter</a></p>\n\n<p>Bare Bones Details:</p>\n\n<pre><code>myGrid.UseAccessibleHeader = true;\nmyGrid.HeaderRow.TableSection = TableRowSection.TableHeader;\nmyGrid.FooterRow.TableSection = TableRowSection.TableFooter;\n</code></pre>\n"
},
{
"answer_id": 1158060,
"author": "ChrisCa",
"author_id": 17194,
"author_profile": "https://Stackoverflow.com/users/17194",
"pm_score": 3,
"selected": true,
"text": "<p>I just did something similar to this after doing a little research</p>\n\n<p>you need to subclass the control you want to use (gridview in your case, radiobuttonlist in my case)</p>\n\n<pre><code>public class UlRadioButtonList : RadioButtonList\n {\n protected override void Render(System.Web.UI.HtmlTextWriter writer)\n {\n // Call the base RenderContents method.\n base.Render(writer);\n }\n }\n</code></pre>\n\n<p>Then just have the .browser file refer to your custom subclass, instead of the asp.net control</p>\n\n<p>e.g.</p>\n\n<pre><code><browsers>\n <browser refID=\"Default\">\n <controlAdapters>\n <adapter controlType=\"FM.Web.Source.WebControls.UlRadioButtonList\" adapterType=\"FM.Web.Source.ControlAdapters.RadioButtonListAdapter\" />\n </controlAdapters>\n </browser>\n</browsers>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10039/"
] |
The CSS Friendly Control Adapters for ASP.NET are great for creating markup that is easy to style. A big benefit of the GridView adapter is that it generates THEAD, TBODY, and TFOOT tags, which allow you to do some really great things with libraries like jQuery - for instance, [Tablesorter](http://tablesorter.com/docs/) for client-side table sorting.
The problem is that it seems to be a global on/off for the adapters through the CSSFriendlyAdapters.browser file. What do I do if I already have a slew of GridViews currently in production and only want to use the CSS Friendly Adapters for a new one?
So I would be interested in two types of solutions:
1) A way to extend or modify GridView (a new tag is acceptable) to output THEAD and TBODY tags.
2) A way to conditionally apply or disable CSS Friendly Control Adapters.
|
I just did something similar to this after doing a little research
you need to subclass the control you want to use (gridview in your case, radiobuttonlist in my case)
```
public class UlRadioButtonList : RadioButtonList
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
// Call the base RenderContents method.
base.Render(writer);
}
}
```
Then just have the .browser file refer to your custom subclass, instead of the asp.net control
e.g.
```
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="FM.Web.Source.WebControls.UlRadioButtonList" adapterType="FM.Web.Source.ControlAdapters.RadioButtonListAdapter" />
</controlAdapters>
</browser>
</browsers>
```
|
274,951 |
<p>You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.</p>
<p>However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons.</p>
<p>A trivial example would be if you were sorting a collection of objects that represent contact data. Sometimes you will want to sort by <pre>last name, first name, area code</pre>. Other times <pre>first name, last name</pre> - yet other times <pre>age, first name, area code</pre>... etc</p>
<p>Now, you can certainly write an additional function object for each case, but that violates the DRY principle - especially if each comparison is less trivial.</p>
<p>It seems like you should be able to write a hierarchy of comparison functions - the low level ones do the single, primitive, comparisons (e.g. first name < first name), then higher level ones call the lower level ones in succession (probably chaining with && to make use of short circuit evaluation) to generate the composite functions.</p>
<p>The trouble with this approach is that std::sort takes a binary predicate - the predicate can only return a bool. So if you're composing them you can't tell if a "false" indicates equality or greater than. You can make your lower level predicates return an int, with three states - but then you would have to wrap those in higher level predicates before they could be used with std::sort on their own.</p>
<p>In all, these are not insurmountable problems. It just seems harder than it should be - and certainly invites a helper library implementation.</p>
<p>Therefore, does anyone know of any pre-existing library (esp. if it's a std or boost library) that can help here - of have any other thoughts on the matter?</p>
<p>[Update]</p>
<p>As mentioned in some of the comments - I've gone ahead and written my own implementation of a class to manage this. It's fairly minimal, and probably has some issues with it in general. but on that basis, for anyone interested, the class is here:</p>
<p><a href="http://pastebin.com/f52a85e4f" rel="noreferrer">http://pastebin.com/f52a85e4f</a></p>
<p>And some helper functions (to avoid the need to specify template args) is here:</p>
<p><a href="http://pastebin.com/fa03d66e" rel="noreferrer">http://pastebin.com/fa03d66e</a></p>
|
[
{
"answer_id": 274963,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>One conventional way to handle this is to sort in multiple passes and use a stable sort. Notice that <code>std::sort</code> is generally <em>not</em> stable. However, there’s <code>std::stable_sort</code>.</p>\n\n<p>That said, I would write a wrapper around functors that return a tristate (representing less, equals, greater).</p>\n"
},
{
"answer_id": 275014,
"author": "siukurnin",
"author_id": 35273,
"author_profile": "https://Stackoverflow.com/users/35273",
"pm_score": 2,
"selected": false,
"text": "<p><code>std::sort</code> is not guaranteed to be stable because stable sorts are usually slower than non-stable ones ... so using a stable sort multiple times looks like a recipe for performance trouble...</p>\n\n<p>And yes it's really a shame that sort ask for a predicate:\nI see no other way than create a functor accepting a vector of tristate functions ...</p>\n"
},
{
"answer_id": 275033,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 4,
"selected": true,
"text": "<p>You could build a little chaining system like so:</p>\n\n<pre><code>struct Type {\n string first, last;\n int age;\n};\n\nstruct CmpFirst {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; }\n};\n\nstruct CmpLast {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; }\n};\n\nstruct CmpAge {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.age < rhs.age; }\n};\n\ntemplate <typename First, typename Second>\nstruct Chain {\n Chain(const First& f_, const Second& s_): f(f_), s(s_) {}\n\n bool operator () (const Type& lhs, const Type& rhs) {\n if(f(lhs, rhs))\n return true;\n if(f(rhs, lhs))\n return false;\n\n return s(lhs, rhs);\n }\n\n template <typename Next>\n Chain <Chain, Next> chain(const Next& next) const {\n return Chain <Chain, Next> (*this, next);\n }\n\n First f;\n Second s;\n};\n\nstruct False { bool operator() (const Type& lhs, const Type& rhs) { return false; } };\n\ntemplate <typename Op>\nChain <False, Op> make_chain(const Op& op) { return Chain <False, Op> (False(), op); }\n</code></pre>\n\n<p>Then to use it:</p>\n\n<pre><code>vector <Type> v; // fill this baby up\n\nsort(v.begin(), v.end(), make_chain(CmpLast()).chain(CmpFirst()).chain(CmpAge()));\n</code></pre>\n\n<p>The last line is a little verbose, but I think it's clear what's intended.</p>\n"
},
{
"answer_id": 276172,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 1,
"selected": false,
"text": "<p>The chaining solution is verbose. You could also use boost::bind in conjunction with std::logical_and to build your sorting predicate. See the linked article for more information: <a href=\"http://www.informit.com/articles/article.aspx?p=412354&seqNum=4\" rel=\"nofollow noreferrer\" title=\"How the boost bind library can improve your C++ programs\">How the boost bind library can improve your C++ programs</a></p>\n"
},
{
"answer_id": 11167563,
"author": "Voivoid",
"author_id": 309265,
"author_profile": "https://Stackoverflow.com/users/309265",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this:</p>\n\n<p>Usage:</p>\n\n<pre><code>struct Citizen {\n std::wstring iFirstName;\n std::wstring iLastName;\n};\n\nChainComparer<Citizen> cmp;\ncmp.Chain<std::less>( boost::bind( &Citizen::iLastName, _1 ) );\ncmp.Chain<std::less>( boost::bind( &Citizen::iFirstName, _1 ) );\n\nstd::vector<Citizen> vec;\nstd::sort( vec.begin(), vec.end(), cmp );\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>template <typename T>\nclass ChainComparer {\npublic:\n\n typedef boost::function<bool(const T&, const T&)> TComparator;\n typedef TComparator EqualComparator;\n typedef TComparator CustomComparator;\n\n template <template <typename> class TComparer, typename TValueGetter>\n void Chain( const TValueGetter& getter ) {\n\n iComparers.push_back( std::make_pair( \n boost::bind( getter, _1 ) == boost::bind( getter, _2 ), \n boost::bind( TComparer<TValueGetter::result_type>(), boost::bind( getter, _1 ), boost::bind( getter, _2 ) ) \n ) );\n }\n\n bool operator()( const T& lhs, const T& rhs ) {\n BOOST_FOREACH( const auto& comparer, iComparers ) {\n if( !comparer.first( lhs, rhs ) ) {\n return comparer.second( lhs, rhs );\n }\n }\n\n return false;\n }\n\nprivate:\n std::vector<std::pair<EqualComparator, CustomComparator>> iComparers;\n};\n</code></pre>\n"
},
{
"answer_id": 15014633,
"author": "Alexander Oh",
"author_id": 887836,
"author_profile": "https://Stackoverflow.com/users/887836",
"pm_score": 1,
"selected": false,
"text": "<p>Variadic templates in C++ 11 give a shorter option:</p>\n\n<pre><code> #include <iostream>\n using namespace std;\n\n struct vec { int x,y,z; };\n\n struct CmpX {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.x < rhs.x; }\n };\n\n struct CmpY {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.y < rhs.y; }\n };\n\n struct CmpZ {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.z < rhs.z; }\n };\n\n template <typename T>\n bool chained(const T &, const T &) {\n return false;\n }\n\n template <typename CMP, typename T, typename ...P>\n bool chained(const T &t1, const T &t2, const CMP &c, P...p) {\n if (c(t1,t2)) { return true; }\n if (c(t2,t1)) { return false; }\n else { return chained(t1, t2, p...); }\n }\n\n int main(int argc, char **argv) {\n vec x = { 1,2,3 }, y = { 2,2,3 }, z = { 1,3,3 };\n cout << chained(x,x,CmpX(),CmpY(),CmpZ()) << endl;\n return 0;\n }\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32136/"
] |
You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.
However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons.
A trivial example would be if you were sorting a collection of objects that represent contact data. Sometimes you will want to sort by
```
last name, first name, area code
```
. Other times
```
first name, last name
```
- yet other times
```
age, first name, area code
```
... etc
Now, you can certainly write an additional function object for each case, but that violates the DRY principle - especially if each comparison is less trivial.
It seems like you should be able to write a hierarchy of comparison functions - the low level ones do the single, primitive, comparisons (e.g. first name < first name), then higher level ones call the lower level ones in succession (probably chaining with && to make use of short circuit evaluation) to generate the composite functions.
The trouble with this approach is that std::sort takes a binary predicate - the predicate can only return a bool. So if you're composing them you can't tell if a "false" indicates equality or greater than. You can make your lower level predicates return an int, with three states - but then you would have to wrap those in higher level predicates before they could be used with std::sort on their own.
In all, these are not insurmountable problems. It just seems harder than it should be - and certainly invites a helper library implementation.
Therefore, does anyone know of any pre-existing library (esp. if it's a std or boost library) that can help here - of have any other thoughts on the matter?
[Update]
As mentioned in some of the comments - I've gone ahead and written my own implementation of a class to manage this. It's fairly minimal, and probably has some issues with it in general. but on that basis, for anyone interested, the class is here:
<http://pastebin.com/f52a85e4f>
And some helper functions (to avoid the need to specify template args) is here:
<http://pastebin.com/fa03d66e>
|
You could build a little chaining system like so:
```
struct Type {
string first, last;
int age;
};
struct CmpFirst {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; }
};
struct CmpLast {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; }
};
struct CmpAge {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.age < rhs.age; }
};
template <typename First, typename Second>
struct Chain {
Chain(const First& f_, const Second& s_): f(f_), s(s_) {}
bool operator () (const Type& lhs, const Type& rhs) {
if(f(lhs, rhs))
return true;
if(f(rhs, lhs))
return false;
return s(lhs, rhs);
}
template <typename Next>
Chain <Chain, Next> chain(const Next& next) const {
return Chain <Chain, Next> (*this, next);
}
First f;
Second s;
};
struct False { bool operator() (const Type& lhs, const Type& rhs) { return false; } };
template <typename Op>
Chain <False, Op> make_chain(const Op& op) { return Chain <False, Op> (False(), op); }
```
Then to use it:
```
vector <Type> v; // fill this baby up
sort(v.begin(), v.end(), make_chain(CmpLast()).chain(CmpFirst()).chain(CmpAge()));
```
The last line is a little verbose, but I think it's clear what's intended.
|
274,952 |
<p>Say I have the following interface that I want to share between my server (a regular web service) and my client (a silverlight 2.0 application):</p>
<pre><code>public interface ICustomerService
{
Customer GetCustomer(string name);
}
</code></pre>
<p>My web service implements this interface, and references a class library where <code>Customer</code> type is defined.</p>
<p>Usually, if you want to consume this service from a WCF client, say a winforms app, you could share your model assembly and your service contract interfaces. Then, by using a <code>ChannelFactory</code>, you can dynamically create a proxy which implements your service interface. Something like:</p>
<pre><code>ICustomerService myService = new ChannelFactory<ICustomerService>(myBinding, myEndpoint);
Customer customer = myService.GetCustomer("romain");
</code></pre>
<p>I basically want to do the same thing, but from a Silverlight 2.0 application. The silverlight <code>ChannelFactory</code> doesn't seems to act like the other one...</p>
<p><strong>Do you know if it's possible ?</strong></p>
<p>Note : Since a Silverlight application can only refers Silverlight projects, I have:</p>
<p>Two versions of MyModel.dll which contains <code>Customer</code> type:</p>
<ul>
<li>One compiled targetting .NET framework 3.5, referenced by my web service project </li>
<li>Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app</li>
</ul>
<p>Two versions of MyServicesContracts.dll which contains <code>ICustomerService</code> interface:</p>
<ul>
<li>One compiled targetting .NET framework 3.5, referenced by my web service project </li>
<li>Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app</li>
</ul>
|
[
{
"answer_id": 274962,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 3,
"selected": true,
"text": "<p>I think you will find this <a href=\"http://silverlight.net/forums/t/34368.aspx\" rel=\"nofollow noreferrer\">thread</a> interesting. You can share code files between separate projects or compile a single project against multiple targets.</p>\n"
},
{
"answer_id": 276513,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 0,
"selected": false,
"text": "<p>I could be wrong, but I think if you decorate objects being returned by your WCF Service with the DataContract and DataMember attributes, you should be able to share objects between your Silverlight application and WCF service without creating the class in your client (should be handled by the proxy.</p>\n"
},
{
"answer_id": 287226,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Very short...</p>\n\n<p><br>\n You can have your proxies created under the silverlight application adding a service reference to your service. When you do this, you'll have your proxies automaticaly generated on the client.</p>\n\n<p><br>\nYour wcf services interfaces must be anotated with DataContract and OperationContract attributes and the POCO classes used with this services must have DataContract and DataMember attributes. </p>\n\n<p><br>\n<a href=\"http://msdn.microsoft.com/en-us/library/cc197940(VS.95).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc197940(VS.95).aspx</a></p>\n"
},
{
"answer_id": 11565587,
"author": "Ahmed Ghoneim",
"author_id": 713777,
"author_profile": "https://Stackoverflow.com/users/713777",
"pm_score": 0,
"selected": false,
"text": "<p>I know it's too late to provide a solution but it was my problem too and I found <a href=\"http://msdn.microsoft.com/en-us/library/gg597391.aspx\" rel=\"nofollow\">Portable Class Libraries</a>. It's a perfect solution to your issue.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
Say I have the following interface that I want to share between my server (a regular web service) and my client (a silverlight 2.0 application):
```
public interface ICustomerService
{
Customer GetCustomer(string name);
}
```
My web service implements this interface, and references a class library where `Customer` type is defined.
Usually, if you want to consume this service from a WCF client, say a winforms app, you could share your model assembly and your service contract interfaces. Then, by using a `ChannelFactory`, you can dynamically create a proxy which implements your service interface. Something like:
```
ICustomerService myService = new ChannelFactory<ICustomerService>(myBinding, myEndpoint);
Customer customer = myService.GetCustomer("romain");
```
I basically want to do the same thing, but from a Silverlight 2.0 application. The silverlight `ChannelFactory` doesn't seems to act like the other one...
**Do you know if it's possible ?**
Note : Since a Silverlight application can only refers Silverlight projects, I have:
Two versions of MyModel.dll which contains `Customer` type:
* One compiled targetting .NET framework 3.5, referenced by my web service project
* Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app
Two versions of MyServicesContracts.dll which contains `ICustomerService` interface:
* One compiled targetting .NET framework 3.5, referenced by my web service project
* Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app
|
I think you will find this [thread](http://silverlight.net/forums/t/34368.aspx) interesting. You can share code files between separate projects or compile a single project against multiple targets.
|
274,984 |
<p>How can I correctly serve WSDL of a WCF webservice located in a private LAN from behind a reverse proxy listening on public IP?</p>
<p>I have an Apache webserver configured in reverse proxy mode which listens for requests on a public IP address and serves them from the internal IIS host. WCF webservice generates WSDL using the FQDN address of the LAN host which, of course, cannot be read by an internet web service client.</p>
<p>Is there any setting that can be configured in wcf application's web.config or in IIS in order to customize the WSDL generated containing host address and put public address instead?</p>
|
[
{
"answer_id": 399780,
"author": "Nicolas Dorier",
"author_id": 19803,
"author_profile": "https://Stackoverflow.com/users/19803",
"pm_score": 0,
"selected": false,
"text": "<p><strong>See</strong>: <a href=\"https://learn.microsoft.com/en-us/archive/msdn-magazine/2007/june/service-station-wcf-addressing-in-depth\" rel=\"nofollow noreferrer\">Service Station WCF Addressing In Depth</a> by Aaron Skonnard</p>\n<p><del><a href=\"https://web.archive.org/web/20110514060231/http://msdn.microsoft.com/en-us/magazine/cc163412.aspx\" rel=\"nofollow noreferrer\">archive link</a></del></p>\n"
},
{
"answer_id": 464410,
"author": "stephenl",
"author_id": 50354,
"author_profile": "https://Stackoverflow.com/users/50354",
"pm_score": 1,
"selected": false,
"text": "<p>I'm having similar issues, one of which was the resolution of public and server addresses. This solved that issue although I still have a couple authentication problems.</p>\n<p><strong>See</strong>: <a href=\"https://learn.microsoft.com/en-us/archive/blogs/wenlong/how-to-change-hostname-in-wsdl-for-an-iis-hosted-service\" rel=\"nofollow noreferrer\">How to change HostName in WSDL for an IIS-hosted service?</a> by Wenlong Dong</p>\n<p><del><a href=\"https://web.archive.org/web/20140516150723/http://blogs.msdn.com/b/wenlong/archive/2007/08/02/how-to-change-hostname-in-wsdl-of-an-iis-hosted-service.aspx\" rel=\"nofollow noreferrer\">archive</a></del></p>\n"
},
{
"answer_id": 947276,
"author": "Richard Collette",
"author_id": 107683,
"author_profile": "https://Stackoverflow.com/users/107683",
"pm_score": 4,
"selected": false,
"text": "<p>Add the following attribute to your service class:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><ServiceBehavior(AddressFilterMode:=AddressFilterMode.Any)>\n</code></pre>\n<p>This allows the service to be addressed by the client as <code>https://...</code> but the service can still be hosted on <code>http://.....</code></p>\n<p>See my answer on <a href=\"https://stackoverflow.com/a/6878145/1366033\">How to specify AddressFilterMode.Any declaratively</a> for how to create an extension to allow <code>AddressFilterMode.Any </code>to be specified through configuration without requiring code attributes.</p>\n<p>In the <code>web.config</code> of the service host, the endpoint element <em>must have an absolute URL</em> in the address attribute that is the public URL that will be used by the client. In the same endpoint element, set the <code>listenUri</code> attribute to the absolute URL on which the service host is listening.</p>\n<p>The way I determine what the default absolute URI the host is listening on is to add a service reference in a client application which points the the physical server where the service is hosted. The web.config of the client will have an address for the service. I then copy that into the listenUri attribute in the hosts web.config.</p>\n<p>In your service behavior configuration, add the element <code>serviceMetaData</code> with attribute <code>httpGetEnabled=true</code></p>\n<p>So you'll have something like this:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><serviceBehaviors>\n <behavior name="myBehavior">\n <serviceMetadata httpGetEnabled="true" />\n </behavior>\n</serviceBehaviors>\n<!-- ... -->\n<services>\n <service name="NamespaceQualifiedServiceClass" behavior="myBehavior" >\n <endpoint listenUri="http://www.servicehost.com" \n address="https://www.sslloadbalancer.com" \n binding="someBinding" \n contract="IMyServiceInterface" ... />\n </service>\n</services>\n</code></pre>\n<p>I am not sure if this works with message security or transport security. For this particular application, the credentials were passed as part of the DataContract so we had <code>basicHttpBinding</code> > <code>security</code> > <code>mode=none</code>. Since the transport is secure (to the ssl load balancer) there were no security issues.</p>\n<p>It is also possible in to leave the listenUri attribute blank, however it must be present.</p>\n<p>Unfortunately, there is a bug in WCF where the the base address of imported schemas in the WSDL have the listenUri base address rather than the public base address (the one configured using the address attribute of the endpoint). To work around that issue, you need to create an IWsdlExportExtension implementation which brings the imported schemas into the WSDL document directly and removes the imports.</p>\n<p>An example of this is provided in this article on <a href=\"https://web.archive.org/web/20150315045205/http://winterdom.com/2006/10/inlinexsdinwsdlwithwcf\" rel=\"nofollow noreferrer\">Inline XSD in WSDL with WCF</a>. Additionally you can have the example class inherit from <code>BehaviorExtensionElement</code> and complete the two new methods with:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Overrides ReadOnly Property BehaviorType() As System.Type\n Get\n Return GetType(InlineXsdInWsdlBehavior)\n End Get\nEnd Property\n\nProtected Overrides Function CreateBehavior() As Object\n Return New InlineXsdInWsdlBehavior()\nEnd Function\n</code></pre>\n<p>This will allow you to add an extension behavior in the .config file and add the behavior using configuration rather than having to create a service factory.</p>\n<p>Under the <code>system.servicemodel</code> configuration element add:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><behaviors>\n <endpointBehaviors>\n <behavior name="SSLLoadBalancerBehavior"> \n <flattenXsdImports/>\n </behavior>\n </endpointBehaviors>\n</behaviors>\n<extensions>\n <behaviorExtensions>\n <!--The full assembly name must be specified in the type attribute as of WCF 3.5sp1-->\n <add name="flattenXsdImports" type="Org.ServiceModel.Description.FlattenXsdImportsEndpointBehavior, Org.ServiceModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> \n </behaviorExtensions>\n</extensions>\n</code></pre>\n<p>And then reference the new endpoint behavior in your endpoint configuration using the behaviorConfiguration attribute</p>\n<pre class=\"lang-xml prettyprint-override\"><code><endpoint address="" binding="basicHttpBinding" contract="WCFWsdlFlatten.IService1" behaviorConfiguration="SSLLoadBalancerBehavior">\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/274984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5970/"
] |
How can I correctly serve WSDL of a WCF webservice located in a private LAN from behind a reverse proxy listening on public IP?
I have an Apache webserver configured in reverse proxy mode which listens for requests on a public IP address and serves them from the internal IIS host. WCF webservice generates WSDL using the FQDN address of the LAN host which, of course, cannot be read by an internet web service client.
Is there any setting that can be configured in wcf application's web.config or in IIS in order to customize the WSDL generated containing host address and put public address instead?
|
Add the following attribute to your service class:
```xml
<ServiceBehavior(AddressFilterMode:=AddressFilterMode.Any)>
```
This allows the service to be addressed by the client as `https://...` but the service can still be hosted on `http://.....`
See my answer on [How to specify AddressFilterMode.Any declaratively](https://stackoverflow.com/a/6878145/1366033) for how to create an extension to allow `AddressFilterMode.Any` to be specified through configuration without requiring code attributes.
In the `web.config` of the service host, the endpoint element *must have an absolute URL* in the address attribute that is the public URL that will be used by the client. In the same endpoint element, set the `listenUri` attribute to the absolute URL on which the service host is listening.
The way I determine what the default absolute URI the host is listening on is to add a service reference in a client application which points the the physical server where the service is hosted. The web.config of the client will have an address for the service. I then copy that into the listenUri attribute in the hosts web.config.
In your service behavior configuration, add the element `serviceMetaData` with attribute `httpGetEnabled=true`
So you'll have something like this:
```xml
<serviceBehaviors>
<behavior name="myBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<!-- ... -->
<services>
<service name="NamespaceQualifiedServiceClass" behavior="myBehavior" >
<endpoint listenUri="http://www.servicehost.com"
address="https://www.sslloadbalancer.com"
binding="someBinding"
contract="IMyServiceInterface" ... />
</service>
</services>
```
I am not sure if this works with message security or transport security. For this particular application, the credentials were passed as part of the DataContract so we had `basicHttpBinding` > `security` > `mode=none`. Since the transport is secure (to the ssl load balancer) there were no security issues.
It is also possible in to leave the listenUri attribute blank, however it must be present.
Unfortunately, there is a bug in WCF where the the base address of imported schemas in the WSDL have the listenUri base address rather than the public base address (the one configured using the address attribute of the endpoint). To work around that issue, you need to create an IWsdlExportExtension implementation which brings the imported schemas into the WSDL document directly and removes the imports.
An example of this is provided in this article on [Inline XSD in WSDL with WCF](https://web.archive.org/web/20150315045205/http://winterdom.com/2006/10/inlinexsdinwsdlwithwcf). Additionally you can have the example class inherit from `BehaviorExtensionElement` and complete the two new methods with:
```vb
Public Overrides ReadOnly Property BehaviorType() As System.Type
Get
Return GetType(InlineXsdInWsdlBehavior)
End Get
End Property
Protected Overrides Function CreateBehavior() As Object
Return New InlineXsdInWsdlBehavior()
End Function
```
This will allow you to add an extension behavior in the .config file and add the behavior using configuration rather than having to create a service factory.
Under the `system.servicemodel` configuration element add:
```xml
<behaviors>
<endpointBehaviors>
<behavior name="SSLLoadBalancerBehavior">
<flattenXsdImports/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<!--The full assembly name must be specified in the type attribute as of WCF 3.5sp1-->
<add name="flattenXsdImports" type="Org.ServiceModel.Description.FlattenXsdImportsEndpointBehavior, Org.ServiceModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
```
And then reference the new endpoint behavior in your endpoint configuration using the behaviorConfiguration attribute
```xml
<endpoint address="" binding="basicHttpBinding" contract="WCFWsdlFlatten.IService1" behaviorConfiguration="SSLLoadBalancerBehavior">
```
|
275,004 |
<p>I wish to calculate the time it took for an API to return a value.
The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:</p>
<pre><code> #include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
clock_t start;
double diff;
start = clock();
diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
cout<<"printf: "<< diff <<'\n';
return 0;
}
</code></pre>
<p>The above code gives the time in seconds. How do I get the same in nano seconds and with more precision?</p>
|
[
{
"answer_id": 275012,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>In general, for timing how long it takes to call a function, you want to do it many more times than just once. If you call your function only once and it takes a very short time to run, you still have the overhead of actually calling the timer functions and you don't know how long that takes.</p>\n\n<p>For example, if you estimate your function might take 800 ns to run, call it in a loop ten million times (which will then take about 8 seconds). Divide the total time by ten million to get the time per call.</p>\n"
},
{
"answer_id": 275031,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "<p>With that level of accuracy, it would be better to reason in CPU tick rather than in system call <a href=\"http://mail.python.org/pipermail/python-list/2001-April/079815.html\" rel=\"noreferrer\">like clock()</a>. And do not forget that if it takes more than one nanosecond to execute an instruction... having a nanosecond accuracy is pretty much impossible.</p>\n\n<p>Still, <a href=\"http://coding.derkeiler.com/Archive/C_CPP/comp.lang.cpp/2004-03/1376.html\" rel=\"noreferrer\">something like that</a> is a start:</p>\n\n<p>Here's the actual code to retrieve number of 80x86 CPU clock ticks passed since the CPU was last started. It will work on Pentium and above (386/486 not supported). This code is actually MS Visual C++ specific, but can be probably very easy ported to whatever else, as long as it supports inline assembly.</p>\n\n<pre><code>inline __int64 GetCpuClocks()\n{\n\n // Counter\n struct { int32 low, high; } counter;\n\n // Use RDTSC instruction to get clocks count\n __asm push EAX\n __asm push EDX\n __asm __emit 0fh __asm __emit 031h // RDTSC\n __asm mov counter.low, EAX\n __asm mov counter.high, EDX\n __asm pop EDX\n __asm pop EAX\n\n // Return result\n return *(__int64 *)(&counter);\n\n}\n</code></pre>\n\n<p>This function has also the advantage of being extremely fast - it usually takes no more than 50 cpu cycles to execute. </p>\n\n<p><a href=\"http://www.devx.com/MicrosoftISV/Article/16293\" rel=\"noreferrer\">Using the Timing Figures</a>:<br>\nIf you need to translate the clock counts into true elapsed time, divide the results by your chip's clock speed. Remember that the \"rated\" GHz is likely to be slightly different from the actual speed of your chip. To check your chip's true speed, you can use several very good utilities or the Win32 call, QueryPerformanceFrequency().</p>\n"
},
{
"answer_id": 275045,
"author": "Raymond Martineau",
"author_id": 33952,
"author_profile": "https://Stackoverflow.com/users/33952",
"pm_score": 2,
"selected": false,
"text": "<p>If you need subsecond precision, you need to use system-specific extensions, and will have to check with the documentation for the operating system. POSIX supports up to microseconds with <a href=\"http://dell5.ma.utexas.edu/cgi-bin/man-cgi?gettimeofday+2\" rel=\"nofollow noreferrer\">gettimeofday</a>, but nothing more precise since computers didn't have frequencies above 1GHz.</p>\n\n<p>If you are using Boost, you can check <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/posix_time.html\" rel=\"nofollow noreferrer\">boost::posix_time</a>. </p>\n"
},
{
"answer_id": 275050,
"author": "Will Mc",
"author_id": 35378,
"author_profile": "https://Stackoverflow.com/users/35378",
"pm_score": 2,
"selected": false,
"text": "<p>If this is for Linux, I've been using the function \"gettimeofday\", which returns a struct that gives the seconds and microseconds since the Epoch. You can then use timersub to subtract the two to get the difference in time, and convert it to whatever precision of time you want. However, you specify nanoseconds, and it looks like the function <a href=\"http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html\" rel=\"nofollow noreferrer\">clock_gettime()</a> is what you're looking for. It puts the time in terms of seconds and nanoseconds into the structure you pass into it.</p>\n"
},
{
"answer_id": 275231,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 7,
"selected": true,
"text": "<p>What others have posted about running the function repeatedly in a loop is correct.</p>\n\n<p>For Linux (and BSD) you want to use <A href=\"http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html\" rel=\"noreferrer\">clock_gettime()</A>.</p>\n\n<pre><code>#include <sys/time.h>\n\nint main()\n{\n timespec ts;\n // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD\n clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux\n}\n</code></pre>\n\n<p>For windows you want to use the <A href=\"http://support.microsoft.com/kb/172338\" rel=\"noreferrer\">QueryPerformanceCounter</A>. And here is more on <A href=\"http://msdn.microsoft.com/en-us/library/ms979201.aspx\" rel=\"noreferrer\">QPC</A></p>\n\n<p>Apparently there is a known <A href=\"http://support.microsoft.com/kb/274323\" rel=\"noreferrer\">issue</A> with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a <A href=\"http://forum.beyond3d.com/showthread.php?t=47951\" rel=\"noreferrer\">problem</A>. See the second post by sebbbi, where he states:</p>\n\n<blockquote>\n <p>QueryPerformanceCounter() and\n QueryPerformanceFrequency() offer a\n bit better resolution, but have\n different issues. For example in\n Windows XP, all AMD Athlon X2 dual\n core CPUs return the PC of either of\n the cores \"randomly\" (the PC sometimes\n jumps a bit backwards), unless you\n specially install AMD dual core driver\n package to fix the issue. We haven't\n noticed any other dual+ core CPUs\n having similar issues (p4 dual, p4 ht,\n core2 dual, core2 quad, phenom quad).</p>\n</blockquote>\n\n<p><strong>EDIT 2013/07/16:</strong></p>\n\n<p>It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx</a></p>\n\n<blockquote>\n <p>...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for\n multiple processors, bugs in the BIOS or drivers may result in these routines returning\n different values as the thread moves from one processor to another...</p>\n</blockquote>\n\n<p>However this StackOverflow answer <a href=\"https://stackoverflow.com/a/4588605/34329\">https://stackoverflow.com/a/4588605/34329</a> states that QPC should work fine on any MS OS after Win XP service pack 2.</p>\n\n<p>This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. <a href=\"http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html\" rel=\"noreferrer\">http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html</a> Synchronizing across processors is still an issue.</p>\n\n<p>Other fine reading related to timers:</p>\n\n<ul>\n<li><a href=\"https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks\" rel=\"noreferrer\">https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks</a></li>\n<li><a href=\"http://lwn.net/Articles/209101/\" rel=\"noreferrer\">http://lwn.net/Articles/209101/</a></li>\n<li><a href=\"http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html\" rel=\"noreferrer\">http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html</a></li>\n<li><a href=\"https://stackoverflow.com/questions/7287663/queryperformancecounter-status\">QueryPerformanceCounter Status?</a></li>\n</ul>\n\n<p>See the comments for more details.</p>\n"
},
{
"answer_id": 275543,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the following function with gcc running under x86 processors:</p>\n\n<pre><code>unsigned long long rdtsc()\n{\n #define rdtsc(low, high) \\\n __asm__ __volatile__(\"rdtsc\" : \"=a\" (low), \"=d\" (high))\n\n unsigned int low, high;\n rdtsc(low, high);\n return ((ulonglong)high << 32) | low;\n}\n</code></pre>\n\n<p>with Digital Mars C++:</p>\n\n<pre><code>unsigned long long rdtsc()\n{\n _asm\n {\n rdtsc\n }\n}\n</code></pre>\n\n<p>which reads the high performance timer on the chip. I use this when doing profiling.</p>\n"
},
{
"answer_id": 283584,
"author": "gagneet",
"author_id": 35416,
"author_profile": "https://Stackoverflow.com/users/35416",
"pm_score": 5,
"selected": false,
"text": "<p>I am using the following to get the desired results:</p>\n\n<pre><code>#include <time.h>\n#include <iostream>\nusing namespace std;\n\nint main (int argc, char** argv)\n{\n // reset the clock\n timespec tS;\n tS.tv_sec = 0;\n tS.tv_nsec = 0;\n clock_settime(CLOCK_PROCESS_CPUTIME_ID, &tS);\n ...\n ... <code to check for the time to be put here>\n ...\n clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tS);\n cout << \"Time taken is: \" << tS.tv_sec << \" \" << tS.tv_nsec << endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 3205738,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 5,
"selected": false,
"text": "<p>To do this correctly you can use one of two ways, either go with <code>RDTSC</code> or with <code>clock_gettime()</code>.\nThe second is about 2 times faster and has the advantage of giving the right absolute time. Note that for <code>RDTSC</code> to work correctly you need to use it as indicated (other comments on this page have errors, and may yield incorrect timing values on certain processors)</p>\n\n<pre><code>inline uint64_t rdtsc()\n{\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\" );\n return (uint64_t)hi << 32 | lo;\n}\n</code></pre>\n\n<p>and for clock_gettime: (I chose microsecond resolution arbitrarily)</p>\n\n<pre><code>#include <time.h>\n#include <sys/timeb.h>\n// needs -lrt (real-time lib)\n// 1970-01-01 epoch UTC time, 1 mcs resolution (divide by 1M to get time_t)\nuint64_t ClockGetTime()\n{\n timespec ts;\n clock_gettime(CLOCK_REALTIME, &ts);\n return (uint64_t)ts.tv_sec * 1000000LL + (uint64_t)ts.tv_nsec / 1000LL;\n}\n</code></pre>\n\n<p>the timing and values produced:</p>\n\n<pre><code>Absolute values:\nrdtsc = 4571567254267600\nclock_gettime = 1278605535506855\n\nProcessing time: (10000000 runs)\nrdtsc = 2292547353\nclock_gettime = 1031119636\n</code></pre>\n"
},
{
"answer_id": 4720448,
"author": "Paul J Moesman",
"author_id": 579402,
"author_profile": "https://Stackoverflow.com/users/579402",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using Borland code here is the code ti_hund gives me some times a negativnumber but timing is fairly good.</p>\n\n<pre><code>#include <dos.h>\n\nvoid main() \n{\nstruct time t;\nint Hour,Min,Sec,Hun;\ngettime(&t);\nHour=t.ti_hour;\nMin=t.ti_min;\nSec=t.ti_sec;\nHun=t.ti_hund;\nprintf(\"Start time is: %2d:%02d:%02d.%02d\\n\",\n t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);\n....\nyour code to time\n...\n\n// read the time here remove Hours and min if the time is in sec\n\ngettime(&t);\nprintf(\"\\nTid Hour:%d Min:%d Sec:%d Hundreds:%d\\n\",t.ti_hour-Hour,\n t.ti_min-Min,t.ti_sec-Sec,t.ti_hund-Hun);\nprintf(\"\\n\\nAlt Ferdig Press a Key\\n\\n\");\ngetch();\n} // end main\n</code></pre>\n"
},
{
"answer_id": 11242363,
"author": "Thomas",
"author_id": 1392778,
"author_profile": "https://Stackoverflow.com/users/1392778",
"pm_score": 2,
"selected": false,
"text": "<p>Using Brock Adams's method, with a simple class:</p>\n\n<pre><code>int get_cpu_ticks()\n{\n LARGE_INTEGER ticks;\n QueryPerformanceFrequency(&ticks);\n return ticks.LowPart;\n}\n\n__int64 get_cpu_clocks()\n{\n struct { int32 low, high; } counter;\n\n __asm cpuid\n __asm push EDX\n __asm rdtsc\n __asm mov counter.low, EAX\n __asm mov counter.high, EDX\n __asm pop EDX\n __asm pop EAX\n\n return *(__int64 *)(&counter);\n}\n\nclass cbench\n{\npublic:\n cbench(const char *desc_in) \n : desc(strdup(desc_in)), start(get_cpu_clocks()) { }\n ~cbench()\n {\n printf(\"%s took: %.4f ms\\n\", desc, (float)(get_cpu_clocks()-start)/get_cpu_ticks());\n if(desc) free(desc);\n }\nprivate:\n char *desc;\n __int64 start;\n};\n</code></pre>\n\n<p>Usage Example:</p>\n\n<pre><code>int main()\n{\n {\n cbench c(\"test\");\n ... code ...\n }\n return 0;\n}\n</code></pre>\n\n<p>Result:</p>\n\n<p>test took: 0.0002 ms</p>\n\n<p>Has some function call overhead, but should be still more than fast enough :)</p>\n"
},
{
"answer_id": 11485388,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 6,
"selected": false,
"text": "<p>This new answer uses C++11's <code><chrono></code> facility. While there are other answers that show how to use <code><chrono></code>, none of them shows how to use <code><chrono></code> with the <code>RDTSC</code> facility mentioned in several of the other answers here. So I thought I would show how to use <code>RDTSC</code> with <code><chrono></code>. Additionally I'll demonstrate how you can templatize the testing code on the clock so that you can rapidly switch between <code>RDTSC</code> and your system's built-in clock facilities (which will likely be based on <code>clock()</code>, <code>clock_gettime()</code> and/or <code>QueryPerformanceCounter</code>.</p>\n\n<p>Note that the <code>RDTSC</code> instruction is x86-specific. <code>QueryPerformanceCounter</code> is Windows only. And <code>clock_gettime()</code> is POSIX only. Below I introduce two new clocks: <code>std::chrono::high_resolution_clock</code> and <code>std::chrono::system_clock</code>, which, if you can assume C++11, are now cross-platform.</p>\n\n<p>First, here is how you create a C++11-compatible clock out of the Intel <code>rdtsc</code> assembly instruction. I'll call it <code>x::clock</code>:</p>\n\n<pre><code>#include <chrono>\n\nnamespace x\n{\n\nstruct clock\n{\n typedef unsigned long long rep;\n typedef std::ratio<1, 2'800'000'000> period; // My machine is 2.8 GHz\n typedef std::chrono::duration<rep, period> duration;\n typedef std::chrono::time_point<clock> time_point;\n static const bool is_steady = true;\n\n static time_point now() noexcept\n {\n unsigned lo, hi;\n asm volatile(\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return time_point(duration(static_cast<rep>(hi) << 32 | lo));\n }\n};\n\n} // x\n</code></pre>\n\n<p>All this clock does is count CPU cycles and store it in an unsigned 64-bit integer. You may need to tweak the assembly language syntax for your compiler. Or your compiler may offer an intrinsic you can use instead (e.g. <code>now() {return __rdtsc();}</code>).</p>\n\n<p>To build a clock you have to give it the representation (storage type). You must also supply the clock period, which must be a compile time constant, even though your machine may change clock speed in different power modes. And from those you can easily define your clock's \"native\" time duration and time point in terms of these fundamentals.</p>\n\n<p>If all you want to do is output the number of clock ticks, it doesn't really matter what number you give for the clock period. This constant only comes into play if you want to convert the number of clock ticks into some real-time unit such as nanoseconds. And in that case, the more accurate you are able to supply the clock speed, the more accurate will be the conversion to nanoseconds, (milliseconds, whatever).</p>\n\n<p>Below is example code which shows how to use <code>x::clock</code>. Actually I've templated the code on the clock as I'd like to show how you can use many different clocks with the exact same syntax. This particular test is showing what the looping overhead is when running what you want to time under a loop:</p>\n\n<pre><code>#include <iostream>\n\ntemplate <class clock>\nvoid\ntest_empty_loop()\n{\n // Define real time units\n typedef std::chrono::duration<unsigned long long, std::pico> picoseconds;\n // or:\n // typedef std::chrono::nanoseconds nanoseconds;\n // Define double-based unit of clock tick\n typedef std::chrono::duration<double, typename clock::period> Cycle;\n using std::chrono::duration_cast;\n const int N = 100000000;\n // Do it\n auto t0 = clock::now();\n for (int j = 0; j < N; ++j)\n asm volatile(\"\");\n auto t1 = clock::now();\n // Get the clock ticks per iteration\n auto ticks_per_iter = Cycle(t1-t0)/N;\n std::cout << ticks_per_iter.count() << \" clock ticks per iteration\\n\";\n // Convert to real time units\n std::cout << duration_cast<picoseconds>(ticks_per_iter).count()\n << \"ps per iteration\\n\";\n}\n</code></pre>\n\n<p>The first thing this code does is create a \"real time\" unit to display the results in. I've chosen picoseconds, but you can choose any units you like, either integral or floating point based. As an example there is a pre-made <code>std::chrono::nanoseconds</code> unit I could have used.</p>\n\n<p>As another example I want to print out the average number of clock cycles per iteration as a floating point, so I create another duration, based on double, that has the same units as the clock's tick does (called <code>Cycle</code> in the code).</p>\n\n<p>The loop is timed with calls to <code>clock::now()</code> on either side. If you want to name the type returned from this function it is:</p>\n\n<pre><code>typename clock::time_point t0 = clock::now();\n</code></pre>\n\n<p>(as clearly shown in the <code>x::clock</code> example, and is also true of the system-supplied clocks).</p>\n\n<p>To get a duration in terms of floating point clock ticks one merely subtracts the two time points, and to get the per iteration value, divide that duration by the number of iterations.</p>\n\n<p>You can get the count in any duration by using the <code>count()</code> member function. This returns the internal representation. Finally I use <code>std::chrono::duration_cast</code> to convert the duration <code>Cycle</code> to the duration <code>picoseconds</code> and print that out.</p>\n\n<p>To use this code is simple:</p>\n\n<pre><code>int main()\n{\n std::cout << \"\\nUsing rdtsc:\\n\";\n test_empty_loop<x::clock>();\n\n std::cout << \"\\nUsing std::chrono::high_resolution_clock:\\n\";\n test_empty_loop<std::chrono::high_resolution_clock>();\n\n std::cout << \"\\nUsing std::chrono::system_clock:\\n\";\n test_empty_loop<std::chrono::system_clock>();\n}\n</code></pre>\n\n<p>Above I exercise the test using our home-made <code>x::clock</code>, and compare those results with using two of the system-supplied clocks: <code>std::chrono::high_resolution_clock</code> and <code>std::chrono::system_clock</code>. For me this prints out:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Using rdtsc:\n1.72632 clock ticks per iteration\n616ps per iteration\n\nUsing std::chrono::high_resolution_clock:\n0.620105 clock ticks per iteration\n620ps per iteration\n\nUsing std::chrono::system_clock:\n0.00062457 clock ticks per iteration\n624ps per iteration\n</code></pre>\n\n<p>This shows that each of these clocks has a different tick period, as the ticks per iteration is vastly different for each clock. However when converted to a known unit of time (e.g. picoseconds), I get approximately the same result for each clock (your mileage may vary).</p>\n\n<p>Note how my code is completely free of \"magic conversion constants\". Indeed, there are only two magic numbers in the entire example:</p>\n\n<ol>\n<li>The clock speed of my machine in order to define <code>x::clock</code>.</li>\n<li>The number of iterations to test over. If changing this number makes your results vary greatly, then you should probably make the number of iterations higher, or empty your computer of competing processes while testing.</li>\n</ol>\n"
},
{
"answer_id": 12176835,
"author": "ice",
"author_id": 1482174,
"author_profile": "https://Stackoverflow.com/users/1482174",
"pm_score": 2,
"selected": false,
"text": "<p>What do you think about that:</p>\n\n<pre><code> int iceu_system_GetTimeNow(long long int *res)\n {\n static struct timespec buffer;\n // \n #ifdef __CYGWIN__\n if (clock_gettime(CLOCK_REALTIME, &buffer))\n return 1;\n #else\n if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &buffer))\n return 1;\n #endif\n *res=(long long int)buffer.tv_sec * 1000000000LL + (long long int)buffer.tv_nsec;\n return 0;\n }\n</code></pre>\n"
},
{
"answer_id": 13305395,
"author": "Mi-La",
"author_id": 1809845,
"author_profile": "https://Stackoverflow.com/users/1809845",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <em>Embedded Profiler</em> (free for Windows and Linux) which has an interface to a multiplatform timer (in a processor cycle count) and can give you a number of cycles per seconds:</p>\n\n<pre><code>EProfilerTimer timer;\ntimer.Start();\n\n... // Your code here\n\nconst uint64_t number_of_elapsed_cycles = timer.Stop();\nconst uint64_t nano_seconds_elapsed =\n mumber_of_elapsed_cycles / (double) timer.GetCyclesPerSecond() * 1000000000;\n</code></pre>\n\n<p>Recalculation of cycle count to time is possibly a dangerous operation with modern processors where CPU frequency can be changed dynamically. Therefore to be sure that converted times are correct, it is necessary to fix processor frequency before profiling.</p>\n"
},
{
"answer_id": 19471677,
"author": "gongzhitaao",
"author_id": 1429714,
"author_profile": "https://Stackoverflow.com/users/1429714",
"pm_score": 3,
"selected": false,
"text": "<p>For <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow\">C++11</a>, here is a simple wrapper:</p>\n\n<pre><code>#include <iostream>\n#include <chrono>\n\nclass Timer\n{\npublic:\n Timer() : beg_(clock_::now()) {}\n void reset() { beg_ = clock_::now(); }\n double elapsed() const {\n return std::chrono::duration_cast<second_>\n (clock_::now() - beg_).count(); }\n\nprivate:\n typedef std::chrono::high_resolution_clock clock_;\n typedef std::chrono::duration<double, std::ratio<1> > second_;\n std::chrono::time_point<clock_> beg_;\n};\n</code></pre>\n\n<p>Or for C++03 on *nix,</p>\n\n<pre><code>class Timer\n{\npublic:\n Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }\n\n double elapsed() {\n clock_gettime(CLOCK_REALTIME, &end_);\n return end_.tv_sec - beg_.tv_sec +\n (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;\n }\n\n void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }\n\nprivate:\n timespec beg_, end_;\n};\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code>int main()\n{\n Timer tmr;\n double t = tmr.elapsed();\n std::cout << t << std::endl;\n\n tmr.reset();\n t = tmr.elapsed();\n std::cout << t << std::endl;\n return 0;\n}\n</code></pre>\n\n<p>From <a href=\"https://gist.github.com/gongzhitaao/7062087\" rel=\"nofollow\">https://gist.github.com/gongzhitaao/7062087</a></p>\n"
},
{
"answer_id": 23260069,
"author": "Patrick K",
"author_id": 3212800,
"author_profile": "https://Stackoverflow.com/users/3212800",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a nice <a href=\"http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"nofollow\">Boost</a> timer that works well:</p>\n\n<pre><code>//Stopwatch.hpp\n\n#ifndef STOPWATCH_HPP\n#define STOPWATCH_HPP\n\n//Boost\n#include <boost/chrono.hpp>\n//Std\n#include <cstdint>\n\nclass Stopwatch\n{\npublic:\n Stopwatch();\n virtual ~Stopwatch();\n void Restart();\n std::uint64_t Get_elapsed_ns();\n std::uint64_t Get_elapsed_us();\n std::uint64_t Get_elapsed_ms();\n std::uint64_t Get_elapsed_s();\nprivate:\n boost::chrono::high_resolution_clock::time_point _start_time;\n};\n\n#endif // STOPWATCH_HPP\n\n\n//Stopwatch.cpp\n\n#include \"Stopwatch.hpp\"\n\nStopwatch::Stopwatch():\n _start_time(boost::chrono::high_resolution_clock::now()) {}\n\nStopwatch::~Stopwatch() {}\n\nvoid Stopwatch::Restart()\n{\n _start_time = boost::chrono::high_resolution_clock::now();\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_ns()\n{\n boost::chrono::nanoseconds nano_s = boost::chrono::duration_cast<boost::chrono::nanoseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(nano_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_us()\n{\n boost::chrono::microseconds micro_s = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(micro_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_ms()\n{\n boost::chrono::milliseconds milli_s = boost::chrono::duration_cast<boost::chrono::milliseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(milli_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_s()\n{\n boost::chrono::seconds sec = boost::chrono::duration_cast<boost::chrono::seconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(sec.count());\n}\n</code></pre>\n"
},
{
"answer_id": 35312966,
"author": "Yeti",
"author_id": 1009901,
"author_profile": "https://Stackoverflow.com/users/1009901",
"pm_score": 2,
"selected": false,
"text": "<h1>Minimalistic copy&paste-struct + lazy usage</h1>\n\n<p>If the idea is to have a minimalistic struct that you can use for quick tests, then I suggest you just <strong>copy and paste</strong> anywhere in your C++ file right after the <code>#include</code>'s. This is the only instance in which I sacrifice Allman-style formatting.</p>\n\n<p>You can easily adjust the precision in the first line of the struct. Possible values are: <code>nanoseconds</code>, <code>microseconds</code>, <code>milliseconds</code>, <code>seconds</code>, <code>minutes</code>, or <code>hours</code>.</p>\n\n<pre><code>#include <chrono>\nstruct MeasureTime\n{\n using precision = std::chrono::microseconds;\n std::vector<std::chrono::steady_clock::time_point> times;\n std::chrono::steady_clock::time_point oneLast;\n void p() {\n std::cout << \"Mark \" \n << times.size()/2\n << \": \" \n << std::chrono::duration_cast<precision>(times.back() - oneLast).count() \n << std::endl;\n }\n void m() {\n oneLast = times.back();\n times.push_back(std::chrono::steady_clock::now());\n }\n void t() {\n m();\n p();\n m();\n }\n MeasureTime() {\n times.push_back(std::chrono::steady_clock::now());\n }\n};\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>MeasureTime m; // first time is already in memory\ndoFnc1();\nm.t(); // Mark 1: next time, and print difference with previous mark\ndoFnc2();\nm.t(); // Mark 2: next time, and print difference with previous mark\ndoStuff = doMoreStuff();\nandDoItAgain = doStuff.aoeuaoeu();\nm.t(); // prints 'Mark 3: 123123' etc...\n</code></pre>\n\n<h2>Standard output result</h2>\n\n<pre><code>Mark 1: 123\nMark 2: 32\nMark 3: 433234\n</code></pre>\n\n<h1>If you want summary after execution</h1>\n\n<p>If you want the report afterwards, because for example your code in between also writes to standard output. Then add the following function to the struct (just before MeasureTime()):</p>\n\n<pre><code>void s() { // summary\n int i = 0;\n std::chrono::steady_clock::time_point tprev;\n for(auto tcur : times)\n {\n if(i > 0)\n {\n std::cout << \"Mark \" << i << \": \"\n << std::chrono::duration_cast<precision>(tprev - tcur).count()\n << std::endl;\n }\n tprev = tcur;\n ++i;\n }\n}\n</code></pre>\n\n<p>So then you can just use:</p>\n\n<pre><code>MeasureTime m;\ndoFnc1();\nm.m();\ndoFnc2();\nm.m();\ndoStuff = doMoreStuff();\nandDoItAgain = doStuff.aoeuaoeu();\nm.m();\nm.s();\n</code></pre>\n\n<p>Which will list all the marks just like before, but then after the other code is executed. Note that you shouldn't use both <code>m.s()</code> and <code>m.t()</code>.</p>\n"
},
{
"answer_id": 65118386,
"author": "metamorphosis",
"author_id": 3454889,
"author_profile": "https://Stackoverflow.com/users/3454889",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://plflib.org/nanotimer.htm\" rel=\"nofollow noreferrer\">plf::nanotimer</a> is a lightweight option for this, works in Windows, Linux, Mac and BSD etc. Has ~microsecond accuracy depending on OS:</p>\n<pre><code> #include "plf_nanotimer.h"\n #include <iostream>\n\n int main(int argc, char** argv)\n {\n plf::nanotimer timer;\n\n timer.start()\n\n // Do something here\n\n double results = timer.get_elapsed_ns();\n std::cout << "Timing: " << results << " nanoseconds." << std::endl; \n return 0;\n }\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
I wish to calculate the time it took for an API to return a value.
The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:
```
#include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
clock_t start;
double diff;
start = clock();
diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
cout<<"printf: "<< diff <<'\n';
return 0;
}
```
The above code gives the time in seconds. How do I get the same in nano seconds and with more precision?
|
What others have posted about running the function repeatedly in a loop is correct.
For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html).
```
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
```
For windows you want to use the [QueryPerformanceCounter](http://support.microsoft.com/kb/172338). And here is more on [QPC](http://msdn.microsoft.com/en-us/library/ms979201.aspx)
Apparently there is a known [issue](http://support.microsoft.com/kb/274323) with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a [problem](http://forum.beyond3d.com/showthread.php?t=47951). See the second post by sebbbi, where he states:
>
> QueryPerformanceCounter() and
> QueryPerformanceFrequency() offer a
> bit better resolution, but have
> different issues. For example in
> Windows XP, all AMD Athlon X2 dual
> core CPUs return the PC of either of
> the cores "randomly" (the PC sometimes
> jumps a bit backwards), unless you
> specially install AMD dual core driver
> package to fix the issue. We haven't
> noticed any other dual+ core CPUs
> having similar issues (p4 dual, p4 ht,
> core2 dual, core2 quad, phenom quad).
>
>
>
**EDIT 2013/07/16:**
It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in <http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx>
>
> ...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for
> multiple processors, bugs in the BIOS or drivers may result in these routines returning
> different values as the thread moves from one processor to another...
>
>
>
However this StackOverflow answer <https://stackoverflow.com/a/4588605/34329> states that QPC should work fine on any MS OS after Win XP service pack 2.
This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. <http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html> Synchronizing across processors is still an issue.
Other fine reading related to timers:
* <https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks>
* <http://lwn.net/Articles/209101/>
* <http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html>
* [QueryPerformanceCounter Status?](https://stackoverflow.com/questions/7287663/queryperformancecounter-status)
See the comments for more details.
|
275,005 |
<p>I am writing a program that will draw a solid along the curve of a spline. I am using visual studio 2005, and writing in C++ for OpenGL. I'm using FLTK to open my windows (fast and light toolkit).</p>
<p>I currently have an algorithm that will draw a Cardinal Cubic Spline, given a set of control points, by breaking the intervals between the points up into subintervals and drawing linesegments between these sub points. The number of subintervals is variable.</p>
<p>The line drawing code works wonderfully, and basically works as follows: I generate a set of points along the spline curve using the spline equation and store them in an array (as a special datastructure called Pnt3f, where the coordinates are 3 floats and there are some handy functions such as distance, length, dot and crossproduct). Then i have a single loop that iterates through the array of points and draws them as so:</p>
<pre><code>glBegin(GL_LINE_STRIP);
for(pt = 0; pt<=numsubsegements ; ++pt) {
glVertex3fv(pt.v());
}
glEnd();
</code></pre>
<p>As stated, this code works great. Now what i want to do is, instead of drawing a line, I want to extrude a solid. My current exploration is using a 'cylinder' quadric to create a tube along the line. This is a bit trickier, as I have to orient openGL in the direction i want to draw the cylinder. My idea is to do this:</p>
<p>Psuedocode:</p>
<pre><code>Push the current matrix,
translate to the first control point
rotate to face the next point
draw a cylinder (length = distance between the points)
Pop the matrix
repeat
</code></pre>
<p>My problem is getting the angles between the points. I only need yaw and pitch, roll isnt important. I know take the arc-cosine of the dot product of the two points divided by the magnitude of both points, will return the angle between them, but this is not something i can feed to OpenGL to rotate with. I've tried doing this in 2d, using the XZ plane to get x rotation, and making the points vectors from the origin, but it does not return the correct angle.</p>
<p>My current approach is much simpler. For each plane of rotation (X and Y), find the angle by:</p>
<p>arc-cosine( (difference in 'x' values)/distance between the points)</p>
<p>the 'x' value depends on how your set your plane up, though for my calculations I always use world x.</p>
<p>Barring a few issues of it making it draw in the correct quadrant that I havent worked out yet, I want to get advice to see if this was a good implementation, or to see if someone knew a better way.</p>
|
[
{
"answer_id": 275040,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered <a href=\"http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/glu/lookat.html\" rel=\"nofollow noreferrer\"><code>gluLookAt</code></a>? Put your control point as the eye point, the next point as the reference point, and make the up vector perpendicular to the difference between the two.</p>\n"
},
{
"answer_id": 275152,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>A few notes:<br>\nfirst of all, this:</p>\n\n<pre><code>for(pt = 0; pt<=numsubsegements ; ++pt) {\n glBegin(GL_LINE_STRIP);\n glVertex3fv(pt.v());\n}\nglEnd();\n</code></pre>\n\n<p>is not a good way to draw anything. You MUST have one glEnd() for every single glBegin(). you probably want to get the glBegin() out of the loop. the fact that this works is pure luck.</p>\n\n<p>second thing </p>\n\n<blockquote>\n <p>My current exploration is using a\n 'cylinder' quadric to create a tube\n along the line</p>\n</blockquote>\n\n<p><strong>This will not work as you expect.</strong> the 'cylinder' quadric has a flat top base and a flat bottom base. Even if you success in making the correct rotations according to the spline the edges of the flat tops are going to pop out of the volume of your intended tube and it will not be smooth. You can try it in 2D with just a pen and a paper. Try to draw a smooth tube using only shorter tubes with a flat bases. This is impossible.</p>\n\n<p>Third, to your actual question, The definitive tool for such rotations are <a href=\"http://en.wikipedia.org/wiki/Quaternions\" rel=\"nofollow noreferrer\">quaternions</a>. Its a bit complex to explain in this scope but you can find plentyful information anywhere you look.<br>\nIf you'd have used QT instead of FLTK you could have also used <a href=\"http://www.libqglviewer.com/\" rel=\"nofollow noreferrer\">libQGLViewer</a>. It has an integrated Quaternion class which would save you the implementation. If you still have a choice I strongly recommend moving to QT. </p>\n"
},
{
"answer_id": 284931,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 2,
"selected": true,
"text": "<p>You are correct in forming two vectors from the three points in two adjacent line segments and then using the arccosine of the dot product to get the angle between them. To make use of this angle you need to determine the axis around which the rotation should occur. Take the cross product of the same two vectors to get this axis. You can then <a href=\"http://web.archive.org/web/20041029003853/http:/www.j3d.org/matrix_faq/matrfaq_latest.html#Q38\" rel=\"nofollow noreferrer\">build a transformation matrix</a> using this axis-angle or pass it as parameters to <a href=\"http://www.opengl.org/sdk/docs/man/xhtml/glRotate.xml\" rel=\"nofollow noreferrer\">glRotate</a>.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33583/"
] |
I am writing a program that will draw a solid along the curve of a spline. I am using visual studio 2005, and writing in C++ for OpenGL. I'm using FLTK to open my windows (fast and light toolkit).
I currently have an algorithm that will draw a Cardinal Cubic Spline, given a set of control points, by breaking the intervals between the points up into subintervals and drawing linesegments between these sub points. The number of subintervals is variable.
The line drawing code works wonderfully, and basically works as follows: I generate a set of points along the spline curve using the spline equation and store them in an array (as a special datastructure called Pnt3f, where the coordinates are 3 floats and there are some handy functions such as distance, length, dot and crossproduct). Then i have a single loop that iterates through the array of points and draws them as so:
```
glBegin(GL_LINE_STRIP);
for(pt = 0; pt<=numsubsegements ; ++pt) {
glVertex3fv(pt.v());
}
glEnd();
```
As stated, this code works great. Now what i want to do is, instead of drawing a line, I want to extrude a solid. My current exploration is using a 'cylinder' quadric to create a tube along the line. This is a bit trickier, as I have to orient openGL in the direction i want to draw the cylinder. My idea is to do this:
Psuedocode:
```
Push the current matrix,
translate to the first control point
rotate to face the next point
draw a cylinder (length = distance between the points)
Pop the matrix
repeat
```
My problem is getting the angles between the points. I only need yaw and pitch, roll isnt important. I know take the arc-cosine of the dot product of the two points divided by the magnitude of both points, will return the angle between them, but this is not something i can feed to OpenGL to rotate with. I've tried doing this in 2d, using the XZ plane to get x rotation, and making the points vectors from the origin, but it does not return the correct angle.
My current approach is much simpler. For each plane of rotation (X and Y), find the angle by:
arc-cosine( (difference in 'x' values)/distance between the points)
the 'x' value depends on how your set your plane up, though for my calculations I always use world x.
Barring a few issues of it making it draw in the correct quadrant that I havent worked out yet, I want to get advice to see if this was a good implementation, or to see if someone knew a better way.
|
You are correct in forming two vectors from the three points in two adjacent line segments and then using the arccosine of the dot product to get the angle between them. To make use of this angle you need to determine the axis around which the rotation should occur. Take the cross product of the same two vectors to get this axis. You can then [build a transformation matrix](http://web.archive.org/web/20041029003853/http:/www.j3d.org/matrix_faq/matrfaq_latest.html#Q38) using this axis-angle or pass it as parameters to [glRotate](http://www.opengl.org/sdk/docs/man/xhtml/glRotate.xml).
|
275,011 |
<p>I am having a problem displaying a Javascript string with embedded Unicode character escape sequences (\uXXXX) where the initial "\" character is itself escaped as "&#92;"
What do I need to do to transform the string so that it properly evaluates the escape sequences and produces output with the correct Unicode character?</p>
<p>For example, I am dealing with input such as:</p>
<p><pre><code>"this is a &#92;u201ctest&#92;u201d";</code></pre></p>
<p>attempting to decode the "&#92;" using a regex expression, e.g.:</p>
<p><pre><code>var out = text.replace('/&#92;/g','\');</code></pre></p>
<p>results in the output text:</p>
<p><pre><code>"this is a \u201ctest\u201d";</code></pre></p>
<p>that is, the Unicode escape sequences are displayed as actual escape sequences, not the double quote characters I would like.</p>
|
[
{
"answer_id": 275021,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if this is it, but the answer might have something to do with eval(), if you can trust your input.</p>\n"
},
{
"answer_id": 275032,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I was thinking along the same lines, but using eval() in everyway I could imagine resulted in the same escaped output; e.g.,</p>\n\n<pre><code>eval(new String(\"this is a &#92;u201ctest&#amp;92;u201d\"));</code></pre>\n\n<p>or even</p>\n\n<pre><code>eval(new String(\"this is a &#92;u201ctest&#amp;92;u201d\".replace('/&#92;/g','\\')));</code></pre>\n\n<p>all results in the same thing:</p>\n\n<pre><code>\"this is a \\u201ctest\\u201d\";</code></pre>\n\n<p>It's as if I need to get the Javascript engine to somehow re-evaluate or re-parse the string, but I don't know what would do it. I thought perhaps eval() or just creating a new string from using the properly escaped input would do it, but now luck.</p>\n\n<p>The fundamental question is - what do I have to do to turn the given string:</p>\n\n<pre><code>\"this is a &#92;u201ctest&#amp;92;u201d\"</code></pre>\n\n<p>into a string that uses the proper Unicode characters?</p>\n"
},
{
"answer_id": 275055,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 3,
"selected": false,
"text": "<p>As it turns out, it's unescape() we want, but with '%uXXXX' rather than '\\uXXXX':</p>\n\n<p>unescape(yourteststringhere.replace(/&#92;/g,'%'))</p>\n"
},
{
"answer_id": 275057,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 1,
"selected": false,
"text": "<p>This is a terrible solution, but you can do this:</p>\n\n<pre><code>var x = \"this is a &#92;u201ctest&#92;u201d\".replace(/&#92;/g,'\\\\')\n// x is now \"this is a \\u201ctest\\u201d\"\neval('x = \"' + x + '\"')\n// x is now \"this is a “test”\"\n</code></pre>\n\n<p>It's terrible because:</p>\n\n<ul>\n<li><p>eval can be dangerous, if you don't know what's in the string</p></li>\n<li><p>the string quoting in the eval statement will break if you have actual quotation marks in your string</p></li>\n</ul>\n"
},
{
"answer_id": 275518,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure '\\' is the only character that might get HTML-escaped? Are you sure '\\uXXXX' is the only kind of string escape in use?</p>\n\n<p>If not, you'll need a general-purpose HTML-character/entity-reference-decoder and JS-string-literal-decoder. Unfortunately JavaScript has no built-in methods for this and it's quite tedious to do manually with a load of regexps.</p>\n\n<p>It is possible to take advantage of the browser's HTML-decoder by assigning the string to an element's innerHTML property, and then ask JavaScript to decode the string as above:</p>\n\n<pre><code>var el= document.createElement('div');\nel.innerHTML= s;\nreturn eval('\"'+el.firstChild.data+'\"');\n</code></pre>\n\n<p>However this is an incredibly ugly hack and a security hole if the string comes from a source that isn't 100% trusted.</p>\n\n<p>Where are the strings coming from? It would be nicer if possible to deal with the problem at the server end where you may have more powerful text handling features available. And if you could fix whatever it is that is unnecessarily HTML-escaping your backslashes you could find the problem fixes itself.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am having a problem displaying a Javascript string with embedded Unicode character escape sequences (\uXXXX) where the initial "\" character is itself escaped as "\"
What do I need to do to transform the string so that it properly evaluates the escape sequences and produces output with the correct Unicode character?
For example, I am dealing with input such as:
```
"this is a \u201ctest\u201d";
```
attempting to decode the "\" using a regex expression, e.g.:
```
var out = text.replace('/\/g','\');
```
results in the output text:
```
"this is a \u201ctest\u201d";
```
that is, the Unicode escape sequences are displayed as actual escape sequences, not the double quote characters I would like.
|
As it turns out, it's unescape() we want, but with '%uXXXX' rather than '\uXXXX':
unescape(yourteststringhere.replace(/\/g,'%'))
|
275,018 |
<p>How do I remove the last character of a string if it is a newline?</p>
<pre><code>"abc\n" --> "abc"
</code></pre>
|
[
{
"answer_id": 275025,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 11,
"selected": false,
"text": "<p>Try the method <code>rstrip()</code> (see doc <a href=\"http://docs.python.org/2/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">Python 2</a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">Python 3</a>)</p>\n<pre><code>>>> 'test string\\n'.rstrip()\n'test string'\n</code></pre>\n<p>Python's <code>rstrip()</code> method strips <em>all</em> kinds of trailing whitespace by default, not just one newline as Perl does with <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\"><code>chomp</code></a>.</p>\n<pre><code>>>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip()\n'test string'\n</code></pre>\n<p>To strip only newlines:</p>\n<pre><code>>>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip('\\n')\n'test string \\n \\r\\n\\n\\r '\n</code></pre>\n<p>In addition to <code>rstrip()</code>, there are also the methods <code>strip()</code> and <code>lstrip()</code>. Here is an example with the three of them:</p>\n<pre><code>>>> s = " \\n\\r\\n \\n abc def \\n\\r\\n \\n "\n>>> s.strip()\n'abc def'\n>>> s.lstrip()\n'abc def \\n\\r\\n \\n '\n>>> s.rstrip()\n' \\n\\r\\n \\n abc def'\n</code></pre>\n"
},
{
"answer_id": 275401,
"author": "Mike",
"author_id": 19215,
"author_profile": "https://Stackoverflow.com/users/19215",
"pm_score": 7,
"selected": false,
"text": "<p>The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \\r or \\n. Here are examples for Mac, Windows, and Unix EOL characters.</p>\n\n<pre><code>>>> 'Mac EOL\\r'.rstrip('\\r\\n')\n'Mac EOL'\n>>> 'Windows EOL\\r\\n'.rstrip('\\r\\n')\n'Windows EOL'\n>>> 'Unix EOL\\n'.rstrip('\\r\\n')\n'Unix EOL'\n</code></pre>\n\n<p>Using '\\r\\n' as the parameter to rstrip means that it will strip out any trailing combination of '\\r' or '\\n'. That's why it works in all three cases above.</p>\n\n<p>This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing '\\r' as its EOL character. The Windows machine on which I was using this message had appended its own '\\r\\n' EOL character. Therefore, the end of each line looked like '\\r\\r\\n'. Using rstrip('\\r\\n') would have taken off the entire '\\r\\r\\n' which is not what I wanted. In that case, I simply sliced off the last two characters instead.</p>\n\n<p>Note that unlike Perl's <code>chomp</code> function, this will strip all specified characters at the end of the string, not just one:</p>\n\n<pre><code>>>> \"Hello\\n\\n\\n\".rstrip(\"\\n\")\n\"Hello\"\n</code></pre>\n"
},
{
"answer_id": 275659,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 8,
"selected": false,
"text": "<p>And I would say the \"pythonic\" way to get lines without trailing newline characters is splitlines().</p>\n\n<pre><code>>>> text = \"line 1\\nline 2\\r\\nline 3\\nline 4\"\n>>> text.splitlines()\n['line 1', 'line 2', 'line 3', 'line 4']\n</code></pre>\n"
},
{
"answer_id": 326279,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:</p>\n\n<pre><code>$x=\"a\\n\";\n\nchomp $x\n</code></pre>\n\n<p>results in <code>$x</code> being <code>\"a\"</code>.</p>\n\n<p>but in Python:</p>\n\n<pre><code>x=\"a\\n\"\n\nx.rstrip()\n</code></pre>\n\n<p>will mean that the value of <code>x</code> is <strong>still</strong> <code>\"a\\n\"</code>. Even <code>x=x.rstrip()</code> doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.</p>\n"
},
{
"answer_id": 1077495,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 4,
"selected": false,
"text": "<p>I don't program in Python, but I came across an <a href=\"http://www.python.org/doc/faq/programming/#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings\" rel=\"nofollow noreferrer\">FAQ</a> at python.org advocating S.rstrip(\"\\r\\n\") for python 2.2 or later.</p>\n"
},
{
"answer_id": 2396894,
"author": "Jamie",
"author_id": 288263,
"author_profile": "https://Stackoverflow.com/users/288263",
"pm_score": 6,
"selected": false,
"text": "<p>I might use something like this:</p>\n\n<pre><code>import os\ns = s.rstrip(os.linesep)\n</code></pre>\n\n<p>I think the problem with <code>rstrip(\"\\n\")</code> is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use <code>\"\\r\\n\"</code>). The other gotcha is that <code>rstrip</code> will strip out repeated whitespace. Hopefully <code>os.linesep</code> will contain the right characters. the above works for me.</p>\n"
},
{
"answer_id": 5764202,
"author": "ingydotnet",
"author_id": 721703,
"author_profile": "https://Stackoverflow.com/users/721703",
"pm_score": 4,
"selected": false,
"text": "<p>rstrip doesn't do the same thing as chomp, on so many levels. Read <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\">http://perldoc.perl.org/functions/chomp.html</a> and see that chomp is very complex indeed.</p>\n\n<p>However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.</p>\n\n<p>Here you can see rstrip removing all the newlines:</p>\n\n<pre><code>>>> 'foo\\n\\n'.rstrip(os.linesep)\n'foo'\n</code></pre>\n\n<p>A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:</p>\n\n<pre><code>>>> re.sub(os.linesep + r'\\Z','','foo\\n\\n')\n'foo\\n'\n</code></pre>\n"
},
{
"answer_id": 5803510,
"author": "Carlos Valiente",
"author_id": 179149,
"author_profile": "https://Stackoverflow.com/users/179149",
"pm_score": 4,
"selected": false,
"text": "<p>Careful with <code>\"foo\".rstrip(os.linesep)</code>: That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:</p>\n\n<pre><code>$ python\nPython 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) \n[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os, sys\n>>> sys.platform\n'linux2'\n>>> \"foo\\r\\n\".rstrip(os.linesep)\n'foo\\r'\n>>>\n</code></pre>\n\n<p>Use <code>\"foo\".rstrip(\"\\r\\n\")</code> instead, as Mike says above.</p>\n"
},
{
"answer_id": 8327143,
"author": "Chij",
"author_id": 1073506,
"author_profile": "https://Stackoverflow.com/users/1073506",
"pm_score": 3,
"selected": false,
"text": "<p>workaround solution for special case:</p>\n\n<p>if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows: </p>\n\n<pre><code>foobar= foobar[:-1]\n</code></pre>\n\n<p>to slice out your newline character. </p>\n"
},
{
"answer_id": 9507807,
"author": "mihaicc",
"author_id": 648904,
"author_profile": "https://Stackoverflow.com/users/648904",
"pm_score": 5,
"selected": false,
"text": "<pre><code>"line 1\\nline 2\\r\\n...".replace('\\n', '').replace('\\r', '')\n>>> 'line 1line 2...'\n</code></pre>\n<p>or you could always get geekier with regexps</p>\n"
},
{
"answer_id": 16527062,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 5,
"selected": false,
"text": "<p>You may use <code>line = line.rstrip('\\n')</code>. This will strip all newlines from the end of the string, not just one.</p>\n"
},
{
"answer_id": 19317570,
"author": "Leozj",
"author_id": 2870855,
"author_profile": "https://Stackoverflow.com/users/2870855",
"pm_score": 3,
"selected": false,
"text": "<p>If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\\n' and then join this list into a new str(newstr).</p>\n\n<p><code>newstr = \"\".join(oldstr.split('\\n'))</code> </p>\n"
},
{
"answer_id": 19531239,
"author": "minopret",
"author_id": 931925,
"author_profile": "https://Stackoverflow.com/users/931925",
"pm_score": 4,
"selected": false,
"text": "<p>An <a href=\"http://docs.python.org/2/library/stdtypes.html#file.next\" rel=\"noreferrer\">example in Python's documentation</a> simply uses <code>line.strip()</code>.</p>\n\n<p>Perl's <code>chomp</code> function removes one linebreak sequence from the end of a string only if it's actually there.</p>\n\n<p>Here is how I plan to do that in Python, if <code>process</code> is conceptually the function that I need in order to do something useful to each line from this file:</p>\n\n<pre><code>import os\nsep_pos = -len(os.linesep)\nwith open(\"file.txt\") as f:\n for line in f:\n if line[sep_pos:] == os.linesep:\n line = line[:sep_pos]\n process(line)\n</code></pre>\n"
},
{
"answer_id": 21242117,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import re\n\nr_unwanted = re.compile(\"[\\n\\t\\r]\")\nr_unwanted.sub(\"\", your_text)\n</code></pre>\n"
},
{
"answer_id": 26554128,
"author": "user4178860",
"author_id": 4178860,
"author_profile": "https://Stackoverflow.com/users/4178860",
"pm_score": -1,
"selected": false,
"text": "<p>A catch all:</p>\n\n<pre><code>line = line.rstrip('\\r|\\n')\n</code></pre>\n"
},
{
"answer_id": 27054136,
"author": "Hackaholic",
"author_id": 2294755,
"author_profile": "https://Stackoverflow.com/users/2294755",
"pm_score": 5,
"selected": false,
"text": "<p>you can use strip:</p>\n\n<pre><code>line = line.strip()\n</code></pre>\n\n<p>demo:</p>\n\n<pre><code>>>> \"\\n\\n hello world \\n\\n\".strip()\n'hello world'\n</code></pre>\n"
},
{
"answer_id": 27890752,
"author": "kuzzooroo",
"author_id": 2829764,
"author_profile": "https://Stackoverflow.com/users/2829764",
"pm_score": 3,
"selected": false,
"text": "<p>I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:</p>\n\n<pre><code>def chomped_lines(it):\n return map(operator.methodcaller('rstrip', '\\r\\n'), it)\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>with open(\"file.txt\") as infile:\n for line in chomped_lines(infile):\n process(line)\n</code></pre>\n"
},
{
"answer_id": 28937424,
"author": "slec",
"author_id": 508792,
"author_profile": "https://Stackoverflow.com/users/508792",
"pm_score": 5,
"selected": false,
"text": "<pre><code>s = s.rstrip()\n</code></pre>\n\n<p>will remove all newlines at the end of the string <code>s</code>. The assignment is needed because <code>rstrip</code> returns a new string instead of modifying the original string. </p>\n"
},
{
"answer_id": 32882948,
"author": "Alien Life Form",
"author_id": 279600,
"author_profile": "https://Stackoverflow.com/users/279600",
"pm_score": 5,
"selected": false,
"text": "<p>This would replicate exactly perl's chomp (minus behavior on arrays) for \"\\n\" line terminator:</p>\n\n<pre><code>def chomp(x):\n if x.endswith(\"\\r\\n\"): return x[:-2]\n if x.endswith(\"\\n\") or x.endswith(\"\\r\"): return x[:-1]\n return x\n</code></pre>\n\n<p>(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \\r\\n in account)</p>\n"
},
{
"answer_id": 33392998,
"author": "Stephen Miller",
"author_id": 5366724,
"author_profile": "https://Stackoverflow.com/users/5366724",
"pm_score": 1,
"selected": false,
"text": "<p>If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:</p>\n\n<pre><code>import time\n\nloops = 50000000\n\ndef method1(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string[:-1]\n t1 = time.time()\n print('Method 1: ' + str(t1 - t0))\n\ndef method2(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string.rstrip()\n t1 = time.time()\n print('Method 2: ' + str(t1 - t0))\n\nmethod1()\nmethod2()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Method 1: 3.92700004578\nMethod 2: 6.73000001907\n</code></pre>\n"
},
{
"answer_id": 37346773,
"author": "Help me",
"author_id": 6361076,
"author_profile": "https://Stackoverflow.com/users/6361076",
"pm_score": 2,
"selected": false,
"text": "<p>Just use : </p>\n\n<pre><code>line = line.rstrip(\"\\n\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>line = line.strip(\"\\n\")\n</code></pre>\n\n<p>You don't need any of this complicated stuff</p>\n"
},
{
"answer_id": 40749138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>>>> ' spacious '.rstrip()\n' spacious'\n>>> \"AABAA\".rstrip(\"A\")\n 'AAB'\n>>> \"ABBA\".rstrip(\"AB\") # both AB and BA are stripped\n ''\n>>> \"ABCABBA\".rstrip(\"AB\")\n 'ABC'\n</code></pre>\n"
},
{
"answer_id": 40750864,
"author": "internetional",
"author_id": 7057076,
"author_profile": "https://Stackoverflow.com/users/7057076",
"pm_score": 2,
"selected": false,
"text": "<p>There are three types of line endings that we normally encounter: <code>\\n</code>, <code>\\r</code> and <code>\\r\\n</code>. A rather simple regular expression in <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a>, namely <code>r\"\\r?\\n?$\"</code>, is able to catch them all.</p>\n\n<p>(And we <em>gotta catch 'em all</em>, am I right?)</p>\n\n<pre><code>import re\n\nre.sub(r\"\\r?\\n?$\", \"\", the_text, 1)\n</code></pre>\n\n<p>With the last argument, we limit the number of occurences replaced to one, mimicking chomp to some extent. Example:</p>\n\n<pre><code>import re\n\ntext_1 = \"hellothere\\n\\n\\n\"\ntext_2 = \"hellothere\\n\\n\\r\"\ntext_3 = \"hellothere\\n\\n\\r\\n\"\n\na = re.sub(r\"\\r?\\n?$\", \"\", text_1, 1)\nb = re.sub(r\"\\r?\\n?$\", \"\", text_2, 1)\nc = re.sub(r\"\\r?\\n?$\", \"\", text_3, 1)\n</code></pre>\n\n<p>... where <code>a == b == c</code> is <code>True</code>.</p>\n"
},
{
"answer_id": 43641376,
"author": "teichert",
"author_id": 3780389,
"author_profile": "https://Stackoverflow.com/users/3780389",
"pm_score": 3,
"selected": false,
"text": "<p>It looks like there is not a perfect analog for perl's <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\">chomp</a>. In particular, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">rstrip</a> cannot handle multi-character newline delimiters like <code>\\r\\n</code>. However, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"noreferrer\">splitlines</a> does <a href=\"https://stackoverflow.com/a/275659/3780389\">as pointed out here</a>.\nFollowing <a href=\"https://stackoverflow.com/a/43641128/3780389\">my answer</a> on a different question, you can combine <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"noreferrer\">join</a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"noreferrer\">splitlines</a> to remove/replace all newlines from a string <code>s</code>:</p>\n\n<pre><code>''.join(s.splitlines())\n</code></pre>\n\n<p>The following removes <em>exactly one <strong>trailing</em></strong> newline (as chomp would, I believe). Passing <code>True</code> as the <code>keepends</code> argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last \"line\": </p>\n\n<pre><code>def chomp(s):\n if len(s):\n lines = s.splitlines(True)\n last = lines.pop()\n return ''.join(lines + last.splitlines())\n else:\n return ''\n</code></pre>\n"
},
{
"answer_id": 45342003,
"author": "Taylor D. Edmiston",
"author_id": 149428,
"author_profile": "https://Stackoverflow.com/users/149428",
"pm_score": 3,
"selected": false,
"text": "<p>I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using <code>re</code> is a clearer more explicit solution to this problem than <code>str.rstrip</code>.</p>\n\n<pre><code>>>> import re\n</code></pre>\n\n<p>If you want to remove one or more <em>trailing</em> newline chars:</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]+$', '', '\\nx\\r\\n')\n'\\nx'\n</code></pre>\n\n<p>If you want to remove newline chars everywhere (not just trailing):</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]+', '', '\\nx\\r\\n')\n'x'\n</code></pre>\n\n<p>If you want to remove only 1-2 trailing newline chars (i.e., <code>\\r</code>, <code>\\n</code>, <code>\\r\\n</code>, <code>\\n\\r</code>, <code>\\r\\r</code>, <code>\\n\\n</code>)</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r\\n')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n')\n'\\nx'\n</code></pre>\n\n<p>I have a feeling what most people really want here, is to remove just <em>one</em> occurrence of a trailing newline character, either <code>\\r\\n</code> or <code>\\n</code> and nothing more.</p>\n\n<pre><code>>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n\\n', count=1)\n'\\nx\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n\\r\\n', count=1)\n'\\nx\\r\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n', count=1)\n'\\nx'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n', count=1)\n'\\nx'\n</code></pre>\n\n<p>(The <code>?:</code> is to create a non-capturing group.)</p>\n\n<p>(By the way this is <em>not</em> what <code>'...'.rstrip('\\n', '').rstrip('\\r', '')</code> does which may not be clear to others stumbling upon this thread. <code>str.rstrip</code> strips as many of the trailing characters as possible, so a string like <code>foo\\n\\n\\n</code> would result in a false positive of <code>foo</code> whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)</p>\n"
},
{
"answer_id": 50870896,
"author": "Venfah Nazir",
"author_id": 3383819,
"author_profile": "https://Stackoverflow.com/users/3383819",
"pm_score": 0,
"selected": false,
"text": "<hr>\n\n<p>This will work both for windows and linux (bit expensive with re sub if you are looking for only re solution)</p>\n\n<pre><code>import re \nif re.search(\"(\\\\r|)\\\\n$\", line):\n line = re.sub(\"(\\\\r|)\\\\n$\", \"\", line)\n</code></pre>\n\n<hr>\n"
},
{
"answer_id": 58499321,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\n# import the module string \nimport string\n# use the method translate to convert \ns.translate({ord(c): None for c in string.whitespace}\n>>'HelloWorldHiThere'\n</code></pre>\n\n<p>With regex</p>\n\n<pre><code>s = ''' Hello World \n\\t\\n\\r\\tHi '''\nprint(re.sub(r\"\\s+\", \"\", s), sep='') # \\s matches all white spaces\n>HelloWorldHi\n</code></pre>\n\n<p>Replace \\n,\\t,\\r</p>\n\n<pre><code>s.replace('\\n', '').replace('\\t','').replace('\\r','')\n>' Hello World Hi '\n</code></pre>\n\n<p>With regex</p>\n\n<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\nregex = re.compile(r'[\\n\\r\\t]')\nregex.sub(\"\", s)\n>'Hello World Hi There'\n</code></pre>\n\n<p>with Join</p>\n\n<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\n' '.join(s.split())\n>'Hello World Hi There'\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I remove the last character of a string if it is a newline?
```
"abc\n" --> "abc"
```
|
Try the method `rstrip()` (see doc [Python 2](http://docs.python.org/2/library/stdtypes.html#str.rstrip) and [Python 3](https://docs.python.org/3/library/stdtypes.html#str.rstrip))
```
>>> 'test string\n'.rstrip()
'test string'
```
Python's `rstrip()` method strips *all* kinds of trailing whitespace by default, not just one newline as Perl does with [`chomp`](http://perldoc.perl.org/functions/chomp.html).
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
```
To strip only newlines:
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
```
In addition to `rstrip()`, there are also the methods `strip()` and `lstrip()`. Here is an example with the three of them:
```
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
```
|
275,022 |
<p>With squid, we can cache webpages. I am not sure if it provides the same number of caching methods as ASP.NET caching (I primarily use ASP.NET), but it's a tool to cache webpages.</p>
<p>Then we have memcached, which can cache database tables. I believe this is correct, and it is like SqlCacheDependency (correct me if I am wrong).</p>
<p>However, is there any situation in a large web application where one would find room to use memcached, squid, AND ASP.NET (or PHP, JSP - application framework-level) caching.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 275025,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 11,
"selected": false,
"text": "<p>Try the method <code>rstrip()</code> (see doc <a href=\"http://docs.python.org/2/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">Python 2</a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">Python 3</a>)</p>\n<pre><code>>>> 'test string\\n'.rstrip()\n'test string'\n</code></pre>\n<p>Python's <code>rstrip()</code> method strips <em>all</em> kinds of trailing whitespace by default, not just one newline as Perl does with <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\"><code>chomp</code></a>.</p>\n<pre><code>>>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip()\n'test string'\n</code></pre>\n<p>To strip only newlines:</p>\n<pre><code>>>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip('\\n')\n'test string \\n \\r\\n\\n\\r '\n</code></pre>\n<p>In addition to <code>rstrip()</code>, there are also the methods <code>strip()</code> and <code>lstrip()</code>. Here is an example with the three of them:</p>\n<pre><code>>>> s = " \\n\\r\\n \\n abc def \\n\\r\\n \\n "\n>>> s.strip()\n'abc def'\n>>> s.lstrip()\n'abc def \\n\\r\\n \\n '\n>>> s.rstrip()\n' \\n\\r\\n \\n abc def'\n</code></pre>\n"
},
{
"answer_id": 275401,
"author": "Mike",
"author_id": 19215,
"author_profile": "https://Stackoverflow.com/users/19215",
"pm_score": 7,
"selected": false,
"text": "<p>The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \\r or \\n. Here are examples for Mac, Windows, and Unix EOL characters.</p>\n\n<pre><code>>>> 'Mac EOL\\r'.rstrip('\\r\\n')\n'Mac EOL'\n>>> 'Windows EOL\\r\\n'.rstrip('\\r\\n')\n'Windows EOL'\n>>> 'Unix EOL\\n'.rstrip('\\r\\n')\n'Unix EOL'\n</code></pre>\n\n<p>Using '\\r\\n' as the parameter to rstrip means that it will strip out any trailing combination of '\\r' or '\\n'. That's why it works in all three cases above.</p>\n\n<p>This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing '\\r' as its EOL character. The Windows machine on which I was using this message had appended its own '\\r\\n' EOL character. Therefore, the end of each line looked like '\\r\\r\\n'. Using rstrip('\\r\\n') would have taken off the entire '\\r\\r\\n' which is not what I wanted. In that case, I simply sliced off the last two characters instead.</p>\n\n<p>Note that unlike Perl's <code>chomp</code> function, this will strip all specified characters at the end of the string, not just one:</p>\n\n<pre><code>>>> \"Hello\\n\\n\\n\".rstrip(\"\\n\")\n\"Hello\"\n</code></pre>\n"
},
{
"answer_id": 275659,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 8,
"selected": false,
"text": "<p>And I would say the \"pythonic\" way to get lines without trailing newline characters is splitlines().</p>\n\n<pre><code>>>> text = \"line 1\\nline 2\\r\\nline 3\\nline 4\"\n>>> text.splitlines()\n['line 1', 'line 2', 'line 3', 'line 4']\n</code></pre>\n"
},
{
"answer_id": 326279,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:</p>\n\n<pre><code>$x=\"a\\n\";\n\nchomp $x\n</code></pre>\n\n<p>results in <code>$x</code> being <code>\"a\"</code>.</p>\n\n<p>but in Python:</p>\n\n<pre><code>x=\"a\\n\"\n\nx.rstrip()\n</code></pre>\n\n<p>will mean that the value of <code>x</code> is <strong>still</strong> <code>\"a\\n\"</code>. Even <code>x=x.rstrip()</code> doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.</p>\n"
},
{
"answer_id": 1077495,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 4,
"selected": false,
"text": "<p>I don't program in Python, but I came across an <a href=\"http://www.python.org/doc/faq/programming/#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings\" rel=\"nofollow noreferrer\">FAQ</a> at python.org advocating S.rstrip(\"\\r\\n\") for python 2.2 or later.</p>\n"
},
{
"answer_id": 2396894,
"author": "Jamie",
"author_id": 288263,
"author_profile": "https://Stackoverflow.com/users/288263",
"pm_score": 6,
"selected": false,
"text": "<p>I might use something like this:</p>\n\n<pre><code>import os\ns = s.rstrip(os.linesep)\n</code></pre>\n\n<p>I think the problem with <code>rstrip(\"\\n\")</code> is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use <code>\"\\r\\n\"</code>). The other gotcha is that <code>rstrip</code> will strip out repeated whitespace. Hopefully <code>os.linesep</code> will contain the right characters. the above works for me.</p>\n"
},
{
"answer_id": 5764202,
"author": "ingydotnet",
"author_id": 721703,
"author_profile": "https://Stackoverflow.com/users/721703",
"pm_score": 4,
"selected": false,
"text": "<p>rstrip doesn't do the same thing as chomp, on so many levels. Read <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\">http://perldoc.perl.org/functions/chomp.html</a> and see that chomp is very complex indeed.</p>\n\n<p>However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.</p>\n\n<p>Here you can see rstrip removing all the newlines:</p>\n\n<pre><code>>>> 'foo\\n\\n'.rstrip(os.linesep)\n'foo'\n</code></pre>\n\n<p>A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:</p>\n\n<pre><code>>>> re.sub(os.linesep + r'\\Z','','foo\\n\\n')\n'foo\\n'\n</code></pre>\n"
},
{
"answer_id": 5803510,
"author": "Carlos Valiente",
"author_id": 179149,
"author_profile": "https://Stackoverflow.com/users/179149",
"pm_score": 4,
"selected": false,
"text": "<p>Careful with <code>\"foo\".rstrip(os.linesep)</code>: That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:</p>\n\n<pre><code>$ python\nPython 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) \n[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os, sys\n>>> sys.platform\n'linux2'\n>>> \"foo\\r\\n\".rstrip(os.linesep)\n'foo\\r'\n>>>\n</code></pre>\n\n<p>Use <code>\"foo\".rstrip(\"\\r\\n\")</code> instead, as Mike says above.</p>\n"
},
{
"answer_id": 8327143,
"author": "Chij",
"author_id": 1073506,
"author_profile": "https://Stackoverflow.com/users/1073506",
"pm_score": 3,
"selected": false,
"text": "<p>workaround solution for special case:</p>\n\n<p>if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows: </p>\n\n<pre><code>foobar= foobar[:-1]\n</code></pre>\n\n<p>to slice out your newline character. </p>\n"
},
{
"answer_id": 9507807,
"author": "mihaicc",
"author_id": 648904,
"author_profile": "https://Stackoverflow.com/users/648904",
"pm_score": 5,
"selected": false,
"text": "<pre><code>"line 1\\nline 2\\r\\n...".replace('\\n', '').replace('\\r', '')\n>>> 'line 1line 2...'\n</code></pre>\n<p>or you could always get geekier with regexps</p>\n"
},
{
"answer_id": 16527062,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 5,
"selected": false,
"text": "<p>You may use <code>line = line.rstrip('\\n')</code>. This will strip all newlines from the end of the string, not just one.</p>\n"
},
{
"answer_id": 19317570,
"author": "Leozj",
"author_id": 2870855,
"author_profile": "https://Stackoverflow.com/users/2870855",
"pm_score": 3,
"selected": false,
"text": "<p>If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\\n' and then join this list into a new str(newstr).</p>\n\n<p><code>newstr = \"\".join(oldstr.split('\\n'))</code> </p>\n"
},
{
"answer_id": 19531239,
"author": "minopret",
"author_id": 931925,
"author_profile": "https://Stackoverflow.com/users/931925",
"pm_score": 4,
"selected": false,
"text": "<p>An <a href=\"http://docs.python.org/2/library/stdtypes.html#file.next\" rel=\"noreferrer\">example in Python's documentation</a> simply uses <code>line.strip()</code>.</p>\n\n<p>Perl's <code>chomp</code> function removes one linebreak sequence from the end of a string only if it's actually there.</p>\n\n<p>Here is how I plan to do that in Python, if <code>process</code> is conceptually the function that I need in order to do something useful to each line from this file:</p>\n\n<pre><code>import os\nsep_pos = -len(os.linesep)\nwith open(\"file.txt\") as f:\n for line in f:\n if line[sep_pos:] == os.linesep:\n line = line[:sep_pos]\n process(line)\n</code></pre>\n"
},
{
"answer_id": 21242117,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import re\n\nr_unwanted = re.compile(\"[\\n\\t\\r]\")\nr_unwanted.sub(\"\", your_text)\n</code></pre>\n"
},
{
"answer_id": 26554128,
"author": "user4178860",
"author_id": 4178860,
"author_profile": "https://Stackoverflow.com/users/4178860",
"pm_score": -1,
"selected": false,
"text": "<p>A catch all:</p>\n\n<pre><code>line = line.rstrip('\\r|\\n')\n</code></pre>\n"
},
{
"answer_id": 27054136,
"author": "Hackaholic",
"author_id": 2294755,
"author_profile": "https://Stackoverflow.com/users/2294755",
"pm_score": 5,
"selected": false,
"text": "<p>you can use strip:</p>\n\n<pre><code>line = line.strip()\n</code></pre>\n\n<p>demo:</p>\n\n<pre><code>>>> \"\\n\\n hello world \\n\\n\".strip()\n'hello world'\n</code></pre>\n"
},
{
"answer_id": 27890752,
"author": "kuzzooroo",
"author_id": 2829764,
"author_profile": "https://Stackoverflow.com/users/2829764",
"pm_score": 3,
"selected": false,
"text": "<p>I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:</p>\n\n<pre><code>def chomped_lines(it):\n return map(operator.methodcaller('rstrip', '\\r\\n'), it)\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>with open(\"file.txt\") as infile:\n for line in chomped_lines(infile):\n process(line)\n</code></pre>\n"
},
{
"answer_id": 28937424,
"author": "slec",
"author_id": 508792,
"author_profile": "https://Stackoverflow.com/users/508792",
"pm_score": 5,
"selected": false,
"text": "<pre><code>s = s.rstrip()\n</code></pre>\n\n<p>will remove all newlines at the end of the string <code>s</code>. The assignment is needed because <code>rstrip</code> returns a new string instead of modifying the original string. </p>\n"
},
{
"answer_id": 32882948,
"author": "Alien Life Form",
"author_id": 279600,
"author_profile": "https://Stackoverflow.com/users/279600",
"pm_score": 5,
"selected": false,
"text": "<p>This would replicate exactly perl's chomp (minus behavior on arrays) for \"\\n\" line terminator:</p>\n\n<pre><code>def chomp(x):\n if x.endswith(\"\\r\\n\"): return x[:-2]\n if x.endswith(\"\\n\") or x.endswith(\"\\r\"): return x[:-1]\n return x\n</code></pre>\n\n<p>(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \\r\\n in account)</p>\n"
},
{
"answer_id": 33392998,
"author": "Stephen Miller",
"author_id": 5366724,
"author_profile": "https://Stackoverflow.com/users/5366724",
"pm_score": 1,
"selected": false,
"text": "<p>If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:</p>\n\n<pre><code>import time\n\nloops = 50000000\n\ndef method1(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string[:-1]\n t1 = time.time()\n print('Method 1: ' + str(t1 - t0))\n\ndef method2(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string.rstrip()\n t1 = time.time()\n print('Method 2: ' + str(t1 - t0))\n\nmethod1()\nmethod2()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Method 1: 3.92700004578\nMethod 2: 6.73000001907\n</code></pre>\n"
},
{
"answer_id": 37346773,
"author": "Help me",
"author_id": 6361076,
"author_profile": "https://Stackoverflow.com/users/6361076",
"pm_score": 2,
"selected": false,
"text": "<p>Just use : </p>\n\n<pre><code>line = line.rstrip(\"\\n\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>line = line.strip(\"\\n\")\n</code></pre>\n\n<p>You don't need any of this complicated stuff</p>\n"
},
{
"answer_id": 40749138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>>>> ' spacious '.rstrip()\n' spacious'\n>>> \"AABAA\".rstrip(\"A\")\n 'AAB'\n>>> \"ABBA\".rstrip(\"AB\") # both AB and BA are stripped\n ''\n>>> \"ABCABBA\".rstrip(\"AB\")\n 'ABC'\n</code></pre>\n"
},
{
"answer_id": 40750864,
"author": "internetional",
"author_id": 7057076,
"author_profile": "https://Stackoverflow.com/users/7057076",
"pm_score": 2,
"selected": false,
"text": "<p>There are three types of line endings that we normally encounter: <code>\\n</code>, <code>\\r</code> and <code>\\r\\n</code>. A rather simple regular expression in <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a>, namely <code>r\"\\r?\\n?$\"</code>, is able to catch them all.</p>\n\n<p>(And we <em>gotta catch 'em all</em>, am I right?)</p>\n\n<pre><code>import re\n\nre.sub(r\"\\r?\\n?$\", \"\", the_text, 1)\n</code></pre>\n\n<p>With the last argument, we limit the number of occurences replaced to one, mimicking chomp to some extent. Example:</p>\n\n<pre><code>import re\n\ntext_1 = \"hellothere\\n\\n\\n\"\ntext_2 = \"hellothere\\n\\n\\r\"\ntext_3 = \"hellothere\\n\\n\\r\\n\"\n\na = re.sub(r\"\\r?\\n?$\", \"\", text_1, 1)\nb = re.sub(r\"\\r?\\n?$\", \"\", text_2, 1)\nc = re.sub(r\"\\r?\\n?$\", \"\", text_3, 1)\n</code></pre>\n\n<p>... where <code>a == b == c</code> is <code>True</code>.</p>\n"
},
{
"answer_id": 43641376,
"author": "teichert",
"author_id": 3780389,
"author_profile": "https://Stackoverflow.com/users/3780389",
"pm_score": 3,
"selected": false,
"text": "<p>It looks like there is not a perfect analog for perl's <a href=\"http://perldoc.perl.org/functions/chomp.html\" rel=\"noreferrer\">chomp</a>. In particular, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.rstrip\" rel=\"noreferrer\">rstrip</a> cannot handle multi-character newline delimiters like <code>\\r\\n</code>. However, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"noreferrer\">splitlines</a> does <a href=\"https://stackoverflow.com/a/275659/3780389\">as pointed out here</a>.\nFollowing <a href=\"https://stackoverflow.com/a/43641128/3780389\">my answer</a> on a different question, you can combine <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"noreferrer\">join</a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.splitlines\" rel=\"noreferrer\">splitlines</a> to remove/replace all newlines from a string <code>s</code>:</p>\n\n<pre><code>''.join(s.splitlines())\n</code></pre>\n\n<p>The following removes <em>exactly one <strong>trailing</em></strong> newline (as chomp would, I believe). Passing <code>True</code> as the <code>keepends</code> argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last \"line\": </p>\n\n<pre><code>def chomp(s):\n if len(s):\n lines = s.splitlines(True)\n last = lines.pop()\n return ''.join(lines + last.splitlines())\n else:\n return ''\n</code></pre>\n"
},
{
"answer_id": 45342003,
"author": "Taylor D. Edmiston",
"author_id": 149428,
"author_profile": "https://Stackoverflow.com/users/149428",
"pm_score": 3,
"selected": false,
"text": "<p>I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using <code>re</code> is a clearer more explicit solution to this problem than <code>str.rstrip</code>.</p>\n\n<pre><code>>>> import re\n</code></pre>\n\n<p>If you want to remove one or more <em>trailing</em> newline chars:</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]+$', '', '\\nx\\r\\n')\n'\\nx'\n</code></pre>\n\n<p>If you want to remove newline chars everywhere (not just trailing):</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]+', '', '\\nx\\r\\n')\n'x'\n</code></pre>\n\n<p>If you want to remove only 1-2 trailing newline chars (i.e., <code>\\r</code>, <code>\\n</code>, <code>\\r\\n</code>, <code>\\n\\r</code>, <code>\\r\\r</code>, <code>\\n\\n</code>)</p>\n\n<pre><code>>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r\\n')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n')\n'\\nx'\n</code></pre>\n\n<p>I have a feeling what most people really want here, is to remove just <em>one</em> occurrence of a trailing newline character, either <code>\\r\\n</code> or <code>\\n</code> and nothing more.</p>\n\n<pre><code>>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n\\n', count=1)\n'\\nx\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n\\r\\n', count=1)\n'\\nx\\r\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n', count=1)\n'\\nx'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n', count=1)\n'\\nx'\n</code></pre>\n\n<p>(The <code>?:</code> is to create a non-capturing group.)</p>\n\n<p>(By the way this is <em>not</em> what <code>'...'.rstrip('\\n', '').rstrip('\\r', '')</code> does which may not be clear to others stumbling upon this thread. <code>str.rstrip</code> strips as many of the trailing characters as possible, so a string like <code>foo\\n\\n\\n</code> would result in a false positive of <code>foo</code> whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)</p>\n"
},
{
"answer_id": 50870896,
"author": "Venfah Nazir",
"author_id": 3383819,
"author_profile": "https://Stackoverflow.com/users/3383819",
"pm_score": 0,
"selected": false,
"text": "<hr>\n\n<p>This will work both for windows and linux (bit expensive with re sub if you are looking for only re solution)</p>\n\n<pre><code>import re \nif re.search(\"(\\\\r|)\\\\n$\", line):\n line = re.sub(\"(\\\\r|)\\\\n$\", \"\", line)\n</code></pre>\n\n<hr>\n"
},
{
"answer_id": 58499321,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\n# import the module string \nimport string\n# use the method translate to convert \ns.translate({ord(c): None for c in string.whitespace}\n>>'HelloWorldHiThere'\n</code></pre>\n\n<p>With regex</p>\n\n<pre><code>s = ''' Hello World \n\\t\\n\\r\\tHi '''\nprint(re.sub(r\"\\s+\", \"\", s), sep='') # \\s matches all white spaces\n>HelloWorldHi\n</code></pre>\n\n<p>Replace \\n,\\t,\\r</p>\n\n<pre><code>s.replace('\\n', '').replace('\\t','').replace('\\r','')\n>' Hello World Hi '\n</code></pre>\n\n<p>With regex</p>\n\n<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\nregex = re.compile(r'[\\n\\r\\t]')\nregex.sub(\"\", s)\n>'Hello World Hi There'\n</code></pre>\n\n<p>with Join</p>\n\n<pre><code>s = '''Hello World \\t\\n\\r\\tHi There'''\n' '.join(s.split())\n>'Hello World Hi There'\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
With squid, we can cache webpages. I am not sure if it provides the same number of caching methods as ASP.NET caching (I primarily use ASP.NET), but it's a tool to cache webpages.
Then we have memcached, which can cache database tables. I believe this is correct, and it is like SqlCacheDependency (correct me if I am wrong).
However, is there any situation in a large web application where one would find room to use memcached, squid, AND ASP.NET (or PHP, JSP - application framework-level) caching.
Thanks!
|
Try the method `rstrip()` (see doc [Python 2](http://docs.python.org/2/library/stdtypes.html#str.rstrip) and [Python 3](https://docs.python.org/3/library/stdtypes.html#str.rstrip))
```
>>> 'test string\n'.rstrip()
'test string'
```
Python's `rstrip()` method strips *all* kinds of trailing whitespace by default, not just one newline as Perl does with [`chomp`](http://perldoc.perl.org/functions/chomp.html).
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
```
To strip only newlines:
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
```
In addition to `rstrip()`, there are also the methods `strip()` and `lstrip()`. Here is an example with the three of them:
```
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
```
|
275,034 |
<p>One of the features of the modern (64 bit OS X and iPhone OS) Objective C runtime is the ability for properties to dynamically synthesize ivars without explicitly declaring them in the class:</p>
<pre><code>@interface MyClass : NSObject {
// NSString *name; unnecessary on modern runtimes
}
@property (retain) NSStrng *name;
@end
@implementation MyClass
@synthesize name;
@end
</code></pre>
<p>In quite a bit of my code I use custom getter implementations in order to initialize the properties:</p>
<pre><code>- (NSString *) name {
if (!name) {
name = @"Louis";
}
return name;
}
</code></pre>
<p>The above is incompatible with synthesized ivars since it needs to access a an ivar that is not declared in the header. For various reasons I would like to update a number of my personal frameworks to use synthesized ivars when built on the modern runtimes, the above code needs to be modified to work with synthesized ivars in order to achieve that goal.</p>
<p>While the Objective C 2.0 documentation states that the synthesized accessors on the modern runtime will synthesize the ivar on first use. It does not specify what low level mechanism is used to do this. Is it done by class_getInstanceVariable(), are the restrictions on class_addIvar() loosened, is it an undocumented function int he objective C 2.0 runtime? While I could implement my own side storage for the data backing my properties, I would much rather use the mechanism that synthesized accessors are using.</p>
|
[
{
"answer_id": 275134,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 5,
"selected": true,
"text": "<p>I went and looked at the documentation again just now, and I think you're misreading it. Synthesized ivars are created at compile time, not at run time.</p>\n<p>According to the <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_5_section_3.html\" rel=\"noreferrer\">Objective-C 2.0 documentation</a>:</p>\n<blockquote>\n<p>There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):</p>\n<p>For the legacy runtimes, instance variables must already be declared in the @interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.</p>\n<p>For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.</p>\n</blockquote>\n<p>So all you need to do is declare the instance variable you need, and the same code will work on both runtimes...</p>\n"
},
{
"answer_id": 5542886,
"author": "JD Brennan",
"author_id": 304712,
"author_profile": "https://Stackoverflow.com/users/304712",
"pm_score": -1,
"selected": false,
"text": "<p>You add properties at run-time with the <a href=\"http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/Reference/Reference.html\" rel=\"nofollow\">NSKeyValueCoding Protocol</a>.</p>\n\n<pre><code>[myObject setValue:@\"whatever\" forKey:@\"foo\"];\n</code></pre>\n"
},
{
"answer_id": 9045742,
"author": "Farcaller",
"author_id": 151652,
"author_profile": "https://Stackoverflow.com/users/151652",
"pm_score": 0,
"selected": false,
"text": "<p>What you are looking for is @synthesized name, like:</p>\n\n<pre><code>@synthesize name = _name;\n\n...\n\n- (NSString *) name {\n if (!name) {\n _name = @\"Louis\";\n }\n\n return _name;\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30506/"
] |
One of the features of the modern (64 bit OS X and iPhone OS) Objective C runtime is the ability for properties to dynamically synthesize ivars without explicitly declaring them in the class:
```
@interface MyClass : NSObject {
// NSString *name; unnecessary on modern runtimes
}
@property (retain) NSStrng *name;
@end
@implementation MyClass
@synthesize name;
@end
```
In quite a bit of my code I use custom getter implementations in order to initialize the properties:
```
- (NSString *) name {
if (!name) {
name = @"Louis";
}
return name;
}
```
The above is incompatible with synthesized ivars since it needs to access a an ivar that is not declared in the header. For various reasons I would like to update a number of my personal frameworks to use synthesized ivars when built on the modern runtimes, the above code needs to be modified to work with synthesized ivars in order to achieve that goal.
While the Objective C 2.0 documentation states that the synthesized accessors on the modern runtime will synthesize the ivar on first use. It does not specify what low level mechanism is used to do this. Is it done by class\_getInstanceVariable(), are the restrictions on class\_addIvar() loosened, is it an undocumented function int he objective C 2.0 runtime? While I could implement my own side storage for the data backing my properties, I would much rather use the mechanism that synthesized accessors are using.
|
I went and looked at the documentation again just now, and I think you're misreading it. Synthesized ivars are created at compile time, not at run time.
According to the [Objective-C 2.0 documentation](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_5_section_3.html):
>
> There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):
>
>
> For the legacy runtimes, instance variables must already be declared in the @interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.
>
>
> For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.
>
>
>
So all you need to do is declare the instance variable you need, and the same code will work on both runtimes...
|
275,038 |
<p>I wish to convert a single string with multiple delimiters into a key=>value hash structure. Is there a simple way to accomplish this? My current implementation is:</p>
<pre><code>sub readConfigFile() {
my %CONFIG;
my $index = 0;
open(CON_FILE, "config");
my @lines = <CON_FILE>;
close(CON_FILE);
my @array = split(/>/, $lines[0]);
my $total = @array;
while($index < $total) {
my @arr = split(/=/, $array[$index]);
chomp($arr[1]);
$CONFIG{$arr[0]} = $arr[1];
$index = $index + 1;
}
while ( ($k,$v) = each %CONFIG ) {
print "$k => $v\n";
}
return;
}
</code></pre>
<p>where 'config' contains:</p>
<pre><code>pub=3>rec=0>size=3>adv=1234 123 4.5 6.00
pub=1>rec=1>size=2>adv=111 22 3456 .76
</code></pre>
<p>The last digits need to be also removed, and kept in a separate key=>value pair whose name can be 'ip'. (I have not been able to accomplish this without making the code too lengthy and complicated).</p>
|
[
{
"answer_id": 275079,
"author": "Martin Redmond",
"author_id": 30541,
"author_profile": "https://Stackoverflow.com/users/30541",
"pm_score": 0,
"selected": false,
"text": "<p>Here's one way. </p>\n\n<pre>\n\nforeach ( @lines ) {\n chomp;\n my %CONFIG;\n # Extract the last digit first and replace it with an end of\n # pair delimiter.\n s/\\s*([\\d\\.]+)\\s*$/>/;\n $CONFIG{ip} = $1;\n while ( /([^=]*)=([^>]*)>/g ) {\n $CONFIG{$1} = $2;\n }\n print Dumper ( \\%CONFIG );\n}\n</pre>\n"
},
{
"answer_id": 275127,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": true,
"text": "<p>What is your configuration data structure supposed to look like? So far the solutions only record the last line because they are stomping on the same hash keys every time they add a record. </p>\n\n<p>Here's something that might get you closer, but you still need to figure out what the data structure should be.</p>\n\n<ul>\n<li><p>I pass in the file handle as an argument so my subroutine isn't tied to a particular way of getting the data. It can be from a file, a string, a socket, or even the stuff below <strong>DATA</strong> in this case.</p></li>\n<li><p>Instead of fixing things up after I parse the string, I fix the string to have the \"ip\" element before I parse it. Once I do that, the \"ip\" element isn't a special case and it's just a matter of a double split. This is a very important technique to save a lot of work and code.</p></li>\n<li><p>I create a hash reference inside the subroutine and return that hash reference when I'm done. I don't need a global variable. :)</p></li>\n</ul>\n\n<pre>\nuse warnings;\nuse strict;\n\nuse Data::Dumper;\n\nreadConfigFile( \\*DATA );\n\nsub readConfigFile\n {\n my( $fh ) = shift;\n\n my $hash = {};\n\n while( <$fh> )\n {\n chomp;\n\n s/\\s+(\\d*\\.\\d+)$/>ip=$1/;\n\n $hash->{ $. } = { map { split /=/ } split />/ };\n }\n\n return $hash;\n }\n\nmy $hash = readConfigFile( \\*DATA );\n\nprint Dumper( $hash );\n\n__DATA__\npub=3>rec=0>size=3>adv=1234 123 4.5 6.00\npub=1>rec=1>size=2>adv=111 22 3456 .76\n\n</pre>\n\n<p>This gives you a data structure where each line is a separate record. I choose the line number of the record (<code>$.</code>) as the top-level key, but you can use anything that you like.</p>\n\n<pre>\n$VAR1 = {\n '1' => {\n 'ip' => '6.00',\n 'rec' => '0',\n 'adv' => '1234 123 4.5',\n 'pub' => '3',\n 'size' => '3'\n },\n '2' => {\n 'ip' => '.76',\n 'rec' => '1',\n 'adv' => '111 22 3456',\n 'pub' => '1',\n 'size' => '2'\n }\n };\n</pre>\n\n<p>If that's not the structure you want, show us what you'd like to end up with and we can adjust our answers.</p>\n"
},
{
"answer_id": 275140,
"author": "Chris Charley",
"author_id": 35812,
"author_profile": "https://Stackoverflow.com/users/35812",
"pm_score": 2,
"selected": false,
"text": "<p>I am assuming that you want to read and parse more than 1 line. So, I chose to store the values in an AoH.<p></p>\n\n<pre>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy @config;\n\nwhile (<DATA>) {\n chomp;\n push @config, { split /[=>]/ };\n}\n\nfor my $href (@config) {\n while (my ($k, $v) = each %$href) {\n print \"$k => $v\\n\";\n }\n}\n\n__DATA__\npub=3>rec=0>size=3>adv=1234 123 4.5 6.00\npub=1>rec=1>size=2>adv=111 22 3456 .76\n</pre>\n\n<p>This results in the printout below. (The while loop above reads from DATA.)</p>\n\n<pre>rec => 0\nadv => 1234 123 4.5 6.00\npub => 3\nsize => 3\nrec => 1\nadv => 111 22 3456 .76\npub => 1\nsize => 2</pre>\n\n<p>Chris</p>\n"
},
{
"answer_id": 275163,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>The config file format is sub-optimal, shall we say. That is, there are easier formats to parse and understand. [<em>Added</em>: but the format is already defined by another program. Perl is flexible enough to deal with that.]</p>\n\n<p>Your code slurps the file when there is no real need.</p>\n\n<p>Your code only pays attention to the last line of data in the file (as Chris Charley noted while I was typing this up).</p>\n\n<p>You also have not allowed for comment lines or blank lines - both are a good idea in any config file and they are easy to support. [<em>Added</em>: again, with the pre-defined format, this is barely relevant, but when you design your own files, do remember it.]</p>\n\n<p>Here's an adaptation of your function into somewhat more idiomatic Perl.</p>\n\n<pre><code>#!/bin/perl -w\nuse strict;\nuse constant debug => 0;\n\nsub readConfigFile()\n{\n my %CONFIG;\n open(CON_FILE, \"config\") or die \"failed to open file ($!)\\n\";\n\n while (my $line = <CON_FILE>)\n {\n chomp $line;\n $line =~ s/#.*//; # Remove comments\n next if $line =~ /^\\s*$/; # Ignore blank lines\n\n foreach my $field (split(/>/, $line))\n {\n my @arr = split(/=/, $field);\n $CONFIG{$arr[0]} = $arr[1];\n print \":: $arr[0] => $arr[1]\\n\" if debug;\n }\n }\n close(CON_FILE);\n\n while (my($k,$v) = each %CONFIG)\n {\n print \"$k => $v\\n\";\n }\n return %CONFIG;\n}\n\nreadConfigFile; # Ignores returned hash\n</code></pre>\n\n<p>Now, you need to explain more clearly what the structure of the last field is, and why you have an 'ip' field without the key=value notation. Consistency makes life easier for everybody. You also need to think about how multiple lines are supposed to be handled. And I'd explore using a more orthodox notation, such as:</p>\n\n<pre><code>pub=3;rec=0;size=3;adv=(1234,123,4.5);ip=6.00\n</code></pre>\n\n<p>Colon or semi-colon as delimiters are fairly conventional; parentheses around comma separated items in a list are not an outrageous convention. Consistency is paramount. Emerson said \"A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines\", but consistency in Computer Science is a great benefit to everyone.</p>\n"
},
{
"answer_id": 277717,
"author": "Altreus",
"author_id": 2386199,
"author_profile": "https://Stackoverflow.com/users/2386199",
"pm_score": 1,
"selected": false,
"text": "<p>The below assumes the delimiter is guaranteed to be a >, and there is no chance of that appearing in the data.</p>\n\n<p>I simply split each line based on '>'. The last value will contain a key=value pair, then a space, then the IP, so split this on / / exactly once (limit 2) and you get the k=v and the IP. Save the IP to the hash and keep the k=v pair in the array, then go through the array and split k=v on '='.</p>\n\n<p>Fill in the hashref and push it to your higher-scoped array. This will then contain your hashrefs when finished.</p>\n\n<p>(Having loaded the config into an array)</p>\n\n<pre><code>my @hashes;\n\nfor my $line (@config) {\n my $hash; # config line will end up here\n\n my @pairs = split />/, $line;\n\n # Do the ip first. Split the last element of @pairs and put the second half into the\n # hash, overwriting the element with the first half at the same time.\n # This means we don't have to do anything special with the for loop below.\n ($pairs[-1], $hash->{ip}) = (split / /, $pairs[-1], 2);\n\n for (@pairs) {\n my ($k, $v) = split /=/;\n $hash->{$k} = $v;\n }\n\n push @hashes, $hash;\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
I wish to convert a single string with multiple delimiters into a key=>value hash structure. Is there a simple way to accomplish this? My current implementation is:
```
sub readConfigFile() {
my %CONFIG;
my $index = 0;
open(CON_FILE, "config");
my @lines = <CON_FILE>;
close(CON_FILE);
my @array = split(/>/, $lines[0]);
my $total = @array;
while($index < $total) {
my @arr = split(/=/, $array[$index]);
chomp($arr[1]);
$CONFIG{$arr[0]} = $arr[1];
$index = $index + 1;
}
while ( ($k,$v) = each %CONFIG ) {
print "$k => $v\n";
}
return;
}
```
where 'config' contains:
```
pub=3>rec=0>size=3>adv=1234 123 4.5 6.00
pub=1>rec=1>size=2>adv=111 22 3456 .76
```
The last digits need to be also removed, and kept in a separate key=>value pair whose name can be 'ip'. (I have not been able to accomplish this without making the code too lengthy and complicated).
|
What is your configuration data structure supposed to look like? So far the solutions only record the last line because they are stomping on the same hash keys every time they add a record.
Here's something that might get you closer, but you still need to figure out what the data structure should be.
* I pass in the file handle as an argument so my subroutine isn't tied to a particular way of getting the data. It can be from a file, a string, a socket, or even the stuff below **DATA** in this case.
* Instead of fixing things up after I parse the string, I fix the string to have the "ip" element before I parse it. Once I do that, the "ip" element isn't a special case and it's just a matter of a double split. This is a very important technique to save a lot of work and code.
* I create a hash reference inside the subroutine and return that hash reference when I'm done. I don't need a global variable. :)
```
use warnings;
use strict;
use Data::Dumper;
readConfigFile( \*DATA );
sub readConfigFile
{
my( $fh ) = shift;
my $hash = {};
while( <$fh> )
{
chomp;
s/\s+(\d*\.\d+)$/>ip=$1/;
$hash->{ $. } = { map { split /=/ } split />/ };
}
return $hash;
}
my $hash = readConfigFile( \*DATA );
print Dumper( $hash );
__DATA__
pub=3>rec=0>size=3>adv=1234 123 4.5 6.00
pub=1>rec=1>size=2>adv=111 22 3456 .76
```
This gives you a data structure where each line is a separate record. I choose the line number of the record (`$.`) as the top-level key, but you can use anything that you like.
```
$VAR1 = {
'1' => {
'ip' => '6.00',
'rec' => '0',
'adv' => '1234 123 4.5',
'pub' => '3',
'size' => '3'
},
'2' => {
'ip' => '.76',
'rec' => '1',
'adv' => '111 22 3456',
'pub' => '1',
'size' => '2'
}
};
```
If that's not the structure you want, show us what you'd like to end up with and we can adjust our answers.
|
275,039 |
<p>I got an image with which links to another page using <code><a href="..."> <img ...> </a></code>.</p>
<p>How can I make it make a post like if it was a button <code><input type="submit"...></code>?</p>
|
[
{
"answer_id": 275047,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://webdesign.about.com/od/htmltags/p/bltags_inputimg.htm\" rel=\"noreferrer\">input type=image</a> will do it for you.</p>\n"
},
{
"answer_id": 275048,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 3,
"selected": false,
"text": "<p>Untested / could be better:</p>\n\n<pre><code><form action=\"page-you're-submitting-to.html\" method=\"POST\">\n <a href=\"#\" onclick=\"document.forms[0].submit();return false;\"><img src=\"whatever.jpg\" /></a>\n</form>\n</code></pre>\n"
},
{
"answer_id": 275049,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": false,
"text": "<p>It looks like you're trying to use an image to submit a form... in that case use\n<code><input type=\"image\" src=\"...\"></code></p>\n\n<p>If you really want to use an anchor then you have to use javascript:</p>\n\n<p><code><a href=\"#\" onclick=\"document.forms['myFormName'].submit(); return false;\">...</a></code></p>\n"
},
{
"answer_id": 275051,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 6,
"selected": true,
"text": "<pre><code><input type=\"image\" name=\"your_image_name\" src=\"your_image_url.png\" />\n</code></pre>\n\n<p>This will send the <code>your_image_name.x</code> and <code>your_image_name.y</code> values as it submits the form, which are the x and y coordinates of the position the user clicked the image.</p>\n"
},
{
"answer_id": 275052,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>Something <a href=\"http://www.bsohq.fr/static/development/css_submit.html?value=\" rel=\"nofollow noreferrer\">like this page</a> ?</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>BSO Communication</title>\n\n<style type=\"text/css\">\n.submit {\n border : 0;\n background : url(ok.gif) left top no-repeat;\n height : 24px;\n width : 24px;\n cursor : pointer;\n text-indent : -9999px;\n}\nhtml:first-child .submit {\n padding-left : 1000px;\n}\n</style>\n<!--[if IE]>\n<style type=\"text/css\">\n.submit {\n text-indent : 0;\n color : expression(this.value = '');\n}\n</style>\n<![endif]-->\n</head>\n\n<body>\n <h1>Display input submit as image with CSS</h1>\n\n <p>Take a look at <a href=\"/2007/07/26/afficher-un-input-submit-comme-une-image/\">the related article</a> (in french).</p>\n <form action=\"\" method=\"get\">\n <fieldset>\n <legend>Some form</legend>\n <p class=\"field\">\n <label for=\"input\">Some value</label>\n\n <input type=\"text\" id=\"input\" name=\"value\" />\n <input type=\"submit\" class=\"submit\" />\n </p>\n </fieldset>\n </form>\n\n <hr />\n <p>This page is part of the <a href=\"http://www.bsohq.fr\">BSO Communication blog</a>.</p>\n\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 277784,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 1,
"selected": false,
"text": "<p>Dont forget the \"BUTTON\" element wich can handle some more HTML inside...</p>\n"
},
{
"answer_id": 2593346,
"author": "Jiky1",
"author_id": 311080,
"author_profile": "https://Stackoverflow.com/users/311080",
"pm_score": 3,
"selected": false,
"text": "<pre><code> <html>\n\n <?php\n\n echo $_POST['c'].\" | \".$_POST['d'].\" | \".$_POST['e'];\n\n ?>\n\n <form action=\"test.php\" method=\"POST\">\n <input type=\"hidden\" name=\"c\" value=\"toto98\">\n <input type=\"hidden\" name=\"d\" value=\"toto97\">\n <input type=\"hidden\" name=\"e\" value=\"toto aaaaaaaaaaaaaaaaaaaa\">\n\n <a href=\"\" onclick=\"document.forms[0].submit();return false;\">Click</a> \n </form>\n\n</html>\n\n\nSo easy.\n\n\n\n\nSo easy.\n</code></pre>\n"
},
{
"answer_id": 7997472,
"author": "Paulius Zaliaduonis",
"author_id": 314454,
"author_profile": "https://Stackoverflow.com/users/314454",
"pm_score": 7,
"selected": false,
"text": "<p>More generic approatch using <strong><a href=\"http://jquery.com/\" rel=\"noreferrer\">JQuery</a></strong> library <a href=\"http://api.jquery.com/closest/\" rel=\"noreferrer\">closest</a>() and <a href=\"http://api.jquery.com/submit/\" rel=\"noreferrer\">submit</a>() buttons.\nHere you do not have to specify whitch form you want to submit, submits the form it is in.</p>\n\n<pre><code><a href=\"#\" onclick=\"$(this).closest('form').submit()\">Submit Link</a>\n</code></pre>\n"
},
{
"answer_id": 14408553,
"author": "Kateriana",
"author_id": 1991753,
"author_profile": "https://Stackoverflow.com/users/1991753",
"pm_score": 0,
"selected": false,
"text": "<p>We replace the submit button with this all the time on forms:</p>\n\n<pre><code><form method=\"post\" action=\"whatever.asp\">\n<input type=...n\n\n<input type=\"image\" name=\"Submit\" src=\"/graphics/continue.gif\" align=\"middle\" border=\"0\" alt=\"Continue\">\n</form>\n</code></pre>\n\n<p>Clicking the image submits the form. Hope that helps!</p>\n"
},
{
"answer_id": 15088641,
"author": "Grit",
"author_id": 1353668,
"author_profile": "https://Stackoverflow.com/users/1353668",
"pm_score": 2,
"selected": false,
"text": "<p>What might be a handy addition to this is the possibility to change the post-url from the extra button so you can post to different urls with different buttons. This can be achieved by setting the form 'action' property. Here's the code for that when using jQuery:</p>\n\n<pre><code>$('#[href button name]').click(function(e) {\n e.preventDefault();\n $('#[form name]').attr('action', 'alternateurl.php');\n $('#[form name]').submit();\n});\n</code></pre>\n\n<p>The action-attribute has some issues with older jQuery versions, but on the latest you'll be good to go.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
I got an image with which links to another page using `<a href="..."> <img ...> </a>`.
How can I make it make a post like if it was a button `<input type="submit"...>`?
|
```
<input type="image" name="your_image_name" src="your_image_url.png" />
```
This will send the `your_image_name.x` and `your_image_name.y` values as it submits the form, which are the x and y coordinates of the position the user clicked the image.
|
275,063 |
<p>I would like to be able to set "Extend my Windows desktop onto this monitor" via code. A PowerShell script would be ideal. WMI seems the way forward but I have zero knowledge in WMI.</p>
|
[
{
"answer_id": 275123,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>One first possible solution is... through the GUI (but without user interaction)</p>\n\n<p><a href=\"https://web.archive.org/web/1/http://techrepublic%2ecom%2ecom/5208-6230-0.html?forumID=101&threadID=220003&messageID=2219887\" rel=\"nofollow noreferrer\">VB script</a> (also <a href=\"http://robbieallen.com/2006/08/extending-desktop-via-script/\" rel=\"nofollow noreferrer\">described here</a> but in <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">Autoit</a> language):</p>\n\n<pre><code>Option Explicit\nDim WshShell, Dummy, Splash\n\nOn Error Resume Next\n\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\n\n'Main\nCall DoIt\nWScript.Quit\n\nSub DoIt\nwshshell.Run(\"%systemroot%\\system32\\control.exe desk.cpl,@0,3\")\n\n' Give Display Properties time to load\nWScript.Sleep 1000\nWshShell.SendKeys \"2\"\nWScript.Sleep 10\nWshShell.SendKeys \"%E\"\nWScript.Sleep 500\nWshShell.SendKeys \"%A\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{ENTER}\"\nEnd Sub 'DoIt\n</code></pre>\n\n<p>In Autoit, that would be:</p>\n\n<pre><code>;\n; — toggle-screen.au3\n;\n\n; exec cpanel app `display settings`\nRun(”C:\\WINDOWS\\system32\\control.exe desk.cpl,@0,3?”)\n\n; wait for window to be active\nWinWaitActive(”Display Settings”)\n\n; select 2nd display\nSend(”{TAB}”)\nSend(”{DOWN}”)\n\n; work back to the ‘extend desktop’ control\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\n\n; toggle ‘extend desktop’ control and apply\nSend(”{SPACE}”)\nSend(”{ENTER}”)\n\n; wait for window to be active\nWinWaitActive(”Display Settings”)\n\n; accept\nSend(”{TAB}”)\nSend(”{ENTER}”)\n\n;\n; — E.O.F.\n; \n</code></pre>\n"
},
{
"answer_id": 275597,
"author": "halr9000",
"author_id": 6637,
"author_profile": "https://Stackoverflow.com/users/6637",
"pm_score": 2,
"selected": false,
"text": "<p>This sort of operation is not directly accessible from PowerShell in the sense that there is not a .NET interface to these settings. A lot of core OS stuff is unmanaged code which can only be manipulated via win32 API calls. While you may be on to something with WMI, I searched for a while and wasn't able to find a satisfactory WMI class which is able to manipulate this setting.</p>\n\n<p>The next step would be to modify the registry directly. It looks like the setting lies under HKLM:\\system\\CurrentControlSet\\control\\video--somewhere. I believe it's the one called \"Attach.ToDesktop\".</p>\n\n<p>This is a partial solution, so I'm marking as community wiki answer. </p>\n\n<p>I'm not certain this is the right registry key, and I don't have a system on which I can test multi-monitor at the moment. The purpose of this is to determine which is the primary controller, and then it outputs the value of the Attach.ToDesktop key.</p>\n\n<pre><code>param ( \n $ControllerName = \"$( throw 'ControllerName is a mandatory parameter' )\"\n)\n$regPath = \"HKLM:\\system\\CurrentControlSet\\control\\video\"\n$devDescStr = \"Device Description\"\n\nSet-Location -path $regPath\n$regSubKey = Get-ChildItem -recurse -include 0000\n$devDescProperty = $regSubKey | Get-ItemProperty -name $devDescStr -erroraction SilentlyContinue \n$priDescProperty = $devDescProperty | Where-Object { $_.$devDescStr -match $ControllerName }\nSet-Location -path $priDescProperty.PSPath\nGet-ItemProperty -path . -name \"Attach.ToDesktop\"\n</code></pre>\n"
},
{
"answer_id": 891694,
"author": "David Resnick",
"author_id": 3904,
"author_profile": "https://Stackoverflow.com/users/3904",
"pm_score": 0,
"selected": false,
"text": "<p>I had to made some small modifications to get VonC's script to work on my machine. It is now a little more generic.</p>\n\n<pre><code>;\n; — toggle-screen2.au3\n;\n\n#include <WinAPI.au3>\n; exec cpanel app `display settings`\nRun(_WinAPI_ExpandEnvironmentStrings(\"%windir%\") & \"\\system32\\control.exe desk.cpl,@0,3?\")\n\n; wait for window to be active\nWinWaitActive(\"Display Properties\")\n\n; select 2nd display\nSend(\"!d\")\nSend(\"{DOWN}\")\n\n; toggle the ‘extend desktop’ checkbox\nSend(\"!e\")\n\n; close the dialog\nSend(\"{ENTER}\")\n</code></pre>\n"
},
{
"answer_id": 2462742,
"author": "loraderon",
"author_id": 22092,
"author_profile": "https://Stackoverflow.com/users/22092",
"pm_score": 3,
"selected": false,
"text": "<p>I've made a cleaner version that does not use sendkeys.</p>\n\n<pre><code>public class DisplayHelper\n{\n [DllImport(\"user32.dll\")]\n static extern DISP_CHANGE ChangeDisplaySettings(uint lpDevMode, uint dwflags);\n [DllImport(\"user32.dll\")]\n static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);\n\n enum DISP_CHANGE : int\n {\n Successful = 0,\n Restart = 1,\n Failed = -1,\n BadMode = -2,\n NotUpdated = -3,\n BadFlags = -4,\n BadParam = -5,\n BadDualView = -1\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n struct DISPLAY_DEVICE\n {\n [MarshalAs(UnmanagedType.U4)]\n public int cb;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n public string DeviceName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceString;\n [MarshalAs(UnmanagedType.U4)]\n public DisplayDeviceStateFlags StateFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceKey;\n }\n\n [Flags()]\n enum DisplayDeviceStateFlags : int\n {\n /// <summary>The device is part of the desktop.</summary>\n AttachedToDesktop = 0x1,\n MultiDriver = 0x2,\n /// <summary>The device is part of the desktop.</summary>\n PrimaryDevice = 0x4,\n /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>\n MirroringDriver = 0x8,\n /// <summary>The device is VGA compatible.</summary>\n VGACompatible = 0x16,\n /// <summary>The device is removable; it cannot be the primary display.</summary>\n Removable = 0x20,\n /// <summary>The device has more display modes than its output devices support.</summary>\n ModesPruned = 0x8000000,\n Remote = 0x4000000,\n Disconnect = 0x2000000\n }\n\n public static void EnableSecondaryDisplay()\n {\n var secondaryIndex = 1;\n var secondary = GetDisplayDevice(secondaryIndex);\n var id = secondary.DeviceKey.Split('\\\\')[7];\n\n using (var key = Registry.CurrentConfig.OpenSubKey(string.Format(@\"System\\CurrentControlSet\\Control\\VIDEO\\{0}\", id), true))\n {\n using (var subkey = key.CreateSubKey(\"000\" + secondaryIndex))\n {\n subkey.SetValue(\"Attach.ToDesktop\", 1, RegistryValueKind.DWord);\n subkey.SetValue(\"Attach.RelativeX\", 1024, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.XResolution\", 1024, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.YResolution\", 768, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.BitsPerPel\", 32, RegistryValueKind.DWord);\n }\n }\n\n ChangeDisplaySettings(0, 0);\n }\n\n private static DISPLAY_DEVICE GetDisplayDevice(int id)\n {\n var d = new DISPLAY_DEVICE();\n d.cb = Marshal.SizeOf(d);\n if (!EnumDisplayDevices(null, (uint)id, ref d, 0))\n throw new NotSupportedException(\"Could not find a monitor with id \" + id);\n return d;\n }\n}\n</code></pre>\n\n<p>I have only tested this on a newly installed computer. </p>\n"
},
{
"answer_id": 3481380,
"author": "MemphiZ",
"author_id": 130465,
"author_profile": "https://Stackoverflow.com/users/130465",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my AutoIt-Script for switching monitors as my ATI graphics card doesn't allow me to have 3 monitors active at the same time. I have 2 monitors attached and a TV. This script is doing what VonC's script does but in a more effective and faster way.</p>\n\n<pre><code>Run(\"C:\\WINDOWS\\system32\\control.exe desk.cpl\", \"C:\\Windows\\system32\\\")\nWinWait(\"Screen Resolution\")\nControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"SAMSUNG\")\n\nif (ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"GetCurrentSelection\", \"\") = \"Disconnect this display\") Then\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"2\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"3\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"0\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"1\")\n ControlClick(\"Screen Resolution\", \"\", \"Button4\")\n WinWait(\"Display Settings\")\n ControlClick(\"Display Settings\", \"\", \"Button1\")\nElse\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"3\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"2\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"1\")\n ControlClick(\"Screen Resolution\", \"\", \"Button4\")\n WinWait(\"Display Settings\")\n ControlClick(\"Display Settings\", \"\", \"Button1\")\nEndIf\n</code></pre>\n\n<p>Just replace \"SAMSUNG\" with your third monitors/tvs name and you're all set!\nAs you surely know you can convert it to an executable which runs on any machine even without AutoIt installed. </p>\n"
},
{
"answer_id": 25094871,
"author": "Communicative Algebra",
"author_id": 3611932,
"author_profile": "https://Stackoverflow.com/users/3611932",
"pm_score": 6,
"selected": false,
"text": "<p>Windows 7, 8 and 10 are supposed to come with a small program that does exactly this: displayswitch.exe. <a href=\"http://jeffwouters.nl/index.php/2012/06/switch-your-display-through-the-command-line/\" rel=\"noreferrer\">This page</a> lists the following parameters:</p>\n<pre><code>displayswitch.exe /internal Disconnect projector (same as "Show only on 1" from the Display Properties dialog)\ndisplayswitch.exe /clone Duplicate screen\ndisplayswitch.exe /extend Extend screen\ndisplayswitch.exe /external Projector only (disconnect local) (same as "Show only on 2" from the Display Properties dialog)\n</code></pre>\n<p>For a one-click solution to the problem posed, simply create a *.bat-file containing the single line</p>\n<pre><code>call displayswitch.exe /extend\n</code></pre>\n<p>and save it to your desktop.</p>\n<p>[I tested this on Windows 8.1, and it has been confirmed to work on Windows 10.]</p>\n"
},
{
"answer_id": 49906724,
"author": "Bong Gutz",
"author_id": 9666019,
"author_profile": "https://Stackoverflow.com/users/9666019",
"pm_score": 2,
"selected": false,
"text": "<p>2 lines in autohotkey</p>\n\n<p>2nd display on:</p>\n\n<pre><code>RunWait C:\\Windows\\System32\\DisplaySwitch.exe /extend\n</code></pre>\n\n<p>2nd display off:</p>\n\n<pre><code>RunWait C:\\Windows\\System32\\DisplaySwitch.exe /internal\n</code></pre>\n\n<p>-</p>\n\n<pre><code>#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.\n; #Warn ; Enable warnings to assist with detecting common errors.\nSendMode Input ; Recommended for new scripts due to its superior speed and reliability.\n#Persistent \n\nAny1stKeyUWantToTurnOn::RunWait C:\\Windows\\System32\\DisplaySwitch.exe /extend\nAny2stKeyUWantToTurnOff::RunWait C:\\Windows\\System32\\DisplaySwitch.exe /internal\n</code></pre>\n\n<p>or</p>\n\n<p>You can check and try out my tool on <a href=\"https://github.com/BNK3R-Boy/DisplaySwitch\" rel=\"nofollow noreferrer\">github / BNK3R-Boy / DisplaySwitch</a>. I published it right now.</p>\n"
},
{
"answer_id": 51522836,
"author": "user3237231",
"author_id": 3237231,
"author_profile": "https://Stackoverflow.com/users/3237231",
"pm_score": 0,
"selected": false,
"text": "<p>windows key + P button will do the same thing</p>\n"
},
{
"answer_id": 69096335,
"author": "askvictor",
"author_id": 224511,
"author_profile": "https://Stackoverflow.com/users/224511",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another solution, in C# (via <a href=\"https://stackoverflow.com/questions/16326932/how-to-set-primary-monitor-for-windows-7-in-c-sharp\">how to set primary monitor for Windows-7, in C#</a>):</p>\n<pre><code>[Flags]\npublic enum SetDisplayConfigFlags : uint\n{\n SDC_TOPOLOGY_INTERNAL = 0x00000001,\n SDC_TOPOLOGY_CLONE = 0x00000002,\n SDC_TOPOLOGY_EXTEND = 0x00000004,\n SDC_TOPOLOGY_EXTERNAL = 0x00000008,\n SDC_APPLY = 0x00000080\n}\n\n[DllImport("user32.dll", CharSet = CharSet.Unicode)]\nprivate static extern long SetDisplayConfig(uint numPathArrayElements,\n IntPtr pathArray, uint numModeArrayElements, IntPtr modeArray, SetDisplayConfigFlags flags);\n\nstatic void CloneDisplays() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_CLONE | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void ExtendDisplays() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTEND | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void ExternalDisplay() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTERNAL | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void InternalDisplay() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_INTERNAL | SetDisplayConfigFlags.SDC_APPLY);\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176626/"
] |
I would like to be able to set "Extend my Windows desktop onto this monitor" via code. A PowerShell script would be ideal. WMI seems the way forward but I have zero knowledge in WMI.
|
Windows 7, 8 and 10 are supposed to come with a small program that does exactly this: displayswitch.exe. [This page](http://jeffwouters.nl/index.php/2012/06/switch-your-display-through-the-command-line/) lists the following parameters:
```
displayswitch.exe /internal Disconnect projector (same as "Show only on 1" from the Display Properties dialog)
displayswitch.exe /clone Duplicate screen
displayswitch.exe /extend Extend screen
displayswitch.exe /external Projector only (disconnect local) (same as "Show only on 2" from the Display Properties dialog)
```
For a one-click solution to the problem posed, simply create a \*.bat-file containing the single line
```
call displayswitch.exe /extend
```
and save it to your desktop.
[I tested this on Windows 8.1, and it has been confirmed to work on Windows 10.]
|
275,064 |
<p>I read a properties-file at the webapplication startup phase (contextInitialized()) and I started to think about how to make these settings 'visible' to the servlets. Do I need to loop through the keys and add each and every one to the context, like this</p>
<pre><code>Iterator i = settings.keySet().iterator();
while (i.hasNext()) {
key = (String) i.next();
value = (String) settings.get(key);
context.setAttribute(key, value);
}
</code></pre>
<p>or are there better methods?</p>
<p>Thank you!</p>
<p>/Adam</p>
|
[
{
"answer_id": 275065,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 1,
"selected": false,
"text": "<p>Have you considered the possibility of defining the settings in web.xml?</p>\n\n<p>Also, if that's not possible, use generics if possible:</p>\n\n<pre><code>String key = null;\nIterator<String> i = settings.keySet().iterator();\nwhile (i.hasNext())\n context.setAttribute(key = i.next(), settings.get(key));\n</code></pre>\n"
},
{
"answer_id": 275256,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 0,
"selected": false,
"text": "<p>What about using the JNDI context. JNDI is a more common way to pass properties to a webapp.</p>\n\n<p>Any Properties may be specified in the META-INF/context.xml for tomcat or any application specific setup.</p>\n"
},
{
"answer_id": 276498,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": false,
"text": "<p>why not store the entire contents in your servlet context?</p>\n\n<pre><code>context.setAttribute(\"mySettings\", settings);\n</code></pre>\n\n<p>setAttribute's signature is:</p>\n\n<pre><code>public void setAttribute(String name, Object object)\n</code></pre>\n"
},
{
"answer_id": 276582,
"author": "Adam Asham",
"author_id": 31518,
"author_profile": "https://Stackoverflow.com/users/31518",
"pm_score": 0,
"selected": false,
"text": "<p>It's something that I have contemplated, setting the entire properties object as a context attribute. </p>\n\n<p>If I do not go this route, are there any guidelines for how to name these attributes or do you feel that \"application.settings\" or \"myBlog.settings\"? How do <strong>you</strong> group keys? Would this be okay: </p>\n\n<pre><code>application.module1.color=black\napplication.module1.font=arial\n</code></pre>\n\n<p>I feel, in a way, that it could become a burden to maintain such an application where the property keys are spread throughout the code? Should another developer rename a property in the properties file, we'll know only when <em>running</em> the application (if/when/what referenced the old key). Right?</p>\n\n<p>I'll have to lookup JNDI.</p>\n"
},
{
"answer_id": 411415,
"author": "Adam Asham",
"author_id": 31518,
"author_profile": "https://Stackoverflow.com/users/31518",
"pm_score": 1,
"selected": false,
"text": "<p>I've been toying with an idea:</p>\n\n<p>In the context initialized method, I've planned to create just one global object for the settings. Much like toolkit proposed. But instead of setting context attributes for each key/attribute/setting, would it be a terrible idea to add a settings container/wrapper object? I'm thinking this class would be responsible for holding (static?) classes of module settings. This way I can get typed references like so</p>\n\n<pre><code>//ExampleServlet.java\nSettings settings = (Settings)context.getAttribute(\"application.settings\");\n\nString color = settings.getModule1().getColor();\nString font = settings.getModule1().getFont();\n\nint blogs = settings.getModule2().getActiveBlogCount();\n</code></pre>\n\n<p>Throughout the code I'll have to remember only <strong>one</strong> attribute key, the one for the entire settings container. Less risk of typos which could cause rumtime exceptions!\nIt will also make it easy to rename attributes.</p>\n\n<p>What do you think?</p>\n\n<p>/Adam</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31518/"
] |
I read a properties-file at the webapplication startup phase (contextInitialized()) and I started to think about how to make these settings 'visible' to the servlets. Do I need to loop through the keys and add each and every one to the context, like this
```
Iterator i = settings.keySet().iterator();
while (i.hasNext()) {
key = (String) i.next();
value = (String) settings.get(key);
context.setAttribute(key, value);
}
```
or are there better methods?
Thank you!
/Adam
|
why not store the entire contents in your servlet context?
```
context.setAttribute("mySettings", settings);
```
setAttribute's signature is:
```
public void setAttribute(String name, Object object)
```
|
275,073 |
<p>I have just noticed that a multidimensional array in C# does not implement <code>IEnumerable<T></code>, while it does implement <code>IEnumerable</code>. For single-dimensional arrays, both <code>IEnumerable<T></code> and <code>IEnumerable</code> are implemented.</p>
<p>Why this difference? If a multi-dimensional array is <code>IEnumerable</code>, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use <code>Cast<T></code> or similar; so I can definitely see the an argument for making multidimensional arrays implement <code>IEnumerable<T></code>.</p>
<p>To clarify my question in code, I would expect the following code to print <code>true</code> four times, while it actually prints <code>true</code>, <code>false</code>, <code>true</code>, <code>true</code>:</p>
<pre><code>int[] singleDimensionArray = new int[10];
int[,] multiDimensional = new int[10, 10];
Debug.WriteLine(singleDimensionArray is IEnumerable<int>);
Debug.WriteLine(multiDimensional is IEnumerable<int>);
Debug.WriteLine(singleDimensionArray is IEnumerable);
Debug.WriteLine(multiDimensional is IEnumerable);
</code></pre>
|
[
{
"answer_id": 275107,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<p>Jagged arrays don't support <code>IEnumerable<int></code> either, because multidimensional structures aren't really an array of a type, they are an array of an array of a type:</p>\n\n<pre><code>int[] singleDimensionArray = new int[10];\nint[][] multiJagged = new int[10][];\n\nDebug.WriteLine(singleDimensionArray is IEnumerable<int>);\nDebug.WriteLine(multiJagged is IEnumerable<int[]>);\nDebug.WriteLine(singleDimensionArray is IEnumerable);\nDebug.WriteLine(multiJagged is IEnumerable);\n</code></pre>\n\n<p>Prints true, true, true, true.</p>\n\n<p><strong>Note</strong>: <code>int[,]</code> isn't an <code>IEnumerable<int[]></code>, that's for the reasons specified in the other answer, namely there's no generic way to know which dimension to iterate over. With jagged arrays, there isn't as much room for interpretation because the syntax is pretty clear about it being an array of arrays.</p>\n"
},
{
"answer_id": 275129,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>The CLR has two different kinds of arrays: <em>vectors</em> which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.</p>\n\n<p>From section 8.9.1 of the CLI spec: </p>\n\n<blockquote>\n <p>Additionally, a created vector with\n element type T, implements the\n interface\n <code>System.Collections.Generic.IList<U></code>\n (§8.7), where U := T.</p>\n</blockquote>\n\n<p>I have to say it seems pretty weird to me. Given that it already implements <code>IEnumerable</code> I don't see why it shouldn't implement <code>IEnumerable<T></code>. It wouldn't make as much sense to implement <code>IList<T></code>, but the simple generic interface would be fine.</p>\n\n<p>If you want this, you could either call <code>Cast<T></code> (if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.</p>\n"
},
{
"answer_id": 1183153,
"author": "Jader Dias",
"author_id": 48465,
"author_profile": "https://Stackoverflow.com/users/48465",
"pm_score": 4,
"selected": false,
"text": "<p>There is a workaround: you can convert any multidimensional array to an IEnumerable</p>\n\n<pre><code>public static class ArrayExtensions\n{\n public static IEnumerable<T> ToEnumerable<T>(this Array target)\n {\n foreach (var item in target)\n yield return (T)item;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27322593,
"author": "PEDRO ACOSTA MOLINA",
"author_id": 4329858,
"author_profile": "https://Stackoverflow.com/users/4329858",
"pm_score": 0,
"selected": false,
"text": "<p>Think inversely. The 2d array already exists. Just enumerate it. Create a 2d array with score and place of an initial array or marks, including duplicate values.</p>\n\n<pre><code>int[] secondmarks = {20, 15, 31, 34, 35, 50, 40, 90, 99, 100, 20};\n\nIEnumerable<int> finallist = secondmarks.OrderByDescending(c => c);\n\nint[,] orderedMarks = new int[2, finallist.Count()];\n\nEnumerable.Range(0, finallist.Count()).ToList().ForEach(k => {orderedMarks[0, k] = (int) finallist.Skip(k).Take(1).Average();\norderedMarks[1, k] = k + 1;}); \n\nEnumerable.Range(0, finallist.Count()).Select(m => new {Score = orderedMarks[0, m], Place = orderedMarks[1, m]}).Dump();\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Score Place\n\n100 1\n99 2 \n90 3 \n50 4 \n40 5 \n35 6 \n34 7 \n31 8 \n20 9 \n20 10 \n15 11 \n</code></pre>\n"
},
{
"answer_id": 46997301,
"author": "Sergey Teplyakov",
"author_id": 250833,
"author_profile": "https://Stackoverflow.com/users/250833",
"pm_score": 4,
"selected": false,
"text": "<p>Zero bound single dimensional arrays implements both <code>IEnumerable</code> and <code>IEnumerable<T></code>, but multi-dimensional arrays, unfortunately, implements only <code>IEnumerable</code>. The \"workaround\" by @Jader Dias indeed converts a multidimensional array to <code>IEnumerable<T></code> but with a huge cost: every element of an array will be boxed.</p>\n\n<p>Here is a version that won't cause boxing for every element:</p>\n\n<pre><code>public static class ArrayExtensions\n{\n public static IEnumerable<T> ToEnumerable<T>(this T[,] target)\n {\n foreach (var item in target)\n yield return item;\n }\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13627/"
] |
I have just noticed that a multidimensional array in C# does not implement `IEnumerable<T>`, while it does implement `IEnumerable`. For single-dimensional arrays, both `IEnumerable<T>` and `IEnumerable` are implemented.
Why this difference? If a multi-dimensional array is `IEnumerable`, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use `Cast<T>` or similar; so I can definitely see the an argument for making multidimensional arrays implement `IEnumerable<T>`.
To clarify my question in code, I would expect the following code to print `true` four times, while it actually prints `true`, `false`, `true`, `true`:
```
int[] singleDimensionArray = new int[10];
int[,] multiDimensional = new int[10, 10];
Debug.WriteLine(singleDimensionArray is IEnumerable<int>);
Debug.WriteLine(multiDimensional is IEnumerable<int>);
Debug.WriteLine(singleDimensionArray is IEnumerable);
Debug.WriteLine(multiDimensional is IEnumerable);
```
|
The CLR has two different kinds of arrays: *vectors* which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.
From section 8.9.1 of the CLI spec:
>
> Additionally, a created vector with
> element type T, implements the
> interface
> `System.Collections.Generic.IList<U>`
> (§8.7), where U := T.
>
>
>
I have to say it seems pretty weird to me. Given that it already implements `IEnumerable` I don't see why it shouldn't implement `IEnumerable<T>`. It wouldn't make as much sense to implement `IList<T>`, but the simple generic interface would be fine.
If you want this, you could either call `Cast<T>` (if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.
|
275,092 |
<p>We have a JavaScript function named "move" which does just "windows.location.href = <em>any given anchor</em>". <br/>
This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer <strong>why</strong> it doesn't work. <br/>
Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?</p>
|
[
{
"answer_id": 275102,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 6,
"selected": true,
"text": "<p>Have you tried just using </p>\n\n<pre><code>window.location = 'url';\n</code></pre>\n\n<p>In some browsers, <code>window.location.href</code> is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the <code>location</code> property on its own, that should redirect for you in all browsers.</p>\n\n<p>Mozilla's documentation has a pretty detailed explanation of how to use the <code>window.location</code> object.</p>\n\n<p><a href=\"https://developer.mozilla.org/en/DOM/window.location\" rel=\"noreferrer\">https://developer.mozilla.org/en/DOM/window.location</a></p>\n"
},
{
"answer_id": 275104,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure to follow you.<br>\nI just tried: going with FF3 to <a href=\"http://www.lua.org/manual/5.1/manual.html\" rel=\"nofollow noreferrer\" title=\"Lua 5.1 Reference Manual\">Lua 5.1 Reference Manual</a> (long and with lot of anchors).<br>\nPasting <code>javascript:window.location.href=\"#2.5\"; alert(window.location.href);</code> in the address bar, I went to the right anchor and it displayed the right URL. Works also with a full URL, of course.<br>\nAlternative code: <code>javascript:(function () { window.location.href=\"#2.5\"; })();</code></p>\n\n<p>Perhaps you forgot the #. Common problem, also with image maps.</p>\n"
},
{
"answer_id": 275110,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use <code>window.location.replace</code> to jump to an anchor without register it in the browser history:</p>\n\n<p>This <a href=\"http://bytes.com/forum/thread587235.html\" rel=\"nofollow noreferrer\">article</a> illustrates how to jump to an anchor and uses href as read-only property.</p>\n\n<pre><code>function navigateNext() \n{\n if (!window.location.hash) \n {\n window.location.replace(window.location.href + unescape(\"#2\"))\n } \n else \n {\n newItem = nextItem(window.location.hash)\n if (document.getElementById(newItem)) \n {\n window.location.replace(stripHash(window.location) + \"#\" + newItem)\n } \n else \n {\n window.location.replace(stripHash(window.location) + \"#1\")\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 275192,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>window.location.href works fine in all versions of Firefox, as does document.location.href I think that there is something else in your code that is breaking things.</p>\n\n<p>drop this in a blank page, if it works, it indicates there is something else wrong on your page.</p>\n\n<pre><code><script>\n window.location.href = 'http://www.google.com/';\n</script>\n</code></pre>\n"
},
{
"answer_id": 275320,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this?</p>\n\n<pre><code>Response.Write(\"<script type='text/javaScript'> window.location = '#myAnchor'; </script>\";); \n</code></pre>\n"
},
{
"answer_id": 275360,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe it's just a typo in your post and not in your code, but it's <strong>window</strong> and not <strong>window<em>s</em></strong></p>\n"
},
{
"answer_id": 325507,
"author": "graffic",
"author_id": 15987,
"author_profile": "https://Stackoverflow.com/users/15987",
"pm_score": 2,
"selected": false,
"text": "<p>I have the same problem and I guess this is related to a <strong>click event</strong>.</p>\n\n<p>I have a function that moves the browser to a specific page. I attach that function to some click events: in a button and in a image. AlsoI execute the function when the user press escape (document onkeypress event).</p>\n\n<p>The results are that in all cases the function is called and executed, but only when there is a click the browser goes to the address I want.</p>\n\n<p><strong>Update</strong>\nI got it working! with a </p>\n\n<pre><code>setTimeout( \"location.replace('whatever.html');\", 0 );\n</code></pre>\n\n<p>I don't know why the location.replace wasn't working when the event was a keypress, but with the settimeout it works :)</p>\n\n<p><strong>Update</strong>\nReturning false after the event when you press escape makes the redirection works. If you return true or nothing the browser will not follow</p>\n"
},
{
"answer_id": 326102,
"author": "serg",
"author_id": 20128,
"author_profile": "https://Stackoverflow.com/users/20128",
"pm_score": -1,
"selected": false,
"text": "<p>Another option:</p>\n\n<pre><code>document.location.href =\"...\"\n</code></pre>\n"
},
{
"answer_id": 390162,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>window.location.hash = \"#gallery\";\n</code></pre>\n"
},
{
"answer_id": 1334836,
"author": "sprite",
"author_id": 145211,
"author_profile": "https://Stackoverflow.com/users/145211",
"pm_score": 4,
"selected": false,
"text": "<p>If you are trying to call this javascript code after an event that is followed by a callback then you must add another line to your function:</p>\n\n<pre><code>function JSNavSomewhere()\n{\n window.location.href = myUrl;\n return false;\n}\n</code></pre>\n\n<p>in your markup for the page, the control that calls this function on click must return this function's value</p>\n\n<pre><code><asp:button ........ onclick=\"return JSNavSomewhere();\" />\n</code></pre>\n\n<p>The false return value will cancel the callback and the redirection will now work. Why this works in IE? Well I guess they were thinking differently on the issue when they prioritized the redirection over the callback.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 2236750,
"author": "Ketan Mayangar",
"author_id": 270267,
"author_profile": "https://Stackoverflow.com/users/270267",
"pm_score": 0,
"selected": false,
"text": "<p>please add full javascript script tag</p>\n\n<pre><code><script type=\"text/javascript\" language=\"javascript\"></script></code></pre>\n"
},
{
"answer_id": 2497437,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You've got to add <strong>return false;</strong> after the window.location.href as mentioned above. </p>\n\n<pre><code>function thisWorks()\n{\n window.location.href = \"http://www.google.com\";\n return false;\n}\n\nfunction thisDoesNotWork()\n{\n window.location.href = \"http://www.google.com\";\n}\n</code></pre>\n"
},
{
"answer_id": 11712842,
"author": "Tom Tom",
"author_id": 1519318,
"author_profile": "https://Stackoverflow.com/users/1519318",
"pm_score": 0,
"selected": false,
"text": "<p>For reference I had the same problem.</p>\n\n<p>onclick = \"javascript: window.location('example.html');\" didn't work under FF (latest)</p>\n\n<p>I just had to rewrite to onclick = \"javascript: window.location = 'example.html';\" to get it working</p>\n"
},
{
"answer_id": 12794064,
"author": "Awal Istirdja",
"author_id": 1687851,
"author_profile": "https://Stackoverflow.com/users/1687851",
"pm_score": 0,
"selected": false,
"text": "<p>I just overcome the same problem. and the problem is not in javascript, but the href attribute on the <code><a></code> element.</p>\n\n<p>my js code</p>\n\n<pre><code>function sebelum_hapus()\n{\nvar setuju = confirm (\"Anda akan menghapus data...\")\nif (setuju)\nwindow.location = \"index.php\";\n}\n</code></pre>\n\n<p>my previous html was</p>\n\n<pre><code><a href=\"\" onClick=\"sebelum_hapus();\">Klik here</a>\n</code></pre>\n\n<p>and I update it to </p>\n\n<pre><code><a href=\"#\" onClick=\"sebelum_hapus();\">Klik here</a>\n</code></pre>\n\n<p>or remove the href attribute</p>\n\n<p>hope this helps.</p>\n"
},
{
"answer_id": 13972210,
"author": "LCJ",
"author_id": 696627,
"author_profile": "https://Stackoverflow.com/users/696627",
"pm_score": 3,
"selected": false,
"text": "<p>One observation to ensure in such a scenario</p>\n\n<p>Following will work in <code>IE</code>, but neither in <code>Chrome</code> nor in <code>Firefox</code> (the versions I tested)</p>\n\n<pre><code> window.location.href(\"http://stackoverflow.com\");\n</code></pre>\n\n<p>Following will work all the three</p>\n\n<pre><code>window.location.href = \"http://stackoverflow.com\";\n</code></pre>\n"
},
{
"answer_id": 18265689,
"author": "libra",
"author_id": 2688133,
"author_profile": "https://Stackoverflow.com/users/2688133",
"pm_score": 1,
"selected": false,
"text": "<p>sometime if you're using <strong><em>form</em></strong> to post data, this may happen.\nif you're using ajax, try to change 'form' to 'div'. \nthis will prevent the default behavior of form and do your ajax code.</p>\n"
},
{
"answer_id": 40882141,
"author": "VikasChauhan",
"author_id": 5793125,
"author_profile": "https://Stackoverflow.com/users/5793125",
"pm_score": 0,
"selected": false,
"text": "<p>window.location.assign(\"link to next page\") should work in both (chrome and firefox) browsers.</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>window.location.assign(\"link to next page\")</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34815/"
] |
We have a JavaScript function named "move" which does just "windows.location.href = *any given anchor*".
This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer **why** it doesn't work.
Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?
|
Have you tried just using
```
window.location = 'url';
```
In some browsers, `window.location.href` is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the `location` property on its own, that should redirect for you in all browsers.
Mozilla's documentation has a pretty detailed explanation of how to use the `window.location` object.
<https://developer.mozilla.org/en/DOM/window.location>
|
275,109 |
<p>I'm writing a url rewrite in django that when a person goes to <a href="http://mysite.com/urlchecker/http://www.google.com" rel="nofollow noreferrer">http://mysite.com/urlchecker/http://www.google.com</a> it sends the url: <a href="http://ww.google.com" rel="nofollow noreferrer">http://ww.google.com</a> to a view as a string variable. </p>
<p>I tried doing:</p>
<pre><code>(r'^urlchecker/(?P<url>\w+)/$', 'mysite.main.views.urlchecker'),
</code></pre>
<p>But that didn't work. Anyone know what I'm doing wrong?</p>
<p>Also, generally is there a good resource to learn regular expressions specifically for python/django?</p>
<p>Thanks guys!</p>
|
[
{
"answer_id": 275117,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 3,
"selected": true,
"text": "<p>Try this instead:</p>\n\n<p><code>(r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker'),</code></p>\n\n<p>This differs from yours in that:</p>\n\n<ul>\n<li>It will take anything after 'urlcheck/', not just \"word\" characters.</li>\n<li>It does not force the url to end in a slash.</li>\n</ul>\n"
},
{
"answer_id": 275281,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 0,
"selected": false,
"text": "<p>I just learned something while grazing the Hidden Features of Python thread.\n<a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python#143636\">Python's re compiler has a debug mode</a>! (Who knew? Well, apparently someone did :-) Anyway, it's worth a read.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I'm writing a url rewrite in django that when a person goes to <http://mysite.com/urlchecker/http://www.google.com> it sends the url: <http://ww.google.com> to a view as a string variable.
I tried doing:
```
(r'^urlchecker/(?P<url>\w+)/$', 'mysite.main.views.urlchecker'),
```
But that didn't work. Anyone know what I'm doing wrong?
Also, generally is there a good resource to learn regular expressions specifically for python/django?
Thanks guys!
|
Try this instead:
`(r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker'),`
This differs from yours in that:
* It will take anything after 'urlcheck/', not just "word" characters.
* It does not force the url to end in a slash.
|
275,120 |
<p>Given a class, <a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/views/navigator/ResourceNavigator.html" rel="noreferrer">org.eclipse.ui.views.navigator.ResourceNavigator</a> for example, how do I find out which jar file to use? I know it's in org.eclipse.ui.ide, but how would I find that out?</p>
<p><strong>Edit</strong>: Thank you to all of you who answered. Like many things, there seems to be several ways to skin this cat. I wish javadoc contained this info. So far here are the different methods:</p>
<ol>
<li><p>Without Internet, Eclipse or NetBeans:</p>
<pre><code>for f in `find . -name '*.jar'`; do echo $f && jar tvf $f | grep -i $1; done
</code></pre></li>
<li><p>If you want to find out locally using Eclipse:</p>
<ul>
<li><a href="http://www.alphaworks.ibm.com/tech/jarclassfinder" rel="noreferrer">JAR Class Finder Plug-in</a></li>
<li><a href="http://classlocator.sourceforge.net/" rel="noreferrer">Class Locator Plug-in</a></li>
</ul></li>
<li><p>If you want to find out from Internet or you do not have the jar yet:</p>
<ul>
<li><a href="http://www.jarfinder.com/" rel="noreferrer">jarFinder</a></li>
<li><a href="http://findjar.com/" rel="noreferrer">findjar.com</a></li>
</ul></li>
</ol>
|
[
{
"answer_id": 275125,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Usually, I do <code>jar -vtf foo.jar</code> to get a list of all the class files.<br>\nNot the most practical way, but handy. You can combine the result with grep, of course.</p>\n"
},
{
"answer_id": 275126,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 2,
"selected": false,
"text": "<p>Use a class/JAR locator:</p>\n\n<p><a href=\"http://classlocator.sourceforge.net/\" rel=\"nofollow noreferrer\">http://classlocator.sourceforge.net/</a></p>\n\n<p>[EDIT] It isn't obvious, even from ClassLocator's docs (!) but it seems to be an Eclipse plugin.</p>\n"
},
{
"answer_id": 275136,
"author": "pkliem",
"author_id": 20707,
"author_profile": "https://Stackoverflow.com/users/20707",
"pm_score": 5,
"selected": false,
"text": "<p>If you have the jar in your class path / project path hit CTRL-SHIFT-T and type the name ... the jar will be displayed at the bottom.</p>\n\n<p>If you haven't the class in your build path\na) put together a dummy project containing all the jars \nb) I think there is a plugin to find jars from IBM Alphaworks (but that might be kind of outdated)</p>\n"
},
{
"answer_id": 275137,
"author": "iberck",
"author_id": 34768,
"author_profile": "https://Stackoverflow.com/users/34768",
"pm_score": 2,
"selected": false,
"text": "<p>Use this: <a href=\"http://plugins.netbeans.org/PluginPortal/faces/PluginListPage.jsp?search=jarfinder\" rel=\"nofollow noreferrer\">netbeans plugin</a></p>\n\n<p>Or <a href=\"http://www.jarfinder.com/\" rel=\"nofollow noreferrer\">jarFinder</a> service</p>\n"
},
{
"answer_id": 275141,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "<p>You also have this eclipse plugin: <a href=\"http://www.alphaworks.ibm.com/tech/jarclassfinder\" rel=\"noreferrer\">jarclassfinder</a></p>\n\n<p>The user enters the name of the class not found (or the name of the class that the Java project needs to access). The plug-in will search the selected directory (and subdirectories) for JAR files containing that class.</p>\n\n<p>All results are displayed in a table in a custom view. The user can then browse this table and select the JAR file to add to his Java project's build path. The user then right-clicks on the entry in the table and, from the context menu, selects the build path to which to add it. </p>\n\n<hr>\n\n<p>Update 2013, as I mention in \"<a href=\"https://stackoverflow.com/a/1086435/6309\">searching through .jar files eclipse</a>\", it is no longer maintained, and the alternatives are sparse. </p>\n\n<p>As <a href=\"https://stackoverflow.com/users/1755242/sunleo\">sunleo</a> comments <a href=\"https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment36479092_275141\">below</a>:</p>\n\n<p><strong>with Eclipse, <kbd>Ctfl</kbd>+<kbd>Shift</kbd>+<kbd>T</kbd> remains the easiest alternative</strong> to look for a type<br>\n(with the jar name displayed in the status bar).</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/users/862268/user862268\">user862268</a> comments <a href=\"https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment60625860_275141\">below</a>:</p>\n\n<blockquote>\n <p>For mac, it is <kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>T</kbd> in Eclipse to find the class and associated jar.</p>\n</blockquote>\n"
},
{
"answer_id": 275144,
"author": "user28791",
"author_id": 28791,
"author_profile": "https://Stackoverflow.com/users/28791",
"pm_score": 3,
"selected": false,
"text": "<p>To answer the question, there is no real way to know which jar to use. Different versions will have potentially different behaviour.</p>\n\n<p>When it comes to locating a jar which contains a given class, I use:</p>\n\n<pre><code>for f in `find . -name '*.jar'`; do echo $f && jar tvf $f | grep -i $1; done\n</code></pre>\n\n<p>This will highlight any jar containing the classname passed in as a parameter in any subfolder.</p>\n\n<p>Another good way to find a class is to use <a href=\"http://www.mvnrepository.com/\" rel=\"noreferrer\">the maven repos search</a>.</p>\n"
},
{
"answer_id": 275232,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I really understand the question, but if you're looking to verify that your class is really in the jar, you can always look through the jar itself, and for that you don't need any Eclipse plugins or specialized external application.</p>\n\n<p>JAR (Java ARchive) files are nothing more than <strong>ZIP</strong> files. All you have to do is unzip the jar, or even view it using a zip-reading application. Under Windows XP, for example, this comes built into the operating system. How convenient.</p>\n\n<p>Hope this helped...</p>\n\n<p>Yuval =8-)</p>\n"
},
{
"answer_id": 275247,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://findjar.com/\" rel=\"nofollow noreferrer\">FindJar.com</a>. It lists all known packages that contain any given class! It's incredibly helpful.</p>\n"
},
{
"answer_id": 275892,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 1,
"selected": false,
"text": "<p>In Intellij IDEA you just ctrl-click on class name and you are will be moved to pseudo source code of that class, and title of window will be like c:\\path\\to\\lib.jar!\\com\\something\\ClassName.class</p>\n"
},
{
"answer_id": 277051,
"author": "Adisesha",
"author_id": 11092,
"author_profile": "https://Stackoverflow.com/users/11092",
"pm_score": 0,
"selected": false,
"text": "<p>Also check <a href=\"http://javacio.us/\" rel=\"nofollow noreferrer\">http://javacio.us/</a>. </p>\n"
},
{
"answer_id": 412709,
"author": "Ralkie",
"author_id": 18104,
"author_profile": "https://Stackoverflow.com/users/18104",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://plugins.intellij.net/plugin/?id=1162\" rel=\"nofollow noreferrer\">IntelliJ IDEA plugin (Class Hunter)</a></p>\n"
},
{
"answer_id": 1388517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could also try <a href=\"http://www.jarvana.com\" rel=\"nofollow noreferrer\">Jarvana</a> to find the jar files for a particular class.</p>\n"
},
{
"answer_id": 8076739,
"author": "user1039322",
"author_id": 1039322,
"author_profile": "https://Stackoverflow.com/users/1039322",
"pm_score": 2,
"selected": false,
"text": "<pre><code>**shell> find . -name \"*.jar\" | xargs -i -t \\jar tvf {} | grep [TheClassNameYouAreLookingFor]**\n</code></pre>\n\n<p>For example, if you are looking for a class LogFactory.class on list of apache commons jars, below command would work</p>\n\n<pre><code>shell> find apache-commons/ -name \"*.jar\" | xargs -i -t \\jar tvf {} | grep LogFactory.class\n\njar tvf apache-commons/commons-beanutils-1.7.0.jar\n\njar tvf apache-commons/commons-fileupload-1.2.1.jar\n\njar tvf apache-commons/commons-lang-2.3.jar\n\n**jar tvf apache-commons/commons-logging-1.1.jar**\n\n**21140 Tue May 09 23:08:12 EDT 2006 org/apache/commons/logging/LogFactory.class**\n\njar tvf apache-commons/commons-net-1.3.0.jar\n</code></pre>\n\n<p>The above result indicates that the match is commons-logging-1.1.jar</p>\n"
},
{
"answer_id": 8572268,
"author": "arvindwill",
"author_id": 724968,
"author_profile": "https://Stackoverflow.com/users/724968",
"pm_score": 4,
"selected": false,
"text": "<p>go for Ctrl+Shift+T in Eclipse IDE</p>\n\n<p>Open Type dialog appears where you enter the class name. after that package identifier and jar destination get displayed. </p>\n"
},
{
"answer_id": 12549172,
"author": "amphibient",
"author_id": 1312080,
"author_profile": "https://Stackoverflow.com/users/1312080",
"pm_score": 0,
"selected": false,
"text": "<p>I vote for CTRL-SHIFT-T because it is already included in Eclipse. I actually dropped jarclassfinder.jar in the plugins dir within the eclipse installation but still couldn't find the plugin in Eclipse GUI</p>\n"
},
{
"answer_id": 14685373,
"author": "user2039378",
"author_id": 2039378,
"author_profile": "https://Stackoverflow.com/users/2039378",
"pm_score": 3,
"selected": false,
"text": "<p>For me this works fine: </p>\n\n<pre><code>find * -type f -name '*.jar' -exec grep -l 'TestClass.class' '{}' \\;\n</code></pre>\n\n<p>Regards</p>\n"
},
{
"answer_id": 46919673,
"author": "Geoffrey Ritchey",
"author_id": 2831843,
"author_profile": "https://Stackoverflow.com/users/2831843",
"pm_score": 1,
"selected": false,
"text": "<p>if you tell eclipse to open a declaration (F3) or implementation (Navigate->Open Implementation) and you get popped into an un-editable edit window, you can see the path to the jar file by right-clicking the editor window and choosing 'show in breadcrumbs'</p>\n\n<p>my find unix based:</p>\n\n<pre><code>find . -name \"*.jar\" -print -exec jar -tf {} \\; >outputfile\n</code></pre>\n\n<p>edit output file to find what you want (instead of grep)</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
Given a class, [org.eclipse.ui.views.navigator.ResourceNavigator](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/views/navigator/ResourceNavigator.html) for example, how do I find out which jar file to use? I know it's in org.eclipse.ui.ide, but how would I find that out?
**Edit**: Thank you to all of you who answered. Like many things, there seems to be several ways to skin this cat. I wish javadoc contained this info. So far here are the different methods:
1. Without Internet, Eclipse or NetBeans:
```
for f in `find . -name '*.jar'`; do echo $f && jar tvf $f | grep -i $1; done
```
2. If you want to find out locally using Eclipse:
* [JAR Class Finder Plug-in](http://www.alphaworks.ibm.com/tech/jarclassfinder)
* [Class Locator Plug-in](http://classlocator.sourceforge.net/)
3. If you want to find out from Internet or you do not have the jar yet:
* [jarFinder](http://www.jarfinder.com/)
* [findjar.com](http://findjar.com/)
|
You also have this eclipse plugin: [jarclassfinder](http://www.alphaworks.ibm.com/tech/jarclassfinder)
The user enters the name of the class not found (or the name of the class that the Java project needs to access). The plug-in will search the selected directory (and subdirectories) for JAR files containing that class.
All results are displayed in a table in a custom view. The user can then browse this table and select the JAR file to add to his Java project's build path. The user then right-clicks on the entry in the table and, from the context menu, selects the build path to which to add it.
---
Update 2013, as I mention in "[searching through .jar files eclipse](https://stackoverflow.com/a/1086435/6309)", it is no longer maintained, and the alternatives are sparse.
As [sunleo](https://stackoverflow.com/users/1755242/sunleo) comments [below](https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment36479092_275141):
**with Eclipse, `Ctfl`+`Shift`+`T` remains the easiest alternative** to look for a type
(with the jar name displayed in the status bar).
---
[user862268](https://stackoverflow.com/users/862268/user862268) comments [below](https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment60625860_275141):
>
> For mac, it is `cmd`+`shift`+`T` in Eclipse to find the class and associated jar.
>
>
>
|
275,128 |
<p>Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)</p>
<pre><code>#include <iostream>
int main() {
int a = 4;
int b = 5;
a, b = b, a;
std::cout << "a: " << a << endl
<< "b: " << b << endl;
return 0;
}
</code></pre>
<p>and prints:</p>
<pre><code>a: 4
b: 5
</code></pre>
<p>What I'd like it to print ... if it weren't obvious, is:</p>
<pre><code>a: 5
b: 4
</code></pre>
<p>As in, say, ruby, or python.</p>
|
[
{
"answer_id": 275146,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<p>Or Perl. But no, it's not possible (as far as I'm aware), you need to use a temporary variable, as in:</p>\n\n<pre><code>int a = 4;\nint b = 5;\n\n{\n int tmp = a;\n a = b;\n b = tmp;\n}\n</code></pre>\n\n<p>FYI, internally those languages (or Perl atleast) create a temporary list <code>{ a, b }</code>, then assign the list to the two variables. In other words, this is atleast as performant, if only a little more messy.</p>\n"
},
{
"answer_id": 275149,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "<p>That's not possible. Your code example</p>\n\n<pre><code>a, b = b, a;\n</code></pre>\n\n<p>is interpreted in the following way:</p>\n\n<pre><code>a, (b = b), a\n</code></pre>\n\n<p>It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens. </p>\n\n<p>The proper way doing this is just </p>\n\n<pre><code>std::swap(a, b);\n</code></pre>\n\n<p>Boost includes a tuple class with which you can do</p>\n\n<pre><code>tie(a, b) = make_tuple(b, a);\n</code></pre>\n\n<p>It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.</p>\n"
},
{
"answer_id": 275155,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "<p>Parallel assignment is not supported in C++. Languages that support this usually treat <code>a,b,c</code> as a list on either side of the assignment operator, this isn't the way the comma operator works in C++. In C++, <code>a, b</code> evaluates a and then b, so <code>a, b = b, a</code> is the same as <code>a; b = b; a;</code>.</p>\n"
},
{
"answer_id": 275196,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Or Lua...<br>\nThere are tricks with C/C++, like using xor or operations, but with risk of overflow and such. Just do it the painful way, with three assignments. Not a big deal.</p>\n"
},
{
"answer_id": 277954,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "<p>There is no such function in the Standard Library. You could write a set of template functions :</p>\n\n<pre><code>template <typename T1> void ParAssign(T1& Lhs_1, T1 const& Rhs1);\ntemplate <typename T1, typename T2> void ParAssign(T1& Lhs1, T2& Lhs2, T1 const& Rhs1, T2 const& Rhs2);\n// etc.\nParAssign(a,b,\n b,a);\n</code></pre>\n\n<p>That's non-trivial if there is aliasing, as in your swap example. </p>\n"
},
{
"answer_id": 47930129,
"author": "Scheff's Cat",
"author_id": 7478597,
"author_profile": "https://Stackoverflow.com/users/7478597",
"pm_score": 1,
"selected": false,
"text": "<p>This question is very old – I just stumbled into it today...<br/>\n...and wondered why nobody gave this answer before...</p>\n\n<p>I think, it's possible to do it in C++11 similar like Python does it (under the hood):</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\nint main()\n{\n int a = 4, b = 5;\n cout << \"Before assignment: a: \" << a << \", b: \" << b << endl;\n pair<int&, int&> ba(b, a);\n ba = make_pair(a, b); // <===: (b, a) = (a, b)\n cout << \"After assignment : a: \" << a << \", b: \" << b << endl;\n return 0;\n}\n</code></pre>\n\n<p>I tried this out on <a href=\"https://ideone.com/RXXG09\" rel=\"nofollow noreferrer\"><strong>ideone.com</strong></a>. The output was:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Before assignment: a: 4, b: 5\nAfter assignment : a: 5, b: 4\n</code></pre>\n\n<p>If I remember right (I'm not a Python expert), in Python, <code>a, b</code> denotes a pair. (<a href=\"https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\">Python Doc.: 5.3. Tuples and Sequences</a>)</p>\n\n<p>Such pair can be done in C++ 11 easily e.g. with <a href=\"http://en.cppreference.com/w/cpp/utility/pair/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a>. In this case, I made a pair of references and assigned the pair of values. It works as the <code>make_pair()</code> loads both variables before the right pair (of values) is assigned to the left pair of references.</p>\n\n<p>Scrolling again, I realize that this answer is close to the boost based solution of <a href=\"https://stackoverflow.com/a/275149/7478597\">Johannes answer</a>.</p>\n\n<p>May be, the reason is that it didn't work in C++03. I tried in coliru.stacked-crooked.com: With <code>-std=c++03</code> it yields terrible to read compiler errors – changing to <code>-std=c++11</code> and it compiles and executes fine as described above.</p>\n\n<p><strong>Disclaimer</strong></p>\n\n<p>I just cannot imagine what this solution is good for nor what practical worth it may have. This is not what I tried to do. As many other answers states \"It does not work.\" IMHO it does (spelling it right according to the C++ language)...</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35807/"
] |
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)
```
#include <iostream>
int main() {
int a = 4;
int b = 5;
a, b = b, a;
std::cout << "a: " << a << endl
<< "b: " << b << endl;
return 0;
}
```
and prints:
```
a: 4
b: 5
```
What I'd like it to print ... if it weren't obvious, is:
```
a: 5
b: 4
```
As in, say, ruby, or python.
|
That's not possible. Your code example
```
a, b = b, a;
```
is interpreted in the following way:
```
a, (b = b), a
```
It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens.
The proper way doing this is just
```
std::swap(a, b);
```
Boost includes a tuple class with which you can do
```
tie(a, b) = make_tuple(b, a);
```
It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.
|
275,150 |
<p>My website is XHTML Transitional compliant <strong>except for one thing</strong>: the & (ampersand) in the URL are written as it is, instead of <code>&amp;</code></p>
<p>That is, all the URLs in my pages are usually like this:</p>
<pre><code><a href="http://www.example.org/page.aspx?x=1&y=2">Foo</a>
</code></pre>
<p>But <a href="http://validator.w3.org/" rel="nofollow noreferrer">XHTML validator</a> generates this error:</p>
<blockquote>
<p>cannot generate system identifier for general entity "y"</p>
</blockquote>
<p>... and it wants the URL to be written like this:</p>
<pre><code><a href="http://www.example.org/page.aspx?x=1&amp;y=2">Foo</a>
</code></pre>
<p>The problem is that Internet Explorer and Firefox don't handle the URL correctly and ignore the y parameter. <strong>How can I make this link work and validate correctly?</strong></p>
<p>It seems to me that it is impossible to write XHTML pages if the browsers don't work with strict encoded XHTML URLs.</p>
<p>Do you want to see in action? See the difference between these two links (copy and paste them as they are):</p>
<pre><code>http://stackoverflow.com/search?q=ff&sort=newest
</code></pre>
<p>and</p>
<pre><code>http://stackoverflow.com/search?q=ff&amp;sort=newest
</code></pre>
|
[
{
"answer_id": 275154,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>You could use <code>&amp;</code> instead of <code>&</code> in your URL within your page.</p>\n<p>That should allow it to be validated as strict XHTML...</p>\n<pre><code><a href="http://www.example.org/page.aspx?x=1&amp;y=2">Foo</a>\n</code></pre>\n<p>Note, if used by an ASP.NET <em>Request.QueryString</em> function, the query string doesn't use XML encoding; it uses <a href=\"http://www.w3schools.com/TAGS/ref_urlencode.asp\" rel=\"nofollow noreferrer\">URL encoding</a>:</p>\n<pre><code>/mypath/mypage?b=%26stuff\n</code></pre>\n<p>So you need to provide a function translating '&' into %26.</p>\n<p>Note: in that case, <em>Server.URLEncode(”neetu & geetu”)</em>, which would produce neetu+%26+geetu, is not what you want, since you need to translate & into %26, not just '&'. You must add a replace() call applied to URLEncode result, in order to replace '%26amp;' by '%26'.</p>\n"
},
{
"answer_id": 275252,
"author": "pipTheGeek",
"author_id": 28552,
"author_profile": "https://Stackoverflow.com/users/28552",
"pm_score": 7,
"selected": true,
"text": "<p>I have just tried this. What you attempted to do is correct. In HTML if you are writing a link the <code>&</code> characters should be encoded as <code>&amp;</code> You would only encode the <code>&</code> as <code>%26</code> if you wanted a parameter value to contain an ampersand. I just wrote a simple HTML page that contained a link: <code><a href=\"Default2.aspx?param1=63&amp;param2=hel\">Click me</a></code>\nand it worked fine: <code>default2.aspx</code> received the parameters intended and the source passed validation.</p>\n\n<p>The encoding of <code>&</code> as <code>&amp;</code> is required in HTML, not in the link. When the browser sees the <code>&amp;</code> in the HTML source for a link it will interpret it as an ampersand and the link target will be as intended. If you paste a URL into your browser address bar it does not expect it to be HTML and does not try to interpret any HTML encoding that it may contain. This is why your example links that you suggest we should copy/paste into a browser don't work and why we wouldn't expect them to work.</p>\n\n<p>If you post a bit more of your actual code we might be able to see what you have done wrong, but you appear to be heading the right direction by using <code>&amp;</code> in your anchor tags.</p>\n"
},
{
"answer_id": 275371,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>It was my fault: the hyperlink control already encoded <code>&</code>, so my URL <code>http://foo?x=1&amp;y=2</code> was encoded to <code>http://foo?x=1&amp;amp;y=2</code></p>\n<p>Normally the <code>&amp</code> inside the URL is correctly handled by browsers, as you stated.</p>\n"
},
{
"answer_id": 280408,
"author": "Simon",
"author_id": 15371,
"author_profile": "https://Stackoverflow.com/users/15371",
"pm_score": -1,
"selected": false,
"text": "<p>The problem is worse than you think - try it in <a href=\"https://en.wikipedia.org/wiki/Safari_%28web_browser%29\" rel=\"nofollow noreferrer\">Safari</a>. <code>&amp;amp;</code> gets converted to <code>&amp;#38;</code> and the hash ends the URL.</p>\n<p>The correct answer is to not output XHTML - there's no reason that justifies spending more time on development and alienating Mac users.</p>\n"
},
{
"answer_id": 26046095,
"author": "kasimir",
"author_id": 1005334,
"author_profile": "https://Stackoverflow.com/users/1005334",
"pm_score": 0,
"selected": false,
"text": "<p>To be even more thorough: use <code>&#38;</code>, a <em>numeric character reference</em>.</p>\n\n<p>Because <code>&amp;</code> is a <em>character entity reference</em>:</p>\n\n<blockquote>\n <p>Character entity references are defined in the markup language\n definition. This means, for example, that for HTML only a specific\n range of characters (defined by the HTML specification) can be\n represented as character entity references (and that includes only a\n small subset of the Unicode range).</p>\n</blockquote>\n\n<p>That's coming from the wise people at W3C (read <a href=\"http://www.w3.org/International/questions/qa-escapes\" rel=\"nofollow\">this</a> for more).</p>\n\n<p>Of course, this is not a very big deal, but the suggestion of W3C is that the numeric one will be valid and useable everywhere and always, while the named one is 'fine' for HTML but nothing more.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
My website is XHTML Transitional compliant **except for one thing**: the & (ampersand) in the URL are written as it is, instead of `&`
That is, all the URLs in my pages are usually like this:
```
<a href="http://www.example.org/page.aspx?x=1&y=2">Foo</a>
```
But [XHTML validator](http://validator.w3.org/) generates this error:
>
> cannot generate system identifier for general entity "y"
>
>
>
... and it wants the URL to be written like this:
```
<a href="http://www.example.org/page.aspx?x=1&y=2">Foo</a>
```
The problem is that Internet Explorer and Firefox don't handle the URL correctly and ignore the y parameter. **How can I make this link work and validate correctly?**
It seems to me that it is impossible to write XHTML pages if the browsers don't work with strict encoded XHTML URLs.
Do you want to see in action? See the difference between these two links (copy and paste them as they are):
```
http://stackoverflow.com/search?q=ff&sort=newest
```
and
```
http://stackoverflow.com/search?q=ff&sort=newest
```
|
I have just tried this. What you attempted to do is correct. In HTML if you are writing a link the `&` characters should be encoded as `&` You would only encode the `&` as `%26` if you wanted a parameter value to contain an ampersand. I just wrote a simple HTML page that contained a link: `<a href="Default2.aspx?param1=63&param2=hel">Click me</a>`
and it worked fine: `default2.aspx` received the parameters intended and the source passed validation.
The encoding of `&` as `&` is required in HTML, not in the link. When the browser sees the `&` in the HTML source for a link it will interpret it as an ampersand and the link target will be as intended. If you paste a URL into your browser address bar it does not expect it to be HTML and does not try to interpret any HTML encoding that it may contain. This is why your example links that you suggest we should copy/paste into a browser don't work and why we wouldn't expect them to work.
If you post a bit more of your actual code we might be able to see what you have done wrong, but you appear to be heading the right direction by using `&` in your anchor tags.
|
275,160 |
<p>Just starting to explore the 'wonders' of regex. Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors... My experiments are in PHP using ereg().</p>
<p>Anyway. I work with first and last names separately but for now using the same regex. So far I have:</p>
<pre><code>^[A-Z][a-zA-Z]+$
</code></pre>
<p>Any length string that starts with a capital and has only letters (capital or not) for the rest. But where I fall apart is dealing with the special situations that can pretty much occur anywhere.</p>
<ul>
<li>Hyphenated Names (Worthington-Smythe) </li>
<li>Names with Apostophies (D'Angelo) </li>
<li>Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.</li>
<li>Joint Names (Ben & Jerry)</li>
</ul>
<p>Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it. I'm pretty sure there will be instances where more than one of these situations comes up in one name.</p>
<p>So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.</p>
|
[
{
"answer_id": 275172,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>if you add spaces then \"He went to the market on Sunday\" would be a valid name.</p>\n\n<p>I don't think you can do this with a regex, you cannot easily detect names from a chunk of text using a regex, you would need a dictionary of approved names and search based on that. Any names not on the list wouldn't be detected.</p>\n"
},
{
"answer_id": 275175,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": -1,
"selected": false,
"text": "<p>Give up. Every rule you can think of has exceptions in some culture or other. Even if that \"culture\" is geeks who like legally change their names to \"37eet\".</p>\n"
},
{
"answer_id": 275177,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 7,
"selected": true,
"text": "<ul>\n<li>Hyphenated Names (Worthington-Smythe)</li>\n</ul>\n\n<p>Add a - into the second character class. The easiest way to do that is to add it at the start so that it can't possibly be interpreted as a range modifier (as in <code>a-z</code>).</p>\n\n<pre>^[A-Z][-a-zA-Z]+$</pre>\n\n<ul>\n<li>Names with Apostophies (D'Angelo)</li>\n</ul>\n\n<p>A naive way of doing this would be as above, giving:</p>\n\n<pre>^[A-Z][-'a-zA-Z]+$</pre>\n\n<p>Don't forget you may need to escape it inside the string! A 'better' way, given your example might be:</p>\n\n<pre>^[A-Z]'?[-a-zA-Z]+$</pre>\n\n<p>Which will allow a possible single apostrophe in the second position.</p>\n\n<ul>\n<li>Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.</li>\n</ul>\n\n<p>Here I'd be tempted to just do our naive way again:</p>\n\n<pre>^[A-Z]'?[- a-zA-Z]+$</pre>\n\n<p>A potentially better way might be:</p>\n\n<pre>^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$</pre>\n\n<p>Which looks for extra words at the end. This probably isn't a good idea if you're trying to match names in a body of extra text, but then again, the original wouldn't have done that well either.</p>\n\n<ul>\n<li>Joint Names (Ben & Jerry)</li>\n</ul>\n\n<p>At this point you're not looking at single names anymore?</p>\n\n<p>Anyway, as you can see, regexes have a habit of growing very quickly...</p>\n"
},
{
"answer_id": 275180,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 1,
"selected": false,
"text": "<pre><code>^[A-Z][a-zA-Z '&-]*[A-Za-z]$ \n</code></pre>\n\n<p>Will accept anything that starts with an uppercase letter, followed by zero or more of any letter, space, hyphen, ampersand or apostrophes, and ending with a letter.</p>\n"
},
{
"answer_id": 275188,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>Basically, I agree with Paul... You will always find exceptions, like <em>di Caprio</em>, <em>DeVil</em>, or such.</p>\n\n<p>Remarks on your message: in PHP, ereg is generally seen as obsolete (slow, incomplete) in favor of preg (PCRE regexes).<br>\nAnd you should try some regex tester, like the powerful <a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">Regex Coach</a>: they are great to test quickly REs against arbitrary strings.</p>\n\n<p>If you really need to solve your problem and aren't satisfied with above answers, just ask, I will give a go.</p>\n"
},
{
"answer_id": 275219,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "<p>See this question for more related \"name-detection\" related stuff. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/256729/regex-to-match-a-maximum-of-4-spaces\">regex to match a maximum of 4 spaces</a></p>\n\n<p>Basically, you have a problem in that, there are effectively no characters in existence that can't form a legal name string. </p>\n\n<p>If you are still limiting yourself to words without ä ü æ ß and other similar non-strictly-ascii characters. </p>\n\n<p>Get yourself a copy of UTF32 character table and realise how many <em>millions</em> of valid characters there are that your simple regex would miss. </p>\n"
},
{
"answer_id": 275223,
"author": "VirtuosiMedia",
"author_id": 13281,
"author_profile": "https://Stackoverflow.com/users/13281",
"pm_score": 2,
"selected": false,
"text": "<p>I don't really have a whole lot to add to a regex that takes care of names because there are already some good suggestions here, but if you want a few resources for learning more about regular expressions, you should check out:</p>\n\n<ul>\n<li><a href=\"http://regexlib.com/\" rel=\"nofollow noreferrer\">Regex Library's</a> <a href=\"http://regexlib.com/CheatSheet.aspx\" rel=\"nofollow noreferrer\">Cheat\nSheet</a></li>\n<li><a href=\"http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/\" rel=\"nofollow noreferrer\">Another cheat sheet</a></li>\n<li>A regex tutorial on the DevNetwork\nforums: <a href=\"http://forums.devnetwork.net/viewtopic.php?f=38&t=33147\" rel=\"nofollow noreferrer\">Part 1</a> and <a href=\"http://forums.devnetwork.net/viewtopic.php?f=38&t=40169\" rel=\"nofollow noreferrer\">Part 2</a></li>\n<li>PHP builder's <a href=\"http://www.phpbuilder.com/columns/dario19990616.php3\" rel=\"nofollow noreferrer\">tutorial</a></li>\n<li>And if you ever need to do regex for\nJavaScript (it's a little\ndifferent flavor), try <a href=\"http://www.javascriptkit.com/jsref/regexp.shtml\" rel=\"nofollow noreferrer\">JavaScript Kit</a>,\nor <a href=\"http://www.regular-expressions.info/javascript.html\" rel=\"nofollow noreferrer\">this resource</a>, or <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions\" rel=\"nofollow noreferrer\">Mozilla's\nreference</a></li>\n</ul>\n"
},
{
"answer_id": 275258,
"author": "Domchi",
"author_id": 29192,
"author_profile": "https://Stackoverflow.com/users/29192",
"pm_score": 2,
"selected": false,
"text": "<p>I second the 'give up' advice. Even if you consider numbers, hyphens, apostrophes and such, something like [a-zA-Z] still wouldn't catch international names (for example, those having šđčćž, or Cyrillic alphabet, or Chinese characters...)</p>\n\n<p>But... why are you even trying to verify names? What errors are you trying to catch? Don't you think people know to write their name better than you? ;) Seriously, the only thing you can do by trying to verify names is to irritate people with unusual names.</p>\n"
},
{
"answer_id": 275687,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "<p>While I agree with the answers saying you basically can't do this with regex, I will point out that some of the objections (internationalized characters) can be resolved by using UTF strings and the <code>\\p{L}</code> character class (matches a unicode \"letter\").</p>\n"
},
{
"answer_id": 2044909,
"author": "Daan",
"author_id": 58565,
"author_profile": "https://Stackoverflow.com/users/58565",
"pm_score": 6,
"selected": false,
"text": "<p>This regex is perfect for me.</p>\n\n<pre><code>^([ \\u00c0-\\u01ffa-zA-Z'\\-])+$\n</code></pre>\n\n<p>It works fine in php environments using preg_match(), but doesn't work everywhere.</p>\n\n<p>It matches <code>Jérémie O'Co-nor</code> so I think it matches all UTF-8 names.</p>\n"
},
{
"answer_id": 4549739,
"author": "Abhisek.test",
"author_id": 556467,
"author_profile": "https://Stackoverflow.com/users/556467",
"pm_score": 1,
"selected": false,
"text": "<p>To add multiple dots in the username use this Regex:</p>\n\n<pre><code>^[a-zA-Z][a-zA-Z0-9_]*\\.?[a-zA-Z0-9_\\.]*$\n</code></pre>\n\n<p>String length can be set separately.</p>\n"
},
{
"answer_id": 5387557,
"author": "Pat Kelly",
"author_id": 630577,
"author_profile": "https://Stackoverflow.com/users/630577",
"pm_score": 1,
"selected": false,
"text": "<p>You can easily neutralize the whole matter of whether letters are upper or lowercase -- even in unexpected or uncommon locations -- by converting the string to all upper case using <strong><em>strtoupper()</em></strong> and then checking it against your regex.</p>\n"
},
{
"answer_id": 5994825,
"author": "uke",
"author_id": 339661,
"author_profile": "https://Stackoverflow.com/users/339661",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<blockquote>\n<pre><code> +[a-z]{2,3} +[a-z]*|[\\w'-]*\n</code></pre>\n</blockquote>\n\n<p>This regex will correctly match names such as the following:</p>\n\n<p>jean-claude van damme</p>\n\n<p>nadine arroyo-rodriquez</p>\n\n<p>wayne la pierre</p>\n\n<p>beverly d'angelo</p>\n\n<p>billy-bob thornton</p>\n\n<p>tito puente</p>\n\n<p>susan del rio</p>\n\n<p>It will group \"van damme\", \"arroyo-rodriquez\" \"d'angelo\", \"billy-bob\", etc. as well as the singular names like \"wayne\".</p>\n\n<p>Note that it does not test that the grouped stuff is actually a valid name. Like others said, you'll need a dictionary for that. Also, it will group numbers, so if that's an issue you may want to modify the regex.</p>\n\n<p>I wrote this to parse names for a MapReduce application. All I wanted was to extract words from the name field, grouping together the del foo and la bar and billy-bobs into one word to make the key-value pair generation more accurate.</p>\n"
},
{
"answer_id": 8880713,
"author": "Tatarasanu Victor",
"author_id": 1169171,
"author_profile": "https://Stackoverflow.com/users/1169171",
"pm_score": 1,
"selected": false,
"text": "<p><code>/([\\u00c0-\\u01ffa-zA-Z'\\-]+[ ]?[*]?[\\u00c0-\\u01ffa-zA-Z'\\-]*)+/;</code></p>\n\n<p>Try this . You can also force to start with char using ^,and end with char using $</p>\n"
},
{
"answer_id": 11342352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have used this, because name can be the part of file-patch.</p>\n\n<pre><code>//http://support.microsoft.com/kb/177506\nforeach(array('/','\\\\',':','*','?','<','>','|') as $char)\n if(strpos($name,$char)!==false)\n die(\"Not allowed char: '$char'\");\n</code></pre>\n"
},
{
"answer_id": 11634636,
"author": "paviktherin",
"author_id": 667434,
"author_profile": "https://Stackoverflow.com/users/667434",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into this same issue, and like many others that have posted, this isn't a 100% fool proof expression, but it's working for us.</p>\n\n<pre><code>/([\\-'a-z]+\\s?){2,4}/\n</code></pre>\n\n<p>This will check for any hyphens and/or apostrophes in either the first and/or last name as well as checking for a space between the first and last names. The last part is a little magic that will check for between 2 and 4 names. If you tend to have a lot of international users that may have 5 or even 6 names, you can change that to 5 or 6 and it should work for you.</p>\n"
},
{
"answer_id": 25795731,
"author": "atif1512",
"author_id": 1465008,
"author_profile": "https://Stackoverflow.com/users/1465008",
"pm_score": 0,
"selected": false,
"text": "<p>i think \"/^[a-zA-Z']+$/\" is not enough it will allow to pass single letter we can adjust the range by adding {4,20} which means the range of letters are 4 to 20.</p>\n"
},
{
"answer_id": 25826707,
"author": "majestic",
"author_id": 4038323,
"author_profile": "https://Stackoverflow.com/users/4038323",
"pm_score": 1,
"selected": false,
"text": "<p>To improve on daan's answer: </p>\n\n<pre><code>^([\\u00c0-\\u01ffa-zA-Z]+\\b['\\-]{0,1})+\\b$\n</code></pre>\n\n<p>only allows a single occurances of hyphen or apostrophy within a-z and valid unicode chars.</p>\n\n<p>also does a backtrack to make sure there is no hyphen or apostrophes at the end of the string.</p>\n"
},
{
"answer_id": 27756303,
"author": "doncadavona",
"author_id": 3936053,
"author_profile": "https://Stackoverflow.com/users/3936053",
"pm_score": 0,
"selected": false,
"text": "<p>I've come up with this RegEx pattern for names:</p>\n\n<pre><code>/^([a-zA-Z]+[\\s'.]?)+\\S$/\n</code></pre>\n\n<p>It works. I think you should use it too.</p>\n\n<p>It matches only names or strings like:</p>\n\n<blockquote>\n <p>Dr. Shaquil O'Neil Armstrong Buzz-Aldrin</p>\n</blockquote>\n\n<p>It won't match strings with 2 or more spaces like:</p>\n\n<blockquote>\n <p>John Paul</p>\n</blockquote>\n\n<p>It won't match strings with ending spaces like:</p>\n\n<blockquote>\n <p>John Paul </p>\n</blockquote>\n\n<p><em>The text above has an ending space. Try highlighting or selecting the text to see the space</em></p>\n\n<p>Here's what I use to learn and create your own regex patterns:</p>\n\n<p><a href=\"http://www.regexr.com\" rel=\"nofollow\">RegExr: Leanr, Build and Test RegEx</a></p>\n"
},
{
"answer_id": 31171703,
"author": "Benjamin",
"author_id": 5071379,
"author_profile": "https://Stackoverflow.com/users/5071379",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>Try this: <pre>/^([A-Z][a-z]<em>([ ][a-z]+)</em>([ '-]([&][ ])?[A-Z][a-z]+)*)$/</pre></li>\n<li>Demo: <a href=\"http://regexr.com/3bai1\" rel=\"nofollow\">http://regexr.com/3bai1</a></li>\n</ul>\n\n<p>Have a nice day !</p>\n"
},
{
"answer_id": 31564796,
"author": "Taher Ahmed",
"author_id": 3436060,
"author_profile": "https://Stackoverflow.com/users/3436060",
"pm_score": 4,
"selected": false,
"text": "<p><strong>THE BEST REGEX EXPRESSIONS FOR NAMES:</strong></p>\n\n<ul>\n<li>I will use the term <strong>special character</strong> to refer to the following three characters:\n\n<ol>\n<li>Dash <b>-</b></li>\n<li>Hyphen <b>'</b></li>\n<li>Dot <b>.</b></li>\n</ol></li>\n<li>Spaces and special characters can not appear twice in a row (e.g.: <b>--</b> or <b>'.</b> or <b>..</b> ) </li>\n<li>Trimmed (No spaces before or after)</li>\n<li>You're welcome ;)</li>\n</ul>\n\n<hr>\n\n<p>Mandatory single name, WITHOUT spaces, WITHOUT special characters:</p>\n\n<pre><code>^([A-Za-z])+$\n</code></pre>\n\n<ul>\n<li><strong>Sierra</strong> is valid, <strong>Jack Alexander</strong> is invalid (has a space), <strong>O'Neil</strong> is invalid (has a special character)</li>\n</ul>\n\n<hr>\n\n<p>Mandatory single name, WITHOUT spaces, <strong>WITH</strong> special characters:</p>\n\n<pre><code>^[A-Za-z]+(((\\'|\\-|\\.)?([A-Za-z])+))?$\n</code></pre>\n\n<ul>\n<li><strong>Sierra</strong> is valid, <strong>O'Neil</strong> is valid, <strong>Jack Alexander</strong> is invalid (has a space)</li>\n</ul>\n\n<hr>\n\n<p>Mandatory single name, <strong>optional additional names</strong>, <strong>WITH</strong> spaces, WITH special characters:</p>\n\n<pre><code>^[A-Za-z]+((\\s)?((\\'|\\-|\\.)?([A-Za-z])+))*$\n</code></pre>\n\n<ul>\n<li><strong>Jack Alexander</strong> is valid, <strong>Sierra O'Neil</strong> is valid</li>\n</ul>\n\n<hr>\n\n<p>Mandatory single name, <strong>optional additional names</strong>, <strong>WITH</strong> spaces, <strong>WITHOUT</strong> special characters: </p>\n\n<pre><code>^[A-Za-z]+((\\s)?([A-Za-z])+)*$\n</code></pre>\n\n<ul>\n<li><strong>Jack Alexander</strong> is valid, <strong>Sierra O'Neil</strong> is invalid (has a special character) </li>\n</ul>\n\n<hr>\n\n<h3>SPECIAL CASE</h3>\n\n<p>Many modern smart devices add spaces at the end of each word, so in my applications I allow unlimited number of spaces before and after the string, then I trim it in the code behind. So I use the following:</p>\n\n<p><strong>Mandatory single name + optional additional names + spaces + special characters:</strong></p>\n\n<pre><code>^(\\s)*[A-Za-z]+((\\s)?((\\'|\\-|\\.)?([A-Za-z])+))*(\\s)*$\n</code></pre>\n\n<hr>\n\n<h3>Add your own special characters</h3>\n\n<p>If you wish to add your own special characters, let's say an underscore <strong>_</strong> this is the group you need to update: </p>\n\n<pre><code>(\\'|\\-|\\.)\n</code></pre>\n\n<p>To</p>\n\n<pre><code>(\\'|\\-|\\.|\\_)\n</code></pre>\n\n<p>PS: If you have questions comment here and I will receive an email and respond ;)</p>\n"
},
{
"answer_id": 46262215,
"author": "Aominé",
"author_id": 7731859,
"author_profile": "https://Stackoverflow.com/users/7731859",
"pm_score": 0,
"selected": false,
"text": "<p>you can use this below for names</p>\n\n<pre><code>^[a-zA-Z'-]{3,}\\s[a-zA-Z'-]{3,}$\n</code></pre>\n\n<p><code>^</code> start of the string</p>\n\n<p><code>$</code> end of the string</p>\n\n<p><code>\\s</code> space</p>\n\n<p><code>[a-zA-Z'-\\s]{3,}</code> will accept any name with a length of 3 characters or more, and it include names with <code>'</code> or <code>-</code> like <code>jean-luc</code></p>\n\n<p>So in our case it will only accept names in 2 parts separated by a space</p>\n\n<hr>\n\n<p>in case of multiple first-name you can add a <code>\\s</code></p>\n\n<pre><code>^[a-zA-Z'-\\s]{3,}\\s[a-zA-Z'-]{3,}$\n</code></pre>\n"
},
{
"answer_id": 46292284,
"author": "tk_",
"author_id": 3168721,
"author_profile": "https://Stackoverflow.com/users/3168721",
"pm_score": 3,
"selected": false,
"text": "<p>security tip: make sure to validate the size of the string before this step to avoid DoS attack that will bring down your system by sending very long charsets.</p>\n<p>Check this out:</p>\n<pre><code>^(([A-Za-z]+[,.]?[ ]?|[a-z]+['-]?)+)$\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/wVkOz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wVkOz.png\" alt=\"regex\" /></a></p>\n<p>You can test it <a href=\"https://regex101.com/r/mS9gD7/46\" rel=\"nofollow noreferrer\">here</a> : <a href=\"https://regex101.com/r/mS9gD7/46\" rel=\"nofollow noreferrer\">https://regex101.com/r/mS9gD7/46</a></p>\n"
},
{
"answer_id": 65544550,
"author": "Charlie Brown",
"author_id": 13941632,
"author_profile": "https://Stackoverflow.com/users/13941632",
"pm_score": -1,
"selected": false,
"text": "<p>Try this regex:</p>\n<pre><code>^[a-zA-Z'-\\s\\.]{3,20}\\s[a-zA-Z'-\\.]{3,20}$\n</code></pre>\n<p>Aomine's answer was quite helpful, I tweaked it a bit to include:</p>\n<ol>\n<li><p>Names with dots (middle): <code>Jane J. Samuels</code></p>\n</li>\n<li><p>Names with dots at the end: <code>John Simms Snr.</code></p>\n</li>\n</ol>\n<p>Also the name will accept minimum 2 letters, and a min. of 2 letters for surname but no more than 20 for each (so total of 40 characters)</p>\n<p>Successful Test cases:</p>\n<pre><code>D'amalia Jones \nDavid Silva Jnr. \nJay-Silva Thompson\nShay .J. Muhanned\nBob J. Iverson\n</code></pre>\n"
},
{
"answer_id": 66102679,
"author": "Jakub Brzezinski",
"author_id": 15169257,
"author_profile": "https://Stackoverflow.com/users/15169257",
"pm_score": 0,
"selected": false,
"text": "<p>Following Regex is simple and useful for proper names (Towns, Cities, First Name, Last Name) allowing all international letters omitting unicode-based regex engine.</p>\n<p>It is flexible - you can add/remove characters you want in the expression (focusing on characters you want to reject rather than include).</p>\n<pre><code>^(?:(?!^\\s|[ \\-']{2}|[\\d\\r\\n\\t\\f\\v!"#$%&()*+,\\.\\/:;<=>?@[\\\\\\]^_`{|}~€‚ƒ„…†‡ˆ‰‹‘’“”•–—˜™›¡¢£¤¥¦§¨©ª«¬®¯°±²³´¶·¸¹º»¼½¾¿×÷№′″ⁿ⁺⁰‱₁₂₃₄]|\\s$).){1,50}$\n</code></pre>\n<p>Regex matches: from 1 to 50 international letters separated by single delimiter (space -')</p>\n<p>Regex rejects: empty prefix/suffix, consecutive delimiters (space - '), digits, new line, tab, limited list of extended ASCII characters</p>\n<p><a href=\"https://regex101.com/r/FXCgJo/1\" rel=\"nofollow noreferrer\">Demo</a></p>\n"
},
{
"answer_id": 69013701,
"author": "Aman Godara",
"author_id": 12581494,
"author_profile": "https://Stackoverflow.com/users/12581494",
"pm_score": 1,
"selected": false,
"text": "<p><code>^[A-Z][a-z]*(([,.] |[ '-])[A-Za-z][a-z]*)*(\\.?)( [IVXLCDM]+)?$</code></p>\n<p>For complete details, please visit <a href=\"https://stackoverflow.com/a/68896296/12581494\"><strong>THIS</strong></a> post. This regex doesn't allow ampersands.</p>\n"
},
{
"answer_id": 71010691,
"author": "kkyucon",
"author_id": 14774669,
"author_profile": "https://Stackoverflow.com/users/14774669",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use for full name:</p>\n<pre><code>$pattern = "/^((\\p{Lu}{1})\\S(\\p{Ll}{1,20})[^0-9])+[-'\\s]((\\p{Lu}{1})\\S(\\p{Ll}{1,20}))*[^0-9]$/u";\n</code></pre>\n<ul>\n<li>Supports all languages</li>\n<li>Common names(<code>"Jane Doe"</code>, <code>"John Doe"</code>)</li>\n<li>Usefull for composed names(<code>"Marie-Josée Côté-Rochon"</code>, <code>"Bill O'reilly"</code>)</li>\n<li>Excludes digits(<code>0-9</code>)</li>\n<li>Only excepts uppercase at beginning of names</li>\n<li>First and last names from 2-21 characters</li>\n<li>Adding <code>trim()</code> to remove whitespace</li>\n<li>Does not except(<code>"John J. William"</code>, <code>"Francis O'reilly Jr. III"</code>)</li>\n<li>Must use full names, not: (<code>"John"</code>, <code>"Jane"</code>, <code>"O'reilly"</code>, <code>"Smith"</code>)</li>\n</ul>\n<p><strong>Edit:</strong>\nIt seems that both <code>[^0-9]</code> in the pattern above was matching at least a fourth digit/letter in each of either first and/or last names.</p>\n<p>Therefore names of three letters/digits could not be matched.</p>\n<p>Here is the edited regular expression:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$pattern = "/^(\\p{Lu}{1}\\S\\p{Ll}{1,20}[-'\\s]\\p{Lu}{1}\\S\\p{Ll}{1,20})+([^\\d]+)$/u";\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444/"
] |
Just starting to explore the 'wonders' of regex. Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors... My experiments are in PHP using ereg().
Anyway. I work with first and last names separately but for now using the same regex. So far I have:
```
^[A-Z][a-zA-Z]+$
```
Any length string that starts with a capital and has only letters (capital or not) for the rest. But where I fall apart is dealing with the special situations that can pretty much occur anywhere.
* Hyphenated Names (Worthington-Smythe)
* Names with Apostophies (D'Angelo)
* Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.
* Joint Names (Ben & Jerry)
Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it. I'm pretty sure there will be instances where more than one of these situations comes up in one name.
So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.
|
* Hyphenated Names (Worthington-Smythe)
Add a - into the second character class. The easiest way to do that is to add it at the start so that it can't possibly be interpreted as a range modifier (as in `a-z`).
```
^[A-Z][-a-zA-Z]+$
```
* Names with Apostophies (D'Angelo)
A naive way of doing this would be as above, giving:
```
^[A-Z][-'a-zA-Z]+$
```
Don't forget you may need to escape it inside the string! A 'better' way, given your example might be:
```
^[A-Z]'?[-a-zA-Z]+$
```
Which will allow a possible single apostrophe in the second position.
* Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.
Here I'd be tempted to just do our naive way again:
```
^[A-Z]'?[- a-zA-Z]+$
```
A potentially better way might be:
```
^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$
```
Which looks for extra words at the end. This probably isn't a good idea if you're trying to match names in a body of extra text, but then again, the original wouldn't have done that well either.
* Joint Names (Ben & Jerry)
At this point you're not looking at single names anymore?
Anyway, as you can see, regexes have a habit of growing very quickly...
|
275,169 |
<p>I have 2 files:</p>
<pre><code>/****demo.cpp****/
#include <iostream.h>
#include "gc.h"
class foo{};
int main(){
gc<foo> x1;
cout<<x1;
}
/*****gc.h*****/
template <class T> class gc
{
T* ptr;
public:
operator T*(){}
};
</code></pre>
<p>If I don't write <code>operator T*(){}</code> then I get a lot of compiler errors.</p>
<p>So plz tell me what is <code>operator T*(void)</code> and when it is invoked?</p>
|
[
{
"answer_id": 275176,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>operator <code>T*(){}</code> is a <a href=\"http://msdn.microsoft.com/en-us/library/ts48df3y.aspx\" rel=\"nofollow noreferrer\">cast operator</a>. You are providing a function that can be used to convert from a <code>gc<T></code> to a <code>T*</code> ... though it should require that you actually return something, presumably <code>ptr</code> in this case.</p>\n\n<p>The problem is that the compiler doesn't know how to format your gc object to the output stream.</p>\n\n<p>By providing a cast from gc to foo* it is able to output the object as just a pointer value ... probably not what you want.</p>\n\n<p>You likely want to define a custom overload for the << operator to dump out your class:</p>\n\n<pre><code>template <class T>\nstd::ostream& operator<<( std::ostream& os, const gc<T>& x)\n{\n // os << .. something useful here ..\n return os;\n}\n</code></pre>\n"
},
{
"answer_id": 275183,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<h3>Regarding your Question</h3>\n\n<p><code>operator type ()</code> is a so-called cast operator. if there is a need for conversion to <code>type</code>, then that operator function is used to do the conversion. </p>\n\n<p>in your example, cout uses your <code>operator T* ()</code> to convert your x1 object using a user defined implicit conversion to a pointer, which is then output by ostream's (cout is of class std::ostream) <code>operator<<</code> which takes a void* .</p>\n\n<h3>Other Problems</h3>\n\n<p>To help you figure out other problems, change the header file name from <code>iostream.h</code> to <code>iostream</code> . Standard C++ does not know <code>iostream.h</code> . Those files were called like that before C++ was made a Standard. Also, all C headers you use, like <code>math.h, stdio.h</code> are still valid in C++, but they are so-called backward-compatibility header files. You should include for example <code>cmath</code> and <code>cstdio</code> instead. That will put all names that are not macros in C into the <code>namespace std</code>. Instead of using <code>cout</code> , you use <code>std::cout</code> . Likewise for other identifiers too.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have 2 files:
```
/****demo.cpp****/
#include <iostream.h>
#include "gc.h"
class foo{};
int main(){
gc<foo> x1;
cout<<x1;
}
/*****gc.h*****/
template <class T> class gc
{
T* ptr;
public:
operator T*(){}
};
```
If I don't write `operator T*(){}` then I get a lot of compiler errors.
So plz tell me what is `operator T*(void)` and when it is invoked?
|
operator `T*(){}` is a [cast operator](http://msdn.microsoft.com/en-us/library/ts48df3y.aspx). You are providing a function that can be used to convert from a `gc<T>` to a `T*` ... though it should require that you actually return something, presumably `ptr` in this case.
The problem is that the compiler doesn't know how to format your gc object to the output stream.
By providing a cast from gc to foo\* it is able to output the object as just a pointer value ... probably not what you want.
You likely want to define a custom overload for the << operator to dump out your class:
```
template <class T>
std::ostream& operator<<( std::ostream& os, const gc<T>& x)
{
// os << .. something useful here ..
return os;
}
```
|
275,174 |
<p>I have a string that is HTML encoded: </p>
<pre><code>'''&lt;img class=&quot;size-medium wp-image-113&quot;\
style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot;\
src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot;\
alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;'''
</code></pre>
<p>I want to change that to:</p>
<pre class="lang-html prettyprint-override"><code><img class="size-medium wp-image-113" style="margin-left: 15px;"
title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"
alt="" width="300" height="194" />
</code></pre>
<p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p>
<p>The string is stored like that because I am using a web-scraping tool called <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer"><code>BeautifulSoup</code></a>, it "scans" a web-page and gets certain content from it, then returns the string in that format.</p>
<p>I've found how to do this in <strong>C#</strong> but not in <strong>Python</strong>. Can someone help me out?</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
|
[
{
"answer_id": 275195,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 2,
"selected": false,
"text": "<p>I found this in the Cheetah source code (<a href=\"http://www.koders.com/python/fid549827F97513858275EEA43DC0135AC97AEAEF57.aspx\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<pre><code>htmlCodes = [\n ['&', '&amp;'],\n ['<', '&lt;'],\n ['>', '&gt;'],\n ['\"', '&quot;'],\n]\nhtmlCodesReversed = htmlCodes[:]\nhtmlCodesReversed.reverse()\ndef htmlDecode(s, codes=htmlCodesReversed):\n \"\"\" Returns the ASCII decoded version of the given HTML string. This does\n NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode().\"\"\"\n for code in codes:\n s = s.replace(code[1], code[0])\n return s\n</code></pre>\n\n<p>not sure why they reverse the list,\n I think it has to do with the way they encode, so with you it may not need to be reversed.\nAlso if I were you I would change htmlCodes to be a list of tuples rather than a list of lists...\nthis is going in my library though :)</p>\n\n<p>i noticed your title asked for encode too, so here is Cheetah's encode function.</p>\n\n<pre><code>def htmlEncode(s, codes=htmlCodes):\n \"\"\" Returns the HTML encoded version of the given string. This is useful to\n display a plain ASCII text string on a web page.\"\"\"\n for code in codes:\n s = s.replace(code[0], code[1])\n return s\n</code></pre>\n"
},
{
"answer_id": 275246,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 8,
"selected": true,
"text": "<p>Given the Django use case, there are two answers to this. Here is its <code>django.utils.html.escape</code> function, for reference:</p>\n\n<pre><code>def escape(html):\n \"\"\"Returns the given HTML with ampersands, quotes and carets encoded.\"\"\"\n return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l\nt;').replace('>', '&gt;').replace('\"', '&quot;').replace(\"'\", '&#39;'))\n</code></pre>\n\n<p>To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:</p>\n\n<pre><code>def html_decode(s):\n \"\"\"\n Returns the ASCII decoded version of the given HTML string. This does\n NOT remove normal HTML tags like <p>.\n \"\"\"\n htmlCodes = (\n (\"'\", '&#39;'),\n ('\"', '&quot;'),\n ('>', '&gt;'),\n ('<', '&lt;'),\n ('&', '&amp;')\n )\n for code in htmlCodes:\n s = s.replace(code[1], code[0])\n return s\n\nunescaped = html_decode(my_string)\n</code></pre>\n\n<p>This, however, is not a general solution; it is only appropriate for strings encoded with <code>django.utils.html.escape</code>. More generally, it is a good idea to stick with the standard library:</p>\n\n<pre><code># Python 2.x:\nimport HTMLParser\nhtml_parser = HTMLParser.HTMLParser()\nunescaped = html_parser.unescape(my_string)\n\n# Python 3.x:\nimport html.parser\nhtml_parser = html.parser.HTMLParser()\nunescaped = html_parser.unescape(my_string)\n\n# >= Python 3.5:\nfrom html import unescape\nunescaped = unescape(my_string)\n</code></pre>\n\n<p>As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.</p>\n\n<p>With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:</p>\n\n<pre><code>{{ context_var|safe }}\n{% autoescape off %}\n {{ context_var }}\n{% endautoescape %}\n</code></pre>\n"
},
{
"answer_id": 275463,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 4,
"selected": false,
"text": "<p>Use daniel's solution if the set of encoded characters is relatively restricted.\nOtherwise, use one of the numerous HTML-parsing libraries.</p>\n\n<p>I like BeautifulSoup because it can handle malformed XML/HTML :</p>\n\n<p><a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"noreferrer\">http://www.crummy.com/software/BeautifulSoup/</a></p>\n\n<p>for your question, there's an example in their <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html\" rel=\"noreferrer\">documentation</a> </p>\n\n<pre><code>from BeautifulSoup import BeautifulStoneSoup\nBeautifulStoneSoup(\"Sacr&eacute; bl&#101;u!\", \n convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]\n# u'Sacr\\xe9 bleu!'\n</code></pre>\n"
},
{
"answer_id": 312538,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 3,
"selected": false,
"text": "<p>See at the bottom of this <a href=\"http://wiki.python.org/moin/EscapingHtml\" rel=\"noreferrer\">page at Python wiki</a>, there are at least 2 options to \"unescape\" html.</p>\n"
},
{
"answer_id": 449169,
"author": "user26294",
"author_id": 26294,
"author_profile": "https://Stackoverflow.com/users/26294",
"pm_score": 6,
"selected": false,
"text": "<p>For html encoding, there's <strong>cgi.escape</strong> from the standard library:</p>\n\n<pre><code>>> help(cgi.escape)\ncgi.escape = escape(s, quote=None)\n Replace special characters \"&\", \"<\" and \">\" to HTML-safe sequences.\n If the optional flag quote is true, the quotation mark character (\")\n is also translated.\n</code></pre>\n\n<p>For html decoding, I use the following:</p>\n\n<pre><code>import re\nfrom htmlentitydefs import name2codepoint\n# for some reason, python 2.5.2 doesn't have this one (apostrophe)\nname2codepoint['#39'] = 39\n\ndef unescape(s):\n \"unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml\"\n return re.sub('&(%s);' % '|'.join(name2codepoint),\n lambda m: unichr(name2codepoint[m.group(1)]), s)\n</code></pre>\n\n<p>For anything more complicated, I use BeautifulSoup.</p>\n"
},
{
"answer_id": 1619286,
"author": "dfrankow",
"author_id": 34935,
"author_profile": "https://Stackoverflow.com/users/34935",
"pm_score": 3,
"selected": false,
"text": "<p>Daniel's comment as an answer:</p>\n\n<p>\"escaping only occurs in Django during template rendering. Therefore, there's no need for an unescape - you just tell the templating engine not to escape. either {{ context_var|safe }} or {% autoescape off %}{{ context_var }}{% endautoescape %}\"</p>\n"
},
{
"answer_id": 3271650,
"author": "slowkvant",
"author_id": 162125,
"author_profile": "https://Stackoverflow.com/users/162125",
"pm_score": 3,
"selected": false,
"text": "<p>I found a fine function at: <a href=\"http://snippets.dzone.com/posts/show/4569\" rel=\"noreferrer\">http://snippets.dzone.com/posts/show/4569</a></p>\n\n<pre><code>def decodeHtmlentities(string):\n import re\n entity_re = re.compile(\"&(#?)(\\d{1,5}|\\w{1,8});\")\n\n def substitute_entity(match):\n from htmlentitydefs import name2codepoint as n2cp\n ent = match.group(2)\n if match.group(1) == \"#\":\n return unichr(int(ent))\n else:\n cp = n2cp.get(ent)\n\n if cp:\n return unichr(cp)\n else:\n return match.group()\n\n return entity_re.subn(substitute_entity, string)[0]\n</code></pre>\n"
},
{
"answer_id": 7088472,
"author": "Jiangge Zhang",
"author_id": 718453,
"author_profile": "https://Stackoverflow.com/users/718453",
"pm_score": 7,
"selected": false,
"text": "<p>With the standard library:</p>\n\n<ul>\n<li><p>HTML Escape</p>\n\n<pre><code>try:\n from html import escape # python 3.x\nexcept ImportError:\n from cgi import escape # python 2.x\n\nprint(escape(\"<\"))\n</code></pre></li>\n<li><p>HTML Unescape</p>\n\n<pre><code>try:\n from html import unescape # python 3.4+\nexcept ImportError:\n try:\n from html.parser import HTMLParser # python 3.x (<3.4)\n except ImportError:\n from HTMLParser import HTMLParser # python 2.x\n unescape = HTMLParser().unescape\n\nprint(unescape(\"&gt;\"))\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 8524552,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 0,
"selected": false,
"text": "<p>Below is a python function that uses module <code>htmlentitydefs</code>. It is not perfect. The version of <code>htmlentitydefs</code> that I have is incomplete and it assumes that all entities decode to one codepoint which is wrong for entities like <code>&NotEqualTilde;</code>:</p>\n\n<p><a href=\"http://www.w3.org/TR/html5/named-character-references.html\" rel=\"nofollow\">http://www.w3.org/TR/html5/named-character-references.html</a></p>\n\n<blockquote>\n<pre><code>NotEqualTilde; U+02242 U+00338 ≂̸\n</code></pre>\n</blockquote>\n\n<p>With those caveats though, here's the code.</p>\n\n<pre><code>def decodeHtmlText(html):\n \"\"\"\n Given a string of HTML that would parse to a single text node,\n return the text value of that node.\n \"\"\"\n # Fast path for common case.\n if html.find(\"&\") < 0: return html\n return re.sub(\n '&(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));',\n _decode_html_entity,\n html)\n\ndef _decode_html_entity(match):\n \"\"\"\n Regex replacer that expects hex digits in group 1, or\n decimal digits in group 2, or a named entity in group 3.\n \"\"\"\n hex_digits = match.group(1) # '&#10;' -> unichr(10)\n if hex_digits: return unichr(int(hex_digits, 16))\n decimal_digits = match.group(2) # '&#x10;' -> unichr(0x10)\n if decimal_digits: return unichr(int(decimal_digits, 10))\n name = match.group(3) # name is 'lt' when '&lt;' was matched.\n if name:\n decoding = (htmlentitydefs.name2codepoint.get(name)\n # Treat &GT; like &gt;.\n # This is wrong for &Gt; and &Lt; which HTML5 adopted from MathML.\n # If htmlentitydefs included mappings for those entities,\n # then this code will magically work.\n or htmlentitydefs.name2codepoint.get(name.lower()))\n if decoding is not None: return unichr(decoding)\n return match.group(0) # Treat \"&noSuchEntity;\" as \"&noSuchEntity;\"\n</code></pre>\n"
},
{
"answer_id": 8593583,
"author": "Chris Harty",
"author_id": 990114,
"author_profile": "https://Stackoverflow.com/users/990114",
"pm_score": 3,
"selected": false,
"text": "<p>If anyone is looking for a simple way to do this via the django templates, you can always use filters like this:</p>\n<pre><code><html>\n{{ node.description|safe }}\n</html>\n</code></pre>\n<p>I had some data coming from a vendor and everything I posted had html tags actually written on the rendered page as if you were looking at the source.</p>\n"
},
{
"answer_id": 9468081,
"author": "Seth Gottlieb",
"author_id": 561578,
"author_profile": "https://Stackoverflow.com/users/561578",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use django.utils.html.escape</p>\n\n<pre><code>from django.utils.html import escape\n\nsomething_nice = escape(request.POST['something_naughty'])\n</code></pre>\n"
},
{
"answer_id": 11273187,
"author": "smilitude",
"author_id": 439649,
"author_profile": "https://Stackoverflow.com/users/439649",
"pm_score": 0,
"selected": false,
"text": "<p>This is the easiest solution for this problem - </p>\n\n<pre><code>{% autoescape on %}\n {{ body }}\n{% endautoescape %}\n</code></pre>\n\n<p>From <a href=\"https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs\" rel=\"nofollow\">this page</a>.</p>\n"
},
{
"answer_id": 28268163,
"author": "James",
"author_id": 1870013,
"author_profile": "https://Stackoverflow.com/users/1870013",
"pm_score": 2,
"selected": false,
"text": "<p>Even though this is a really old question, this may work.</p>\n\n<p>Django 1.5.5</p>\n\n<pre><code>In [1]: from django.utils.text import unescape_entities\nIn [2]: unescape_entities('&lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;')\nOut[2]: u'<img class=\"size-medium wp-image-113\" style=\"margin-left: 15px;\" title=\"su1\" src=\"http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg\" alt=\"\" width=\"300\" height=\"194\" />'\n</code></pre>\n"
},
{
"answer_id": 31282266,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3.4+:</p>\n\n<pre><code>import html\n\nhtml.unescape(your_string)\n</code></pre>\n"
},
{
"answer_id": 51404291,
"author": "Paolo Melchiorre",
"author_id": 755343,
"author_profile": "https://Stackoverflow.com/users/755343",
"pm_score": 0,
"selected": false,
"text": "<p>Searching the simplest solution of this question in Django and Python I found you can use builtin theirs functions to escape/unescape html code.</p>\n\n<h1>Example</h1>\n\n<p>I saved your html code in <code>scraped_html</code> and <code>clean_html</code>:</p>\n\n<pre><code>scraped_html = (\n '&lt;img class=&quot;size-medium wp-image-113&quot; '\n 'style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; '\n 'src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; '\n 'alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;'\n)\nclean_html = (\n '<img class=\"size-medium wp-image-113\" style=\"margin-left: 15px;\" '\n 'title=\"su1\" src=\"http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg\" '\n 'alt=\"\" width=\"300\" height=\"194\" />'\n)\n</code></pre>\n\n<h1>Django</h1>\n\n<p><em>You need Django >= 1.0</em></p>\n\n<h2>unescape</h2>\n\n<p>To unescape your scraped html code you can use <a href=\"https://github.com/django/django/blob/stable/2.0.x/django/utils/text.py#L377\" rel=\"nofollow noreferrer\">django.utils.text.unescape_entities</a> which:</p>\n\n<blockquote>\n <p>Convert all named and numeric character references to the corresponding unicode characters.</p>\n</blockquote>\n\n<pre><code>>>> from django.utils.text import unescape_entities\n>>> clean_html == unescape_entities(scraped_html)\nTrue\n</code></pre>\n\n<h2>escape</h2>\n\n<p>To escape your clean html code you can use <a href=\"https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.html.escape\" rel=\"nofollow noreferrer\">django.utils.html.escape</a> which:</p>\n\n<blockquote>\n <p>Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.</p>\n</blockquote>\n\n<pre><code>>>> from django.utils.html import escape\n>>> scraped_html == escape(clean_html)\nTrue\n</code></pre>\n\n<h1>Python</h1>\n\n<p><em>You need Python >= 3.4</em></p>\n\n<h2>unescape</h2>\n\n<p>To unescape your scraped html code you can use <a href=\"https://docs.python.org/3/library/html.html#html.unescape\" rel=\"nofollow noreferrer\">html.unescape</a> which:</p>\n\n<blockquote>\n <p>Convert all named and numeric character references (e.g. <code>&gt;</code>, <code>&#62;</code>, <code>&x3e;</code>) in the string s to the corresponding unicode characters.</p>\n</blockquote>\n\n<pre><code>>>> from html import unescape\n>>> clean_html == unescape(scraped_html)\nTrue\n</code></pre>\n\n<h2>escape</h2>\n\n<p>To escape your clean html code you can use <a href=\"https://docs.python.org/3/library/html.html#html.escape\" rel=\"nofollow noreferrer\">html.escape</a> which:</p>\n\n<blockquote>\n <p>Convert the characters <code>&</code>, <code><</code> and <code>></code> in string s to HTML-safe sequences.</p>\n</blockquote>\n\n<pre><code>>>> from html import escape\n>>> scraped_html == escape(clean_html)\nTrue\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I have a string that is HTML encoded:
```
'''<img class="size-medium wp-image-113"\
style="margin-left: 15px;" title="su1"\
src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"\
alt="" width="300" height="194" />'''
```
I want to change that to:
```html
<img class="size-medium wp-image-113" style="margin-left: 15px;"
title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"
alt="" width="300" height="194" />
```
I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text.
The string is stored like that because I am using a web-scraping tool called [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/), it "scans" a web-page and gets certain content from it, then returns the string in that format.
I've found how to do this in **C#** but not in **Python**. Can someone help me out?
### Related
* [Convert XML/HTML Entities into Unicode String in Python](https://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
|
Given the Django use case, there are two answers to this. Here is its `django.utils.html.escape` function, for reference:
```
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '&l
t;').replace('>', '>').replace('"', '"').replace("'", '''))
```
To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:
```
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
htmlCodes = (
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&')
)
for code in htmlCodes:
s = s.replace(code[1], code[0])
return s
unescaped = html_decode(my_string)
```
This, however, is not a general solution; it is only appropriate for strings encoded with `django.utils.html.escape`. More generally, it is a good idea to stick with the standard library:
```
# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)
```
As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.
With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:
```
{{ context_var|safe }}
{% autoescape off %}
{{ context_var }}
{% endautoescape %}
```
|
275,194 |
<p>How can I format data coming from a DataBinder.Eval statement in an ASPX page?</p>
<p>For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.</p>
<p>The code for this goes like this:</p>
<pre><code><asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
</code></pre>
<p>Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?</p>
<pre><code><asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
</code></pre>
<p>If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?</p>
|
[
{
"answer_id": 275218,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 7,
"selected": true,
"text": "<p>There is an optional overload for DataBinder.Eval to supply formatting:</p>\n\n<pre><code><%# DataBinder.Eval(Container.DataItem, \"expression\"[, \"format\"]) %>\n</code></pre>\n\n<p>The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:</p>\n\n<pre><code><asp:Label id=\"lblNewsDate\" runat=\"server\" Text='<%# DataBinder.Eval(Container.DataItem, \"publishedDate\", \"{0:dddd d MMMM}\") %>'</label>\n</code></pre>\n"
},
{
"answer_id": 275319,
"author": "dexter",
"author_id": 2703984,
"author_profile": "https://Stackoverflow.com/users/2703984",
"pm_score": 4,
"selected": false,
"text": "<p>You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.</p>\n\n<p>You also can format your field inline:</p>\n\n<pre><code><%# ((DateTime)DataBinder.Eval(Container.DataItem,\"publishedDate\")).ToString(\"yyyy-MMM-dd\") %>\n</code></pre>\n\n<p>If you use ASP.NET 2.0 or newer you can write this as below:</p>\n\n<pre><code><%# ((DateTime)Eval(\"publishedDate\")).ToString(\"yyyy-MMM-dd\") %>\n</code></pre>\n\n<p>Another option is to bind the value to label at OnItemDataBound event.</p>\n"
},
{
"answer_id": 275828,
"author": "Nahom Tijnam",
"author_id": 11172,
"author_profile": "https://Stackoverflow.com/users/11172",
"pm_score": 4,
"selected": false,
"text": "<p>After some searching on the Internet I found that <strong>it is in fact very much possible</strong> to call a custom method passing the DataBinder.Eval value.</p>\n\n<p>The custom method can be written in the code behind file, but has to be declared <strong>public</strong> or <strong>protected</strong>. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be <strong>private</strong>.</p>\n\n<p>So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:</p>\n\n<p>default.aspx</p>\n\n<pre><code><asp:Label ID=\"lblNewsDate\" runat=\"server\" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, \"publishedDate\")) )%>'></asp:Label>\n</code></pre>\n\n<p>default.aspx.cs code:</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page\n{\n\n protected string GetDateInHomepageFormat(DateTime d)\n {\n\n string retValue = \"\";\n\n // Do all processing required and return value\n\n return retValue;\n }\n}\n</code></pre>\n\n<p>Hope this helps others as well.</p>\n"
},
{
"answer_id": 1211493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This line solved my problem:</p>\n\n<pre><code><%#DateTime.Parse(Eval(\"DDDate\").ToString()).ToString(\"dd-MM-yyyy\")%>\n</code></pre>\n"
},
{
"answer_id": 1439119,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code><asp:Label ID=\"ServiceBeginDate\" runat=\"server\" Text='<%# (DataBinder.Eval(Container.DataItem, \"ServiceBeginDate\", \"{0:yyyy}\") == \"0001\") ? \"\" : DataBinder.Eval(Container.DataItem, \"ServiceBeginDate\", \"{0:MM/dd/yyyy}\") %>'>\n</asp:Label>\n</code></pre>\n"
},
{
"answer_id": 1605239,
"author": "santosh kumar",
"author_id": 194332,
"author_profile": "https://Stackoverflow.com/users/194332",
"pm_score": 0,
"selected": false,
"text": "<p>You can use it this way in aspx page</p>\n\n<pre><code><%# DataBinder.Eval(Container.DataItem, \"DateColoumnName\", \"{0:dd-MMM-yyyy}\") %>\n</code></pre>\n"
},
{
"answer_id": 6026812,
"author": "Diego C.",
"author_id": 80268,
"author_profile": "https://Stackoverflow.com/users/80268",
"pm_score": 4,
"selected": false,
"text": "<p>Why not use the simpler syntax?</p>\n\n<pre><code><asp:Label id=\"lblNewsDate\" runat=\"server\" Text='<%# Eval(\"publishedDate\", \"{0:dddd d MMMM}\") %>'</label>\n</code></pre>\n\n<p>This is the template control \"Eval\" that takes in the expression and the string format:</p>\n\n<pre><code>protected internal string Eval(\nstring expression,\nstring format\n</code></pre>\n\n<p>)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/3d2sz789.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/3d2sz789.aspx</a></p>\n"
},
{
"answer_id": 7651385,
"author": "GMG",
"author_id": 978506,
"author_profile": "https://Stackoverflow.com/users/978506",
"pm_score": 2,
"selected": false,
"text": "<p>To format the date using the local date format use:</p>\n\n<pre><code><%#((DateTime)Eval(\"ExpDate\")).ToString(\"d\")%>\n</code></pre>\n\n<p><a href=\"http://willmtz.blogspot.com/2011/09/how-to-format-eval-statement-to-display_24.html\" rel=\"nofollow\">How to Format an Eval Statement to Display a Date using Date Locale</a></p>\n"
},
{
"answer_id": 7762117,
"author": "gaz",
"author_id": 892575,
"author_profile": "https://Stackoverflow.com/users/892575",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.</p>\n\n<p>Mark Up:-</p>\n\n<pre><code><asp:Label ID=\"Label3\" runat=\"server\" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, \"psWages1D\")) %>'/>\n</code></pre>\n\n<p>Code behind:-</p>\n\n<pre><code>Public Function fLabel(ByVal tval) As String\n fLabel = tval.ToString(\"#,##0.00%;(#,##0.00%);Zero\")\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 26581656,
"author": "Devendra Patel",
"author_id": 3027600,
"author_profile": "https://Stackoverflow.com/users/3027600",
"pm_score": 1,
"selected": false,
"text": "<p>Text='<%# DateTime.Parse(Eval(\"LastLoginDate\").ToString()).ToString(\"MM/dd/yyyy hh:mm tt\") %>'</p>\n\n<p>This works for the format as you want</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11172/"
] |
How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
```
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
```
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
```
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
```
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
|
There is an optional overload for DataBinder.Eval to supply formatting:
```
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
```
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
```
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
```
|
275,199 |
<p>How do you do the following operations in C++?</p>
<ol>
<li>Opening Files</li>
<li>Closing Files</li>
<li>Reading Files</li>
<li>Writing Files</li>
</ol>
|
[
{
"answer_id": 275201,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.cplusplus.com/doc/tutorial/files.html\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/doc/tutorial/files.html</a></p>\n\n<p>I personally still use the C style fopen, fread, fwrite, etc, but that is more of preference than actually \"correct\".</p>\n"
},
{
"answer_id": 275224,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 4,
"selected": false,
"text": "<h2>Reading</h2>\n\n<pre><code>#include <fstream>\nint main()\n{\n std::ifstream inputFile(\"MyFileName\") // Opens a File.\n\n int x;\n inputFile >> x; // Reads an integer from a file.\n\n std::string word;\n inputFile >> word; // Reads a space separated word from a file.\n\n double y;\n inputFile >> y; // Reads a floating point number from the file.\n\n // etc..\n } // File AutoMagically closed by going out of scope.\n</code></pre>\n\n<h2>Writing</h2>\n\n<pre><code>#include <fstream>\nint main()\n{\n std::ofstream inputFile(\"MyFileName\") // Opens a File.\n\n int x = 5;\n inputFile << x << \" \"; // Writes an integer to a file then a space.\n inputFile << 5 << \" \"; // Same Again.\n\n std::string word(\"This is a line\");\n inputFile << word << \"\\n\"; // Writes a string to a file followed by a newline\n // Notice the difference between reading and\n // writing a string.\n inputFile << \"Write a string constant to a file\\n\";\n\n double y = 15.4;\n inputFile << y << \":\"; // Writes a floating point number \n // to the file followed by \":\".\n\n // etc..\n } // File AutoMagically closed by going out of scope.\n</code></pre>\n"
},
{
"answer_id": 275234,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<h2>All at once</h2>\n\n<pre><code>{ \n std::ifstream in(\"foo.txt\"); /* opens for reading */\n std::ofstream out(\"bar.txt\"); /* opens for writing */\n out << in.rdbuf(); /* streams in into out. writing and reading */\n} /* closes automatically */\n</code></pre>\n"
},
{
"answer_id": 275283,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 1,
"selected": false,
"text": "<p>With C++ you've got lots of choices for how to interact with files, especially if you are using one of the many frameworks around, like Qt, wxWidgets, or GLib. To summarize, the standard C++ library uses a streams based model of file access, via std::ifstream and std::ofstream. This is similar to what you see when using std::cout and is what @Martin's post exemplifies. You also have available the standard C library functions for reading and writing files, namely open(), close(), read() and write(). The f*() variants take a FILE pointer rather than a file descriptor. The C variants are more useful when you want to treat a file as a raw stream of bytes, which unfortunately happens more often than it should. While both of these are \"portable\", constructing paths and handling directories/special files usually isn't, which is why you get things like boost::filesystem.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35821/"
] |
How do you do the following operations in C++?
1. Opening Files
2. Closing Files
3. Reading Files
4. Writing Files
|
Reading
-------
```
#include <fstream>
int main()
{
std::ifstream inputFile("MyFileName") // Opens a File.
int x;
inputFile >> x; // Reads an integer from a file.
std::string word;
inputFile >> word; // Reads a space separated word from a file.
double y;
inputFile >> y; // Reads a floating point number from the file.
// etc..
} // File AutoMagically closed by going out of scope.
```
Writing
-------
```
#include <fstream>
int main()
{
std::ofstream inputFile("MyFileName") // Opens a File.
int x = 5;
inputFile << x << " "; // Writes an integer to a file then a space.
inputFile << 5 << " "; // Same Again.
std::string word("This is a line");
inputFile << word << "\n"; // Writes a string to a file followed by a newline
// Notice the difference between reading and
// writing a string.
inputFile << "Write a string constant to a file\n";
double y = 15.4;
inputFile << y << ":"; // Writes a floating point number
// to the file followed by ":".
// etc..
} // File AutoMagically closed by going out of scope.
```
|
275,207 |
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p>
<p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p>
<pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long))
print fptr(1234)
</code></pre>
<p>Now, why does this script keeps doing segmentation fault whenever I run it?</p>
<p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p>
<p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
|
[
{
"answer_id": 275300,
"author": "artificialidiot",
"author_id": 7988,
"author_profile": "https://Stackoverflow.com/users/7988",
"pm_score": 0,
"selected": false,
"text": "<p>Does python even allow such usage? I should learn it then...</p>\n\n<p>I think the interpreter doesn't expect any register to be changed. Try saving the registers that you use inside the function if you plan to use your assembler output like this.</p>\n\n<p>Btw, call convention of x86_64 is different than regular x86. You may have trouble if you lose stack pointer alignment and mix external objects generated with other tools.</p>\n"
},
{
"answer_id": 275333,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can't freely execute any allocated memory without first setting it as executable. I never tried myself, but you might want to check the unix function <code>mprotect</code>:</p>\n\n<p><a href=\"http://linux.about.com/library/cmd/blcmdl2_mprotect.htm\" rel=\"nofollow noreferrer\">http://linux.about.com/library/cmd/blcmdl2_mprotect.htm</a></p>\n\n<p><code>VirtualProtect</code> seems to do the same thing on windows :</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx</a></p>\n"
},
{
"answer_id": 275426,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 3,
"selected": false,
"text": "<p>Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT_EXEC and on others it does.</p>\n\n<p>Therefore it is necessary to change the protection level with mprotect afterwards.</p>\n\n<p>Lame thing, took a while to find out what to do.</p>\n\n<pre><code>from ctypes import (\n cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi\n)\n\nPROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4\nmprotect = pythonapi.mprotect\n\nbuffer = ''.join(map(chr, [ #0000000000000000 <add>:\n 0x55, # push %rbp\n 0x48, 0x89, 0xe5, # mov %rsp,%rbp\n 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)\n 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax\n 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax\n 0xc9, # leaveq \n 0xc3, # retq\n]))\n\npagesize = pythonapi.getpagesize()\ncbuffer = create_string_buffer(buffer)#c_char_p(buffer)\naddr = addressof(cbuffer)\nsize = sizeof(cbuffer)\nmask = pagesize - 1\nif mprotect(~mask&addr, mask&addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) < 0:\n print \"mprotect failed?\"\nelse:\n fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long))\n print repr(fptr(1234))\n</code></pre>\n"
},
{
"answer_id": 275460,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": true,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333\">vincent</a> mentioned, this is due to the allocated page being marked as non executable. Newer processors support this <a href=\"http://en.wikipedia.org/wiki/NX_bit\" rel=\"nofollow noreferrer\">functionality</a>, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.</p>\n\n<p>To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:</p>\n\n<pre><code>libc = CDLL('libc.so')\n\n# Some constants\nPROT_READ = 1\nPROT_WRITE = 2\nPROT_EXEC = 4\n\ndef executable_code(buffer):\n \"\"\"Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.\n The pointer should be freed with libc.free() when finished\"\"\"\n\n buf = c_char_p(buffer)\n size = len(buffer)\n # Need to align to a page boundary, so use valloc\n addr = libc.valloc(size)\n addr = c_void_p(addr)\n\n if 0 == addr: \n raise Exception(\"Failed to allocate memory\")\n\n memmove(addr, buf, size)\n if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):\n raise Exception(\"Failed to set protection on buffer\")\n return addr\n\ncode_ptr = executable_code(buffer)\nfptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))\nprint fptr(1234)\nlibc.free(code_ptr)\n</code></pre>\n\n<p>Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. </p>\n\n<p>Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).</p>\n"
},
{
"answer_id": 1812514,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 0,
"selected": false,
"text": "<p>There's simpler approach I've figured only but recently that doesn't involve mprotect. Plainly mmap the executable space for program directly. These days python has a module for doing exactly this, though I didn't find way to get the address of the code. In short you'd allocate memory calling mmap instead of using string buffers and setting the execution flag indirectly. This is easier and safer, you can be sure only your code can be executed now.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86\_64 as well, but I immediately hit a problem.
I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86\_64 code is correct:
```
from ctypes import cast, CFUNCTYPE, c_char_p, c_long
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long))
print fptr(1234)
```
Now, why does this script keeps doing segmentation fault whenever I run it?
I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT\_EXEC -area. Unless, of course, you use a write protection in .text
But then, why have that PROT\_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?
|
As [vincent](https://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333) mentioned, this is due to the allocated page being marked as non executable. Newer processors support this [functionality](http://en.wikipedia.org/wiki/NX_bit), and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.
To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:
```
libc = CDLL('libc.so')
# Some constants
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4
def executable_code(buffer):
"""Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.
The pointer should be freed with libc.free() when finished"""
buf = c_char_p(buffer)
size = len(buffer)
# Need to align to a page boundary, so use valloc
addr = libc.valloc(size)
addr = c_void_p(addr)
if 0 == addr:
raise Exception("Failed to allocate memory")
memmove(addr, buf, size)
if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):
raise Exception("Failed to set protection on buffer")
return addr
code_ptr = executable_code(buffer)
fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))
print fptr(1234)
libc.free(code_ptr)
```
Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit.
Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).
|
275,213 |
<p>Previously, I had a class that wrapped an internal <code>System.Collections.Generic.List<Item></code> (where Item is a class I created). The wrapper class provided several collection-level properties that provided totals, averages, and other computations on items in the list. I was creating a <code>BindingSource</code> around this wrapped <code>List<></code> and another <code>BindingSource</code> around my class and was able to get at the Items in the wrapped list through the first <code>BindingSource</code> and the collection-level properties of the wrapper class using the second. </p>
<p>A simplified example looks like: </p>
<pre><code>public class OldClass()
{
private List<Item> _Items;
public OldClass()
{
_Items = new List<Item>();
}
public List<Item> Items { get { return _Items; } }
// collection-level properties
public float AverageValue { get { return Average() } }
public float TotalValue { get { return Total() } }
// ... other properties like this
}
</code></pre>
<p>With the binding sources created in this way:</p>
<pre><code>_itemsBindingSource = new BindingSource(oldClass.Items);
_summaryBindingSource = new BindingSource(oldClass);
</code></pre>
<p>Recently, I tried to change this class to be derived from <code>System.Collections.Generic.List<Item></code> instead of keeping a wrapped <code>List<></code> member. My hope was to get rid of the extra wrapper layer and use only one <code>BindingSource</code> instead of two. However, now I find that I cannot get at the properties that apply to all items in the list (such as <code>AverageValue</code>) when I do data binding. Only the properties of list items are available. </p>
<p>Am I forced to go back to using a wrapped <code>List<></code> of <code>Item</code>s? Or is there a way that I can get at both the properties of <code>Item</code>s stored my new class as well as the properties that apply to the collection itself?</p>
|
[
{
"answer_id": 275318,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 0,
"selected": false,
"text": "<p>The problem here is that you want to use your one class for two completely different purposes (in terms of bindings).</p>\n\n<p>Example: The \"AverageValue\" property doesn't make sense to be on each item, because it's a global property that spans all items.</p>\n\n<p>Either way, I'm guessing that your _itemsBindingSource is for a ComboBox or something, and that your _summaryBindingSource is for a PropertyGrid (or something like that).</p>\n\n<p>What you <em>could</em> do, that <em>might</em> work in your situation (I can't be certain because I don't know what you are actually doing) is this:</p>\n\n<p>1) Make your \"OldClass\" implement IEnumerable... and in that, simply return the enumeration from the list. That will give you the ability to bind to \"oldClass\" instead of \"oldClass.Items\".</p>\n\n<p>2) Make the \"public List Items\" a field, instead of a property... or add the \"Browsable(false)\" attribute so it won't get bound to the PropertyGrid (this is a guess as it's unclear what you're using these bindings for).</p>\n"
},
{
"answer_id": 275392,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>The system treats anything that implements <code>IList</code> (or <code>IListSource</code>) as a container, rather than an item. As such, you cannot bind to properties of anything that implements <code>IList</code>. As such, <em>encapsulation</em> (i.e. what you already have) is the best approach if you want to be able to bind to properties of the container.</p>\n\n<p>However, you should note that many bindings support dot-notation in the source - i.e. either binding to \"Items.SomeProperty\", or setting the auxiliary property (typically <code>DataMember</code>) to specify sub-lists.</p>\n\n<p>This allows you to have a single <code>BindingSource</code>, and have different controls bound to different levels in the hierarchy - i.e. you might have a <code>TextBox</code> bound to <code>AverageValue</code>, and a <code>DataGridView</code> (with the same <code>DataSource</code>) that has <code>DataMember=\"Items\"</code>.</p>\n"
},
{
"answer_id": 276037,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of creating a wrapper class around your List, have you considered creating an extension class (assuming you're using C# 3)</p>\n\n<pre><code>public static class MyExtensions\n{\n public static float GetAverage(this List<Item>)\n {\n // implementation\n }\n\n public static float GetTotal(this List<Item>)\n {\n // implementation\n }\n}\n</code></pre>\n\n<p>Of course, your properties become method calls (<a href=\"https://stackoverflow.com/questions/137775/should-extension-properties-be-added-to-c-40\">maybe C# 4 will fix this</a>), but you would eliminate the wrapper entirely.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4849/"
] |
Previously, I had a class that wrapped an internal `System.Collections.Generic.List<Item>` (where Item is a class I created). The wrapper class provided several collection-level properties that provided totals, averages, and other computations on items in the list. I was creating a `BindingSource` around this wrapped `List<>` and another `BindingSource` around my class and was able to get at the Items in the wrapped list through the first `BindingSource` and the collection-level properties of the wrapper class using the second.
A simplified example looks like:
```
public class OldClass()
{
private List<Item> _Items;
public OldClass()
{
_Items = new List<Item>();
}
public List<Item> Items { get { return _Items; } }
// collection-level properties
public float AverageValue { get { return Average() } }
public float TotalValue { get { return Total() } }
// ... other properties like this
}
```
With the binding sources created in this way:
```
_itemsBindingSource = new BindingSource(oldClass.Items);
_summaryBindingSource = new BindingSource(oldClass);
```
Recently, I tried to change this class to be derived from `System.Collections.Generic.List<Item>` instead of keeping a wrapped `List<>` member. My hope was to get rid of the extra wrapper layer and use only one `BindingSource` instead of two. However, now I find that I cannot get at the properties that apply to all items in the list (such as `AverageValue`) when I do data binding. Only the properties of list items are available.
Am I forced to go back to using a wrapped `List<>` of `Item`s? Or is there a way that I can get at both the properties of `Item`s stored my new class as well as the properties that apply to the collection itself?
|
The system treats anything that implements `IList` (or `IListSource`) as a container, rather than an item. As such, you cannot bind to properties of anything that implements `IList`. As such, *encapsulation* (i.e. what you already have) is the best approach if you want to be able to bind to properties of the container.
However, you should note that many bindings support dot-notation in the source - i.e. either binding to "Items.SomeProperty", or setting the auxiliary property (typically `DataMember`) to specify sub-lists.
This allows you to have a single `BindingSource`, and have different controls bound to different levels in the hierarchy - i.e. you might have a `TextBox` bound to `AverageValue`, and a `DataGridView` (with the same `DataSource`) that has `DataMember="Items"`.
|
275,233 |
<p>What I would like to do is the following. I have a single table, Products, containing a private key ProductID. Instead of having SQL Server auto-increment ProductID on inserts, I want to increment it in the DataContext partial method "InsertProduct":</p>
<pre><code>Partial Public Class MyDataContext
Private Sub InsertProduct(ByVal instance As Product)
Dim id As Integer = Me.Products.Max(Function(p As Product) p.ProductID) + 1
instance.ProductID = id
Me.ExecuteDynamicInsert(instance)
End Sub
End Class
</code></pre>
<p>However, this will only work when inserting the first Product instance. When attempting to insert a second instance, the id retrieved is the same as for the first,</p>
<pre><code>Using context As New MyDataContext
Dim product1 As New Product
context.Products.InsertOnSubmit(product1)
context.SubmitChanges() 'This works
Dim product2 As New Product
context.Products.InsertOnSubmit(product2)
context.SubmitChanges() 'DuplicateKeyException
End Using
</code></pre>
<p>Am I missing something obvious here?</p>
|
[
{
"answer_id": 275308,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>InsertProduct isn't declared as a partial method in the code above. Is this a typo in your post or have you declared it with a different signature than required and thus it is not being executed?</p>\n\n<p>[EDIT] I'm not a VB programmer (I use C#), but I think your code needs to declare the code as partial as well as in the designer. This is true in C#, anyway. </p>\n"
},
{
"answer_id": 275350,
"author": "valure",
"author_id": 9919,
"author_profile": "https://Stackoverflow.com/users/9919",
"pm_score": 0,
"selected": false,
"text": "<p>InsertProduct is declared as a partial method in the designer generated file (MyDataClasses.designer.vb).</p>\n\n<p>It is executed, in fact I can insert a breakpoint in InsertProduct and observe everything running correctly for product1. For product2 an exception is thrown by <code>context.SubmitChanges()</code> but the breakpoint is not hit.</p>\n"
},
{
"answer_id": 276300,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 2,
"selected": false,
"text": "<p>I would really recommend letting SQL Server do the incremental numbering. The above approach even if you do get it working would fail under load in a multi-user scenario where they both get the same ID and try to insert the same one.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9919/"
] |
What I would like to do is the following. I have a single table, Products, containing a private key ProductID. Instead of having SQL Server auto-increment ProductID on inserts, I want to increment it in the DataContext partial method "InsertProduct":
```
Partial Public Class MyDataContext
Private Sub InsertProduct(ByVal instance As Product)
Dim id As Integer = Me.Products.Max(Function(p As Product) p.ProductID) + 1
instance.ProductID = id
Me.ExecuteDynamicInsert(instance)
End Sub
End Class
```
However, this will only work when inserting the first Product instance. When attempting to insert a second instance, the id retrieved is the same as for the first,
```
Using context As New MyDataContext
Dim product1 As New Product
context.Products.InsertOnSubmit(product1)
context.SubmitChanges() 'This works
Dim product2 As New Product
context.Products.InsertOnSubmit(product2)
context.SubmitChanges() 'DuplicateKeyException
End Using
```
Am I missing something obvious here?
|
I would really recommend letting SQL Server do the incremental numbering. The above approach even if you do get it working would fail under load in a multi-user scenario where they both get the same ID and try to insert the same one.
|
275,250 |
<p>I'm writing some disposable Haskell scripts to solve some of the <a href="http://projecteuler.net" rel="nofollow noreferrer">Project Euler</a> problems. I don't really want to have to compile them because of the number of changes I'm constantly having to make, but in a few cases I've found that I've run out of stack space.</p>
<p>The documentation for <code>runhaskell</code> says that the following syntax should increase the stack space:</p>
<pre><code>runhaskell +RTS -K5M -RTS Script.hs
</code></pre>
<p>This never, ever works (in any permutation I've tried). The stack size always remains 8,388,608. This is maddening, and I haven't found much help on Google.</p>
<p>Any suggestions? What am I doing wrong?</p>
|
[
{
"answer_id": 275619,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 4,
"selected": true,
"text": "<p>I'm guessing you're using GHC. Chapter 4 of the User's Guide of the newly released 6.10.1 says: </p>\n\n<blockquote>\n <p>The only runghc flag currently is -f\n /path/to/ghc, which tells runghc which\n GHC to use to run the program.</p>\n</blockquote>\n\n<p>I don't see a bug logged at <a href=\"http://hackage.haskell.org/trac/ghc\" rel=\"noreferrer\">http://hackage.haskell.org/trac/ghc</a> . Seems pretty lame to me. I'd suggest asking on irc #ghc, or the cvs-ghc mailing list.</p>\n\n<p>Of the other Haskell compilers/interpreters, only nhc98 seems allow you to set the max stack size. Depending on your OS, nhc98 could be an option. </p>\n"
},
{
"answer_id": 275623,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>Just compile it.</p>\n\n<p>Problem123.hs:</p>\n\n<pre><code>module Main where\nmain = do\n print solution\nsolution = ...\n</code></pre>\n\n<p>Short and sweet command line:</p>\n\n<pre><code>ghc --make -O3 Problem123.hs\n./Problem123\n</code></pre>\n\n<p>Final note: I'm not sure I would call them \"scripts\".</p>\n"
},
{
"answer_id": 431989,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I'm doing the same thing (Project Euler) and have been using ghc. The trick (thanks #haskell!) is to tell the <em>executable</em> to have more stack size rather than the <em>compiler</em>.</p>\n\n<pre><code>$ ghc -O2 -o 23 23.hs\n$ ./23 +RTS -K128M\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27779/"
] |
I'm writing some disposable Haskell scripts to solve some of the [Project Euler](http://projecteuler.net) problems. I don't really want to have to compile them because of the number of changes I'm constantly having to make, but in a few cases I've found that I've run out of stack space.
The documentation for `runhaskell` says that the following syntax should increase the stack space:
```
runhaskell +RTS -K5M -RTS Script.hs
```
This never, ever works (in any permutation I've tried). The stack size always remains 8,388,608. This is maddening, and I haven't found much help on Google.
Any suggestions? What am I doing wrong?
|
I'm guessing you're using GHC. Chapter 4 of the User's Guide of the newly released 6.10.1 says:
>
> The only runghc flag currently is -f
> /path/to/ghc, which tells runghc which
> GHC to use to run the program.
>
>
>
I don't see a bug logged at <http://hackage.haskell.org/trac/ghc> . Seems pretty lame to me. I'd suggest asking on irc #ghc, or the cvs-ghc mailing list.
Of the other Haskell compilers/interpreters, only nhc98 seems allow you to set the max stack size. Depending on your OS, nhc98 could be an option.
|
275,273 |
<p>I recently downloaded PLT Scheme and DrScheme. When I open DrScheme, I am told to choose a language. However, I'm not familiar with any of my options, and the help guides don't really break it down to help me easily choose which choice.</p>
<p>So, first - is DrScheme and PLT Scheme really the tools I need to learn Lisp and/or Scheme? If so, what are the different languages and which one(s) should I be using?</p>
|
[
{
"answer_id": 275291,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": 0,
"selected": false,
"text": "<p>Standard (R5RS) is the actual thing so that would be your best bet<br>\ni learnt it from <a href=\"http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/\" rel=\"nofollow noreferrer\">http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/</a><br>\nused MIT Scheme while doing that<br>\nbut otherwise i find plt a lot nicer to work with</p>\n"
},
{
"answer_id": 275313,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 5,
"selected": true,
"text": "<p>Just go for \"Pretty Big\". That will be all you need until you know what the rest are for. I find that R5RS is good, but it does lack the extensions that PLT has added to DrScheme.</p>\n\n<p><em>edit:</em> I just checked and I guess that both \"Pretty Big\" and \"R5RS\" are considered \"legacy\" in DrScheme 4 and the \"Module\" language is favored instead. Just make sure that all the files you use with the Module language start with</p>\n\n<pre><code>#lang scheme\n</code></pre>\n\n<p>Module is a way to specify the language used in the source file rather than globally by the DrScheme interpreter. This means that you can use different languages for different parts of your program by breaking it up into files and indicating in each file the language you're using. If you're just starting out, all you need to worry about is just keeping #lang scheme at the top of all the files you use.</p>\n\n<p>A small note - this declaration is not official Scheme, and needs to be removed if you attempt to use the files in another Scheme interpreter.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
I recently downloaded PLT Scheme and DrScheme. When I open DrScheme, I am told to choose a language. However, I'm not familiar with any of my options, and the help guides don't really break it down to help me easily choose which choice.
So, first - is DrScheme and PLT Scheme really the tools I need to learn Lisp and/or Scheme? If so, what are the different languages and which one(s) should I be using?
|
Just go for "Pretty Big". That will be all you need until you know what the rest are for. I find that R5RS is good, but it does lack the extensions that PLT has added to DrScheme.
*edit:* I just checked and I guess that both "Pretty Big" and "R5RS" are considered "legacy" in DrScheme 4 and the "Module" language is favored instead. Just make sure that all the files you use with the Module language start with
```
#lang scheme
```
Module is a way to specify the language used in the source file rather than globally by the DrScheme interpreter. This means that you can use different languages for different parts of your program by breaking it up into files and indicating in each file the language you're using. If you're just starting out, all you need to worry about is just keeping #lang scheme at the top of all the files you use.
A small note - this declaration is not official Scheme, and needs to be removed if you attempt to use the files in another Scheme interpreter.
|
275,338 |
<p>What is the <em>best</em> way to print the cells of a <code>String[][]</code> array as a right-justified table? For example, the input</p>
<pre><code>{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }
</code></pre>
<p>should yield the output</p>
<pre><code> x xxx
yyy y
zz zz
</code></pre>
<p>This seems like something that one <em>should</em> be able to accomplish using <code>java.util.Formatter</code>, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.</p>
|
[
{
"answer_id": 275339,
"author": "Aditya Mukherji",
"author_id": 25990,
"author_profile": "https://Stackoverflow.com/users/25990",
"pm_score": 1,
"selected": false,
"text": "<p>find the length of the longest string..<br>\nleft pad all the strings with spaces until they r that length + 1<br>\nSystem.out.print them using 2 nested for loops</p>\n"
},
{
"answer_id": 275391,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "<p>Indeed, if you specify a width for the fields, it should be right-justified.<br>\nIf you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.</p>\n"
},
{
"answer_id": 275438,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an answer, using dynamically-generated format strings for each column:</p>\n\n<pre><code>public static void printTable(String[][] table) {\n // Find out what the maximum number of columns is in any row\n int maxColumns = 0;\n for (int i = 0; i < table.length; i++) {\n maxColumns = Math.max(table[i].length, maxColumns);\n }\n\n // Find the maximum length of a string in each column\n int[] lengths = new int[maxColumns];\n for (int i = 0; i < table.length; i++) {\n for (int j = 0; j < table[i].length; j++) {\n lengths[j] = Math.max(table[i][j].length(), lengths[j]);\n }\n }\n\n // Generate a format string for each column\n String[] formats = new String[lengths.length];\n for (int i = 0; i < lengths.length; i++) {\n formats[i] = \"%1$\" + lengths[i] + \"s\" \n + (i + 1 == lengths.length ? \"\\n\" : \" \");\n }\n\n // Print 'em out\n for (int i = 0; i < table.length; i++) {\n for (int j = 0; j < table[i].length; j++) {\n System.out.printf(formats[j], table[i][j]);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
What is the *best* way to print the cells of a `String[][]` array as a right-justified table? For example, the input
```
{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }
```
should yield the output
```
x xxx
yyy y
zz zz
```
This seems like something that one *should* be able to accomplish using `java.util.Formatter`, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.
|
Indeed, if you specify a width for the fields, it should be right-justified.
If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.
|
275,351 |
<p>Is there a way to get all methods (private, privileged, or public) of a javascript object from within? Here's the sample object:</p>
<pre><code>var Test = function() {
// private methods
function testOne() {}
function testTwo() {}
function testThree() {}
// public methods
function getMethods() {
for (i in this) {
alert(i); // shows getMethods, but not private methods
}
}
return { getMethods : getMethods }
}();
// should return ['testOne', 'testTwo', 'testThree', 'getMethods']
Test.getMethods();
</code></pre>
<p>The current issue is the code in <code>getMethods()</code>, the simplified example will return just the public methods, but not to private ones.</p>
<p><strong>edit</strong>: my test code may (or may not) be overcomplicating what i'm hoping to get at. given the following:</p>
<pre><code>function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;
}
</code></pre>
<p>is there a way to find out what variables exist in <code>myFunction()</code> from within <code>myFunction()</code>. the pseudo-code would look like this:</p>
<pre><code>function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;
alert(current.properties); // would be nice to get ['test1', 'test2', 'test3']
}
</code></pre>
|
[
{
"answer_id": 275362,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "<p>If you call getMethods() like that, isn't it static? Surely you'd need to properly init the class for <code>this</code> to work as expected?</p>\n\n<pre><code>var t = new Test();\nt.getMethods();\n</code></pre>\n\n<p>If that doesn't work, please take a look at the <a href=\"http://www.iconico.com/workshop/jsSerializer/\" rel=\"nofollow noreferrer\">JS Serializer</a>. I used it a while back for some debug and I think it worked for private vars.</p>\n"
},
{
"answer_id": 275380,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "<p>Javascript doesn't really have the notion of private anything. Because of that, javascript doesn't have a reflection API as such. The technique you're using doesn't so much make them private as render them inaccessible; they're hidden, not private. I think you could manage something by putting those methods somewhere manually.</p>\n"
},
{
"answer_id": 275390,
"author": "eswald",
"author_id": 21229,
"author_profile": "https://Stackoverflow.com/users/21229",
"pm_score": 1,
"selected": false,
"text": "<p>Part of the issue with your test code is that Test is the object created by your return statement: \"<code>{ getMethods : getMethods }</code>\" It has no testOne, testTwo, or testThree methods; instead, those are only available within the same namespace as the original getMethods function.</p>\n"
},
{
"answer_id": 275457,
"author": "Kevin Gorski",
"author_id": 35806,
"author_profile": "https://Stackoverflow.com/users/35806",
"pm_score": 6,
"selected": true,
"text": "<p>The technical reason why those methods are hidden is twofold. </p>\n\n<p>First, when you execute a method on the Test object, \"this\" will be the untyped object returned at the end of the anonymous function that contains the public methods per the <a href=\"http://yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"nofollow noreferrer\">Module Pattern</a>. </p>\n\n<p>Second, the methods testOne, testTwo, and testThree aren't attached to a specific object, and exist only in the context of the anonymous function. You could attach the methods to an internal object and then expose them through a public method, but it wouldn't be quite as clean as the original pattern and it won't help if you're getting this code from a third party.</p>\n\n<p>The result would look something like this:</p>\n\n<pre><code>var Test = function() {\n var private = {\n testOne : function () {},\n testTwo : function () {},\n testThree : function () {}\n };\n\n function getMethods() {\n for (i in this) {\n alert(i); // shows getMethods, but not private methods\n }\n for (i in private) {\n alert(i); // private methods\n }\n }\n return { getMethods : getMethods }\n}();\n\n// will return ['getMethods', 'testOne', 'testTwo', 'testThree']\nTest.getMethods();\n</code></pre>\n\n<p><strong>edit:</strong></p>\n\n<p>Unfortunately, no. The set of local variables aren't accessible via a single, automatic keyword. </p>\n\n<p>If you remove the \"var\" keyword they would be attached to the global context (usually the window object), but that's the only behavior that I know of that is similar to what you're describing. There would be a lot of other properties and methods on that object if you did that, though.</p>\n"
},
{
"answer_id": 315635,
"author": "small_jam",
"author_id": 15752,
"author_profile": "https://Stackoverflow.com/users/15752",
"pm_score": 1,
"selected": false,
"text": "<p>you can use <code>var that = this;</code> trick:</p>\n\n<pre><code>var Test = function() {\n var that = this;\n function testOne() {}\n function testTwo() {}\n function testThree() {}\n function getMethods() {\n for (i in that) {\n alert(i);\n }\n }\n return { getMethods : getMethods }\n}();\n</code></pre>\n"
},
{
"answer_id": 10174525,
"author": "Rune FS",
"author_id": 112407,
"author_profile": "https://Stackoverflow.com/users/112407",
"pm_score": 1,
"selected": false,
"text": "<p>With a little change to the way the function is defined you can achieve what you want. Wrap the actual implementation of the function in an object literal it would then look like this:</p>\n\n<pre><code>(function() {\n var obj = {\n // private methods\n testOne: function () {},\n testTwo : function () {},\n testThree: function () {},\n // public methods\n getMethods : function () {\n for (i in this) {\n alert(i); // shows getMethods, but not private methods\n }\n }\n };\n return { getMethods : function(){return obj.getMethods();} }\n})();\n</code></pre>\n"
},
{
"answer_id": 10538036,
"author": "Jay",
"author_id": 390720,
"author_profile": "https://Stackoverflow.com/users/390720",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://netjs.codeplex.com/SourceControl/changeset/view/91169#1773642\" rel=\"noreferrer\">http://netjs.codeplex.com/SourceControl/changeset/view/91169#1773642</a></p>\n\n<pre><code>//Reflection\n\n~function (extern) {\n\nvar Reflection = this.Reflection = (function () { return Reflection; });\n\nReflection.prototype = Reflection;\n\nReflection.constructor = Reflection;\n\nReflection.getArguments = function (func) {\n var symbols = func.toString(),\n start, end, register;\n start = symbols.indexOf('function');\n if (start !== 0 && start !== 1) return undefined;\n start = symbols.indexOf('(', start);\n end = symbols.indexOf(')', start);\n var args = [];\n symbols.substr(start + 1, end - start - 1).split(',').forEach(function (argument) {\n args.push(argument);\n });\n return args;\n};\n\nextern.Reflection = extern.reflection = Reflection;\n\nFunction.prototype.getArguments = function () { return Reflection.getArguments(this); }\n\nFunction.prototype.getExpectedReturnType = function () { /*ToDo*/ }\n\n} (this);\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4853/"
] |
Is there a way to get all methods (private, privileged, or public) of a javascript object from within? Here's the sample object:
```
var Test = function() {
// private methods
function testOne() {}
function testTwo() {}
function testThree() {}
// public methods
function getMethods() {
for (i in this) {
alert(i); // shows getMethods, but not private methods
}
}
return { getMethods : getMethods }
}();
// should return ['testOne', 'testTwo', 'testThree', 'getMethods']
Test.getMethods();
```
The current issue is the code in `getMethods()`, the simplified example will return just the public methods, but not to private ones.
**edit**: my test code may (or may not) be overcomplicating what i'm hoping to get at. given the following:
```
function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;
}
```
is there a way to find out what variables exist in `myFunction()` from within `myFunction()`. the pseudo-code would look like this:
```
function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;
alert(current.properties); // would be nice to get ['test1', 'test2', 'test3']
}
```
|
The technical reason why those methods are hidden is twofold.
First, when you execute a method on the Test object, "this" will be the untyped object returned at the end of the anonymous function that contains the public methods per the [Module Pattern](http://yuiblog.com/blog/2007/06/12/module-pattern/).
Second, the methods testOne, testTwo, and testThree aren't attached to a specific object, and exist only in the context of the anonymous function. You could attach the methods to an internal object and then expose them through a public method, but it wouldn't be quite as clean as the original pattern and it won't help if you're getting this code from a third party.
The result would look something like this:
```
var Test = function() {
var private = {
testOne : function () {},
testTwo : function () {},
testThree : function () {}
};
function getMethods() {
for (i in this) {
alert(i); // shows getMethods, but not private methods
}
for (i in private) {
alert(i); // private methods
}
}
return { getMethods : getMethods }
}();
// will return ['getMethods', 'testOne', 'testTwo', 'testThree']
Test.getMethods();
```
**edit:**
Unfortunately, no. The set of local variables aren't accessible via a single, automatic keyword.
If you remove the "var" keyword they would be attached to the global context (usually the window object), but that's the only behavior that I know of that is similar to what you're describing. There would be a lot of other properties and methods on that object if you did that, though.
|
275,355 |
<p>another request sorry..
Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..</p>
<p>if my file contains</p>
<pre><code>Hey Bob
Now
</code></pre>
<p>should give me</p>
<pre><code>Hey
Bob
[NEW LINE]
NOW
</code></pre>
<p>Is there a way to do this without using getline?</p>
|
[
{
"answer_id": 275405,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": true,
"text": "<p>Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters.</p>\n\n<p>If you want to read a line at a time use std::getline()<br>\nThe line can then be tokenized separately with a string stream.</p>\n\n<pre><code>std::string line;\nwhile(std::getline(std::cin,line))\n{\n\n // If you then want to tokenize the line use a string stream:\n\n std::stringstream lineStream(line);\n std::string token;\n while(lineStream >> token)\n {\n std::cout << \"Token(\" << token << \")\\n\";\n }\n\n std::cout << \"New Line Detected\\n\";\n}\n</code></pre>\n\n<p>Small addition:<br></p>\n\n<h2>Without using getline()</h2>\n\n<p>So you really want to be able to detect a newline. This means that newline becomes another type of token. So lets assume that you have words separated by 'white spaces' as tokens and newline as its own token.</p>\n\n<p>Then you can create a Token type.<br>\nThen all you have to do is write the stream operators for a token:</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n\nclass Token\n{\n private:\n friend std::ostream& operator<<(std::ostream&,Token const&);\n friend std::istream& operator>>(std::istream&,Token&);\n std::string value;\n};\nstd::istream& operator>>(std::istream& str,Token& data)\n{\n // Check to make sure the stream is OK.\n if (!str)\n { return str;\n }\n\n char x;\n // Drop leading space\n do\n {\n x = str.get();\n }\n while(str && isspace(x) && (x != '\\n'));\n\n // If the stream is done. exit now.\n if (!str)\n {\n return str;\n }\n\n // We have skipped all white space up to the\n // start of the first token. We can now modify data.\n data.value =\"\";\n\n // If the token is a '\\n' We are finished.\n if (x == '\\n')\n { data.value = \"\\n\";\n return str;\n }\n\n // Otherwise read the next token in.\n str.unget();\n str >> data.value;\n\n return str;\n}\nstd::ostream& operator<<(std::ostream& str,Token const& data)\n{\n return str << data.value;\n}\n\n\nint main()\n{\n std::ifstream f(\"PLOP\");\n Token x;\n\n while(f >> x)\n {\n std::cout << \"Token(\" << x << \")\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 277054,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know why you think <code>std::getline</code> is bad. You can still recognize newlines.</p>\n\n<pre><code>std::string token;\nstd::ifstream file(\"file.txt\");\nwhile(std::getline(file, token)) {\n std::istringstream line(token);\n while(line >> token) {\n std::cout << \"Token :\" << token << std::endl;\n }\n if(file.unget().get() == '\\n') {\n std::cout << \"newline found\" << std::endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 806542,
"author": "the_drow",
"author_id": 85140,
"author_profile": "https://Stackoverflow.com/users/85140",
"pm_score": 1,
"selected": false,
"text": "<p>This is another cool and much less verbose way I came across to tokenize strings.</p>\n\n<pre><code>vector<string> vec; //we'll put all of the tokens in here \nstring token;\nistringstream iss(\"put text here\"); \n\nwhile ( getline(iss, token, '\\n') ) {\n vec.push_back(token);\n}\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33481/"
] |
another request sorry..
Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..
if my file contains
```
Hey Bob
Now
```
should give me
```
Hey
Bob
[NEW LINE]
NOW
```
Is there a way to do this without using getline?
|
Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters.
If you want to read a line at a time use std::getline()
The line can then be tokenized separately with a string stream.
```
std::string line;
while(std::getline(std::cin,line))
{
// If you then want to tokenize the line use a string stream:
std::stringstream lineStream(line);
std::string token;
while(lineStream >> token)
{
std::cout << "Token(" << token << ")\n";
}
std::cout << "New Line Detected\n";
}
```
Small addition:
Without using getline()
-----------------------
So you really want to be able to detect a newline. This means that newline becomes another type of token. So lets assume that you have words separated by 'white spaces' as tokens and newline as its own token.
Then you can create a Token type.
Then all you have to do is write the stream operators for a token:
```
#include <iostream>
#include <fstream>
class Token
{
private:
friend std::ostream& operator<<(std::ostream&,Token const&);
friend std::istream& operator>>(std::istream&,Token&);
std::string value;
};
std::istream& operator>>(std::istream& str,Token& data)
{
// Check to make sure the stream is OK.
if (!str)
{ return str;
}
char x;
// Drop leading space
do
{
x = str.get();
}
while(str && isspace(x) && (x != '\n'));
// If the stream is done. exit now.
if (!str)
{
return str;
}
// We have skipped all white space up to the
// start of the first token. We can now modify data.
data.value ="";
// If the token is a '\n' We are finished.
if (x == '\n')
{ data.value = "\n";
return str;
}
// Otherwise read the next token in.
str.unget();
str >> data.value;
return str;
}
std::ostream& operator<<(std::ostream& str,Token const& data)
{
return str << data.value;
}
int main()
{
std::ifstream f("PLOP");
Token x;
while(f >> x)
{
std::cout << "Token(" << x << ")\n";
}
}
```
|
275,375 |
<p>From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors.</p>
<p>However, whenever I go to look at a vector in the debugger I just see M_impl, with M_start and M_finish members (and a couple of others) - but nothing in-between! (it's a debug build, btw).</p>
<p>Am I missing a setting or something somewhere?</p>
<p>I've also read that there are macros available that can augment the debug viewer even further to inspect more complex containers - but have been unable to find any.</p>
<p>I'd also like to be able to view std::wstrings, without having to drop to the memory viewer. It shows std::string fine. Is there anything I can do to show std::wstring?</p>
<p>I realise this is a bit of a composite question - but it's all really part of the same subject.</p>
|
[
{
"answer_id": 275381,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 2,
"selected": false,
"text": "<p>You can create <a href=\"https://web.archive.org/web/20090812202145/http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeDebugging/600-Viewing_Variables_and_Memory/variables_and_memory.html\" rel=\"nofollow noreferrer\">Data formatters</a> for different variable types so they show up nicer :-).</p>\n"
},
{
"answer_id": 275398,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 2,
"selected": true,
"text": "<p>The ability to view the container's items may rely on the complexity of the templated type. For trivial objects like int, bool, etc., and even simple class templates like </p>\n\n<pre><code>template <class T> struct S { T m_t; }\n</code></pre>\n\n<p>I <em>normally</em> have no problem viewing vector items in the debugger variable view. I say normally because there seem to be occasional bugs that cause stuff--particularly when debugging--not to behave the way I expected. One of those things is garbage or totally useless information in the variable view. Usually a clean rebuild of the target (or sometimes even a more drastic restarting of XCode followed by a clean rebuild) fixes the problem.</p>\n\n<p>As for the other container types, it's most likely hard to efficiently view this information. For example a map is often implemented as a red-black tree. The debugger would have to know that in advance in order to properly walk the tree and show you all the keys and values. That's probably asking a lot from Xcode or GDB--especially since the former focuses more on Objective-C and plain C than C++ (hence the fact that namespaces tend to kill code completion despite their ubiquity and importance).</p>\n"
},
{
"answer_id": 11430010,
"author": "Dan Wexler",
"author_id": 1118386,
"author_profile": "https://Stackoverflow.com/users/1118386",
"pm_score": 1,
"selected": false,
"text": "<p>Try using the GDB debugger in Project->Edit Scheme... and consider switching your compiler to LLVM GCC 4.2 in the Project Build Settings (under Build Options -> Compiler for C/C++/Objective-C).</p>\n\n<p>In XCode 4, I found I needed these settings to view things like a std::vector of V3f where V3f is a templated float vector type.</p>\n\n<p>Note that I think you can't use ARC (Automatic Reference Counting) with LLVM GCC 4.2.</p>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32136/"
] |
From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors.
However, whenever I go to look at a vector in the debugger I just see M\_impl, with M\_start and M\_finish members (and a couple of others) - but nothing in-between! (it's a debug build, btw).
Am I missing a setting or something somewhere?
I've also read that there are macros available that can augment the debug viewer even further to inspect more complex containers - but have been unable to find any.
I'd also like to be able to view std::wstrings, without having to drop to the memory viewer. It shows std::string fine. Is there anything I can do to show std::wstring?
I realise this is a bit of a composite question - but it's all really part of the same subject.
|
The ability to view the container's items may rely on the complexity of the templated type. For trivial objects like int, bool, etc., and even simple class templates like
```
template <class T> struct S { T m_t; }
```
I *normally* have no problem viewing vector items in the debugger variable view. I say normally because there seem to be occasional bugs that cause stuff--particularly when debugging--not to behave the way I expected. One of those things is garbage or totally useless information in the variable view. Usually a clean rebuild of the target (or sometimes even a more drastic restarting of XCode followed by a clean rebuild) fixes the problem.
As for the other container types, it's most likely hard to efficiently view this information. For example a map is often implemented as a red-black tree. The debugger would have to know that in advance in order to properly walk the tree and show you all the keys and values. That's probably asking a lot from Xcode or GDB--especially since the former focuses more on Objective-C and plain C than C++ (hence the fact that namespaces tend to kill code completion despite their ubiquity and importance).
|
275,382 |
<p>I currently have 2 domain names that I want to setup different websites for. I am currently looking at using some free hosting that works well for my current needs but doesn't give me any way to point "mydomain.com" to the actual site. Instead I have to give users a longer, harder to remember url.</p>
<p>My proposed solution is to point my domains to my home ip and host a small ASP.NET app through IIS consisting of a redirect page that simply redirects to the appropriate site. Is there a way in ASP.NET to recognize which domain url was requested in order to know where to redirect the page to?</p>
|
[
{
"answer_id": 275388,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "<p>From asp.net code you can access the host from the request object:</p>\n\n<pre><code>if(Request.Url.Authority == \"www.site1.com\")\n Response.Redirect(...);\n</code></pre>\n\n<p>If you have access to the IIS server you can also set up two sites with different binding host names and have each redirect as you like.</p>\n"
},
{
"answer_id": 276556,
"author": "Jim",
"author_id": 681,
"author_profile": "https://Stackoverflow.com/users/681",
"pm_score": 3,
"selected": true,
"text": "<p>Here is one way to do it (as recommended by 1and1.com if you host multiple domains). Put this at the root of your web space. All of your websites will point to this root. The script below will forward the requests to the proper subfolder. It's kind of a hack, but if you don't have complete control over the IIS settings, this will work.</p>\n\n<p>Name this file default.asp:</p>\n\n<pre><code><%EnableSessionState=False\n\nhost = Request.ServerVariables(\"HTTP_HOST\")\n\nif host = \"website1.com\" or host = \"www.website1.com\" then\nresponse.redirect(\"http://website1.com/website1/default.aspx\")\n\nelseif host = \"website2.com\" or host = \"www.website2.com\" then\nresponse.redirect(\"http://website2.com/website2/default.aspx\")\n\nelse\nresponse.redirect(\"http://website1.com/\")\n\nend if\n%>\n</code></pre>\n"
}
] |
2008/11/08
|
[
"https://Stackoverflow.com/questions/275382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489/"
] |
I currently have 2 domain names that I want to setup different websites for. I am currently looking at using some free hosting that works well for my current needs but doesn't give me any way to point "mydomain.com" to the actual site. Instead I have to give users a longer, harder to remember url.
My proposed solution is to point my domains to my home ip and host a small ASP.NET app through IIS consisting of a redirect page that simply redirects to the appropriate site. Is there a way in ASP.NET to recognize which domain url was requested in order to know where to redirect the page to?
|
Here is one way to do it (as recommended by 1and1.com if you host multiple domains). Put this at the root of your web space. All of your websites will point to this root. The script below will forward the requests to the proper subfolder. It's kind of a hack, but if you don't have complete control over the IIS settings, this will work.
Name this file default.asp:
```
<%EnableSessionState=False
host = Request.ServerVariables("HTTP_HOST")
if host = "website1.com" or host = "www.website1.com" then
response.redirect("http://website1.com/website1/default.aspx")
elseif host = "website2.com" or host = "www.website2.com" then
response.redirect("http://website2.com/website2/default.aspx")
else
response.redirect("http://website1.com/")
end if
%>
```
|
275,404 |
<p>How do you split a string into tokens in C++?</p>
|
[
{
"answer_id": 275410,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on how complex the token delimiter is and if there are more than one. For easy problems, just use std::istringstream and std::getline. For more complex tasks or if you want to iterate the tokens in an STL-compliant way, use Boost's Tokenizer. Another possibility (although messier than either of these two) is to set up a while loop that calls std::string::find and updates the position of the last found token to be the start point for searching for the next. But this is probably the most bug-prone of the 3 options.</p>\n"
},
{
"answer_id": 275413,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>Try using stringstream:</p>\n\n<pre><code>std::string line(\"A line of tokens\");\nstd::stringstream lineStream(line);\n\nstd::string token;\nwhile(lineStream >> token)\n{\n}\n</code></pre>\n\n<p>Check out my answer to your last question:<br>\n<a href=\"https://stackoverflow.com/questions/275355/c-reading-file-tokens#275405\">C++ Reading file Tokens</a></p>\n"
},
{
"answer_id": 275417,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 4,
"selected": false,
"text": "<p>this works nicely for me :), it puts the results in <code>elems</code>. <code>delim</code> can be any <code>char</code>.</p>\n\n<pre><code>std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n</code></pre>\n"
},
{
"answer_id": 275674,
"author": "Imbue",
"author_id": 3175,
"author_profile": "https://Stackoverflow.com/users/3175",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the C function <a href=\"http://www.cplusplus.com/reference/clibrary/cstring/strtok.html\" rel=\"nofollow noreferrer\">strtok</a>:</p>\n\n<pre><code>/* strtok example */\n#include <stdio.h>\n#include <string.h>\n\nint main ()\n{\n char str[] =\"- This, a sample string.\";\n char * pch;\n printf (\"Splitting string \\\"%s\\\" into tokens:\\n\",str);\n pch = strtok (str,\" ,.-\");\n while (pch != NULL)\n {\n printf (\"%s\\n\",pch);\n pch = strtok (NULL, \" ,.-\");\n }\n return 0;\n}\n</code></pre>\n\n<p>The <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/tokenizer/index.html\" rel=\"nofollow noreferrer\">Boost Tokenizer</a> will also do the job:</p>\n\n<pre><code>#include<iostream>\n#include<boost/tokenizer.hpp>\n#include<string>\n\nint main(){\n using namespace std;\n using namespace boost;\n string s = \"This is, a test\";\n tokenizer<> tok(s);\n for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){\n cout << *beg << \"\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 275702,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "<p>With <a href=\"http://nuwen.net/mingw.html#download\" rel=\"nofollow noreferrer\">this Mingw distro</a> that includes Boost:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <ostream>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\nusing namespace std;\nusing namespace boost;\n\nint main() {\n vector<string> v;\n split(v, \"1=2&3=4&5=6\", is_any_of(\"=&\"));\n copy(v.begin(), v.end(), ostream_iterator<string>(cout, \"\\n\"));\n}\n</code></pre>\n"
},
{
"answer_id": 275816,
"author": "Sergey Skoblikov",
"author_id": 12151,
"author_profile": "https://Stackoverflow.com/users/12151",
"pm_score": 2,
"selected": false,
"text": "<p>See also boost::split from <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/string_algo/reference.html#header.boost.algorithm.string.split_hpp\" rel=\"nofollow noreferrer\">String Algo library</a></p>\n\n<pre>\nstring str1(\"hello abc-*-ABC-*-aBc goodbye\");\nvector<string> tokens;\nboost::split(tokens, str1, boost::is_any_of(\"-*\")); \n// tokens == { \"hello abc\",\"ABC\",\"aBc goodbye\" }\n\n</pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33481/"
] |
How do you split a string into tokens in C++?
|
this works nicely for me :), it puts the results in `elems`. `delim` can be any `char`.
```
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
```
|
275,411 |
<p>I'm writing a php program that pulls from a database source. Some of the varchars have quotes that are displaying as black diamonds with a question mark in them (�, <a href="http://www.fileformat.info/info/unicode/char/fffd/index.htm" rel="noreferrer">REPLACEMENT CHARACTER</a>, I assume from Microsoft Word text).</p>
<p>How can I use php to strip these characters out?</p>
|
[
{
"answer_id": 275420,
"author": "che",
"author_id": 7806,
"author_profile": "https://Stackoverflow.com/users/7806",
"pm_score": 1,
"selected": false,
"text": "<p>That can be caused by unicode or other charset mismatch. Try changing charset in your browser, in of the settings the text will look OK. Then it's question of how to convert your database contents to charset you use for displaying. (Which can actually be just adding utf-8 charset statement to your output.)</p>\n"
},
{
"answer_id": 275448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>If you see that character (� U+FFFD \"REPLACEMENT CHARACTER\") it usually means that the text itself is encoded in some form of single byte encoding but interpreted in one of the unicode encodings (UTF8 or UTF16).</p>\n\n<p>If it were the other way around it would (usually) look something like this: ä.</p>\n\n<p>Probably the original encoding is ISO-8859-1, also known as Latin-1. You can check this without having to change your script: Browsers give you the option to re-interpret a page in a different encoding -- in Firefox use \"View\" -> \"Character Encoding\". </p>\n\n<p>To make the browser use the correct encoding, add an HTTP header like this:</p>\n\n<pre><code>header(\"Content-Type: text/html; charset=ISO-8859-1\");\n</code></pre>\n\n<p>or put the encoding in a meta tag:</p>\n\n<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</code></pre>\n\n<p>Alternatively you could try to read from the database in another encoding (UTF-8, preferably) or convert the text with <a href=\"http://php.net/manual/function.iconv.php\" rel=\"noreferrer\"><code>iconv()</code></a>.</p>\n"
},
{
"answer_id": 275449,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 5,
"selected": false,
"text": "<p>This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.</p>\n<p>The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:</p>\n<ul>\n<li>All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).</li>\n<li>Your web-server is configured to serve files with <code>charset=iso-8859-1</code></li>\n<li>Alternatively, you can override the webservers settings from within the PHP-document, using <a href=\"http://docs.php.net/manual/en/function.header.php\" rel=\"noreferrer\"><code>header</code></a>.</li>\n<li>In addition, you <em>may</em> insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.</li>\n<li>You <em>may</em> also specify the <code>accept-charset</code> attribute on your <code><form></code> elements.</li>\n<li>Database tables are defined with encoding as latin1</li>\n<li>The database connection between PHP to and database is set to latin1</li>\n</ul>\n<p>If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.</p>\n<h3>A note on meta-tags, since everybody misunderstands what they are:</h3>\n<p>When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the <code>Content-Type</code> header, which specifies the mimetype of the file (Eg. <code>text/html</code>) as well as the encoding (aka charset).\nWhile most webservers will send a <code>Content-Type</code> header with <code>charset</code> info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with <code>http-equiv="Content-Type"</code>. It's important to realise that the meta-tag is <strong>only</strong> interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.</p>\n<p><a href=\"http://www.phpwact.org/php/i18n/charsets\" rel=\"noreferrer\">This page</a> has a very good explanation of these things.</p>\n"
},
{
"answer_id": 275467,
"author": "Daniel Cassidy",
"author_id": 31662,
"author_profile": "https://Stackoverflow.com/users/31662",
"pm_score": 3,
"selected": false,
"text": "<p>Based on your description of the problem, the data in your database is almost certainly encoded as <a href=\"http://en.wikipedia.org/wiki/Windows-1252\" rel=\"noreferrer\">Windows-1252</a>, and your page is almost certainly being served as <a href=\"http://en.wikipedia.org/wiki/ISO/IEC_8859-1\" rel=\"noreferrer\">ISO-8859-1</a>. These two character sets are equivalent except that Windows-1252 has 16 extra characters which are not present in ISO-8859-1, including left and right curly quotes.</p>\n\n<p>Assuming my analysis is correct, the simplest solution is to serve your page as Windows-1252. This will work because all characters that are in ISO-8859-1 are also in Windows-1252. In PHP you can change the encoding as follows:</p>\n\n<pre><code>header('Content-Type: text/html; charset=Windows-1252');\n</code></pre>\n\n<p>However, you really should check what character encoding you are using in your HTML files and the contents of your database, and take care to be consistent, or convert properly where this is not possible.</p>\n"
},
{
"answer_id": 275827,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 0,
"selected": false,
"text": "<p>You can also change the caracter set in your browser. Just for debug reasons.</p>\n"
},
{
"answer_id": 10023664,
"author": "ptwiggerl",
"author_id": 1057535,
"author_profile": "https://Stackoverflow.com/users/1057535",
"pm_score": 4,
"selected": false,
"text": "<p>To make sure your MYSQL connection is set to UTF-8 (or latin1, depending on what you're using), you can do this to:</p>\n\n<pre><code>$con = mysql_connect(\"localhost\",\"username\",\"password\"); \nmysql_set_charset('utf8',$con);\n</code></pre>\n\n<p>or use this to check what charset you are using: </p>\n\n<pre><code>$con = mysql_connect(\"localhost\",\"username\",\"password\"); \n$charset = mysql_client_encoding($con);\necho \"The current character set is: $charset\\n\"; \n</code></pre>\n\n<p>More info here: <a href=\"http://php.net/manual/en/function.mysql-set-charset.php\" rel=\"noreferrer\">http://php.net/manual/en/function.mysql-set-charset.php</a></p>\n"
},
{
"answer_id": 15138120,
"author": "Avatar",
"author_id": 1066234,
"author_profile": "https://Stackoverflow.com/users/1066234",
"pm_score": 6,
"selected": false,
"text": "<p>I also faced this � issue. Meanwhile I ran into three cases where it happened:</p>\n<ol>\n<li><p><strong>substr()</strong></p>\n<p>I was using <code>substr()</code> on a UTF8 string which cut UTF8 characters, thus the cut chars could not be displayed correctly. Use <code>mb_substr($utfstring, 0, 10, 'utf-8');</code> instead. <a href=\"https://stackoverflow.com/questions/9087502/php-substr-function-with-utf-8-leaves-marks-at-the-end\">Credits</a></p>\n</li>\n<li><p><strong>htmlspecialchars()</strong></p>\n<p>Another problem was using <code>htmlspecialchars()</code> on a UTF8 string. The fix is to use: <code>htmlspecialchars($utfstring, ENT_QUOTES, 'UTF-8');</code></p>\n</li>\n<li><p><strong>preg_replace()</strong></p>\n<p>Lastly I found out that <code>preg_replace()</code> can lead to problems with UTF. The code <code>$string = preg_replace('/[^A-Za-z0-9ÄäÜüÖöß]/', ' ', $string);</code> for example transformed the UTF string "F(×)=2×-3" into "F � 2� ". The fix is to use <a href=\"http://php.net/manual/en/function.mb-ereg-replace.php\" rel=\"noreferrer\"><code>mb_ereg_replace()</code></a> instead.</p>\n</li>\n</ol>\n<p>I hope this additional information will help to get rid of such problems.</p>\n"
},
{
"answer_id": 24352574,
"author": "GrafixGuy",
"author_id": 1888232,
"author_profile": "https://Stackoverflow.com/users/1888232",
"pm_score": 0,
"selected": false,
"text": "<p>Using the same charset (as suggested here) in both the database and the HTML has not worked for me... So remembering that the code is generated as HTML, I chose to use the <code>&quot;</code>(HTML code) or the <code>&#34;</code> (ISO Latin-1 code) in my database text where quotes were used. This solved the problem while providing me a quotation mark. It is odd to note that prior to this solution, only some of the quotation marks and apostrophes did not display correctly while others did, however, the special code did work in all instances.</p>\n"
},
{
"answer_id": 31690375,
"author": "DropHit",
"author_id": 1656124,
"author_profile": "https://Stackoverflow.com/users/1656124",
"pm_score": 3,
"selected": false,
"text": "<p>I chose to strip these characters out of the string by doing this - </p>\n\n<pre><code>ini_set('mbstring.substitute_character', \"none\"); \n$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');\n</code></pre>\n"
},
{
"answer_id": 32037413,
"author": "Hamlet Kraskian",
"author_id": 1531995,
"author_profile": "https://Stackoverflow.com/users/1531995",
"pm_score": 4,
"selected": false,
"text": "<p>As mentioned in earlier answers, it is happening because your text has been written to the database in <code>iso-8859-1</code> encoding, or any other format.</p>\n\n<p>So you just need to convert the data to <code>utf8</code> before outputting it. </p>\n\n<pre><code>$text = “string from database”;\n$text = utf8_encode($text);\necho $text;\n</code></pre>\n"
},
{
"answer_id": 39338349,
"author": "drtechno",
"author_id": 6797108,
"author_profile": "https://Stackoverflow.com/users/6797108",
"pm_score": 0,
"selected": false,
"text": "<p>I ran the \"detect encoding\" code after my collation change in phpmyadmin and now it comes up as Latin_1.</p>\n\n<p>but here is something I came across looking a different data anomaly in my application and how I fixed it:</p>\n\n<p>I just imported a table that has mixed encoding (with diamond question marks in some lines, and all were in the same column.) so here is my fix code. I used utf8_decode process that takes the undefined placeholder and assigns a plain question mark in the place of the \"diamond question mark \" then I used str_replace to replace the question mark with a space between quotes.\nhere is the \n[code]\n \n\n<pre><code> include 'dbconnectfile.php';\n\n //// the variable $db comes from my db connect file\n /// inx is my auto increment column\n /// broke_column is the column I need to fix\n\n $qwy = \"select inx,broke_column from Table \";\n $res = $db->query($qwy); \n\n while ($data = $res->fetch_row()) {\n for ($m=0; $m<$res->field_count; $m++) {\n if ($m==0){ \n $id=0;\n $id=$data[$m];\n echo $id;\n }else if ($m==1){ \n $fix=0;\n $fix=$data[$m];\n\n\n $fix = utf8_decode($fix);\n $fixx =str_replace(\"?\",\" \",$fix);\n\n echo $fixx;\n\n ////I echoed the data to the screen because I like to see something as I execute it :)\n }\n }\n $insert= \"UPDATE Table SET broke_column='\".$fixx.\"' where inx='\".$id.\"'\";\n $insresult= $db->query($insert);\n echo\"<br>\";\n }\n\n ?> \n</code></pre>\n"
},
{
"answer_id": 39373995,
"author": "drtechno",
"author_id": 6797108,
"author_profile": "https://Stackoverflow.com/users/6797108",
"pm_score": 1,
"selected": false,
"text": "<p>what I ended up doing in the end after I fixed my tables was to back it up and change back the settings to utf-8 then I altered my dump file so that DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci are my character set entries </p>\n\n<p>now I don't have characterset issues anymore because the database and browser are utf8.</p>\n\n<p>I figured out what caused it. It was the web page+browser effects on the DB. On the terminals that are linux (ubuntu+firefox) it was encoding the database in latin1 which is what the tabes are set. But on the windows 10+edge terminals, the entries were force coded into utf8. Also I noticed the windows 10 has issues staying with latin1 so I decided to bend with the wind and convert all to utf8.</p>\n\n<p>I figured it was a windows 10 issue because we started using win 10 terminals.\nso yet again microsoft bugs causes issues. I still don't know why the encoding changes on the forms because the browser in windows 10 shows the latin1 characterset but when it goes in its utf8 encoded and I get the data anomaly. but in linux+firefox it doesn't do that.</p>\n"
},
{
"answer_id": 39890612,
"author": "Vishal P Gothi",
"author_id": 6560809,
"author_profile": "https://Stackoverflow.com/users/6560809",
"pm_score": 2,
"selected": false,
"text": "<p>Try This Please</p>\n\n<p>mb_substr($description, 0, 490, \"UTF-8\");</p>\n"
},
{
"answer_id": 41451445,
"author": "JacobRossDev",
"author_id": 1595997,
"author_profile": "https://Stackoverflow.com/users/1595997",
"pm_score": 1,
"selected": false,
"text": "<p>This happened to work in my case:</p>\n\n<pre><code>$text = utf8_decode($text)\n</code></pre>\n\n<p>I turns the black diamond character into a question mark so you can: </p>\n\n<pre><code>$text = str_replace('?', '', utf8_decode($text));\n</code></pre>\n"
},
{
"answer_id": 41695732,
"author": "rk_programmer",
"author_id": 7430093,
"author_profile": "https://Stackoverflow.com/users/7430093",
"pm_score": 2,
"selected": false,
"text": "<p>Add this function to your variables \nutf8_encode($your variable);</p>\n"
},
{
"answer_id": 42801565,
"author": "asma",
"author_id": 7712774,
"author_profile": "https://Stackoverflow.com/users/7712774",
"pm_score": 1,
"selected": false,
"text": "<p>Just add these lines before headers.</p>\n\n<p>Accurate format of <code>.doc/docx</code> files will be retrieved:</p>\n\n<pre><code> if(ini_get('zlib.output_compression'))\n\n ini_set('zlib.output_compression', 'Off');\n ob_clean();\n</code></pre>\n"
},
{
"answer_id": 43001066,
"author": "javier_domenech",
"author_id": 2192660,
"author_profile": "https://Stackoverflow.com/users/2192660",
"pm_score": 0,
"selected": false,
"text": "<p>For global purposes.</p>\n<p>Instead of converting, codifying, decodifying each text I prefer to let them as they are and instead change the server php settings.\nSo,</p>\n<ol>\n<li><p>Let the diamonds</p>\n</li>\n<li><p>From the browser, on the view menu select\n"text encoding" and find the one which let's you see your text\ncorrectly.</p>\n</li>\n<li><p>Edit your php.ini and add:</p>\n<p><code>default_charset = "ISO-8859-1"</code></p>\n</li>\n</ol>\n<p>or instead of ISO-8859 the one which fits your text encoding.</p>\n"
},
{
"answer_id": 44410006,
"author": "Utmost Creator",
"author_id": 6901693,
"author_profile": "https://Stackoverflow.com/users/6901693",
"pm_score": 1,
"selected": false,
"text": "<p>When you extract data from anywhere you should use functions with the prefix <code>md_FUNC_NAME</code>.</p>\n\n<p>Had the same problem it helped me out.</p>\n\n<p>Or you can find the code of this symbol and use regexp to delete these symbols.</p>\n"
},
{
"answer_id": 45897517,
"author": "Dheeraj Verma",
"author_id": 2275052,
"author_profile": "https://Stackoverflow.com/users/2275052",
"pm_score": -1,
"selected": false,
"text": "<p>Go to your phpmyadmin and select your database and just increase the length/value of that table's field to 500 or 1000 it will solve your problem.</p>\n"
},
{
"answer_id": 46633907,
"author": "Prasant Kumar",
"author_id": 5231984,
"author_profile": "https://Stackoverflow.com/users/5231984",
"pm_score": 2,
"selected": false,
"text": "<p>This will help you. Put this inside <code><head></code> tag</p>\n\n<pre><code><meta charset=\"iso-8859-1\">\n</code></pre>\n"
},
{
"answer_id": 56009343,
"author": "Harshil Kaneria",
"author_id": 10949608,
"author_profile": "https://Stackoverflow.com/users/10949608",
"pm_score": 3,
"selected": false,
"text": "<p>Just Paste This Code In Starting to The Top of Page.</p>\n\n<pre><code><?php\nheader(\"Content-Type: text/html; charset=ISO-8859-1\");\n?>\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm writing a php program that pulls from a database source. Some of the varchars have quotes that are displaying as black diamonds with a question mark in them (�, [REPLACEMENT CHARACTER](http://www.fileformat.info/info/unicode/char/fffd/index.htm), I assume from Microsoft Word text).
How can I use php to strip these characters out?
|
If you see that character (� U+FFFD "REPLACEMENT CHARACTER") it usually means that the text itself is encoded in some form of single byte encoding but interpreted in one of the unicode encodings (UTF8 or UTF16).
If it were the other way around it would (usually) look something like this: ä.
Probably the original encoding is ISO-8859-1, also known as Latin-1. You can check this without having to change your script: Browsers give you the option to re-interpret a page in a different encoding -- in Firefox use "View" -> "Character Encoding".
To make the browser use the correct encoding, add an HTTP header like this:
```
header("Content-Type: text/html; charset=ISO-8859-1");
```
or put the encoding in a meta tag:
```
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
```
Alternatively you could try to read from the database in another encoding (UTF-8, preferably) or convert the text with [`iconv()`](http://php.net/manual/function.iconv.php).
|
275,421 |
<p>I trying to implement a typical languages menu where users can select the language they want to view the site in through a menu that appears throughout all pages in the site.</p>
<p>The menu will appear on multiple master pages (currently one for pages where users are logged in and one for pages where users are not).</p>
<p>My current implementation is having a single master page base class (let's call it MasterBase). MasterBase has an event</p>
<pre><code>public event LanguageChangedEventHandler LanguageChanged;
</code></pre>
<p>where LanguagedChangedEventHandler is simply defined as</p>
<pre><code>public delegate void LanguageChangedEventHandler(string NewCulture);
</code></pre>
<p>MasterBase also has an overridable method</p>
<pre><code>protected virtual void OnLanguageChanged(string NewCulture)
</code></pre>
<p>which just basically fires the event.</p>
<p>Each master page that inherits MasterBase overrides OnLanguageChanged and does the usual stuff like set the Thread's CurrentUICulture and the language cookie then does a </p>
<pre><code>Server.Transfer(this.Page.AppRelativeVirtualPath, true);
</code></pre>
<p>to get the page to reload with localized values for the new culture. On the master page for logged in users it also updates the user's language pref in the db.</p>
<p>Each language option is currently a LinkButton on a master page that inherits from MasterBase. When the link is clicked it calls the base OnLanguagedChanged method passing in the correct culture info. E.g.</p>
<pre><code>protected void btnEnglish_Click(object sender, EventArgs e) {
this.OnLanguageChanged("en-US");
}
</code></pre>
<p>Each page that needs to handle a language change then has some code in the page load that looks like...</p>
<pre><code>((MasterBase)this.Master).LanguageChanged += this.Page_OnLanguageChanged;
// Where Page_OnLanguageChanged has the signature of LanguageChangedEventHandler
// and has stuff like reloading options in a drop down using the new language.
</code></pre>
<p>Quite a convoluted 'framework' =)</p>
<ol>
<li>Firstly it's hard for new developers to know they have to hook up a method to the MasterBase's LanguageChanged event to handle language changes. Yes, we do document it. But still it's not something straightforward and obvious.</li>
<li>Secondly, all language changes are post backs. This is problematic especially when you want to navigate back with the browser Back button.</li>
</ol>
<p>I'm looking for a more elegant solution. One that doesn't have both the problems above and also handles my current requirements.</p>
<p>Greatly appreciate any suggestions. Thanks.</p>
|
[
{
"answer_id": 275492,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 4,
"selected": true,
"text": "<p>How about <a href=\"http://www.ericmmartin.com/projects/simplemodal/\" rel=\"nofollow noreferrer\">SimpleModal</a> for jQuery?</p>\n"
},
{
"answer_id": 2289367,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 1,
"selected": false,
"text": "<p>I've found <a href=\"http://dev.iceburg.net/jquery/jqModal/\" rel=\"nofollow noreferrer\">jqModal</a> [for jQuery] to be very easy to work with.</p>\n"
},
{
"answer_id": 4686465,
"author": "Ryan Anderson",
"author_id": 173949,
"author_profile": "https://Stackoverflow.com/users/173949",
"pm_score": 1,
"selected": false,
"text": "<p>I like the Dialog in <a href=\"http://jqueryui.com/demos/dialog/\" rel=\"nofollow noreferrer\">jQueryUI</a></p>\n<p>Easy to use, clean.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8280/"
] |
I trying to implement a typical languages menu where users can select the language they want to view the site in through a menu that appears throughout all pages in the site.
The menu will appear on multiple master pages (currently one for pages where users are logged in and one for pages where users are not).
My current implementation is having a single master page base class (let's call it MasterBase). MasterBase has an event
```
public event LanguageChangedEventHandler LanguageChanged;
```
where LanguagedChangedEventHandler is simply defined as
```
public delegate void LanguageChangedEventHandler(string NewCulture);
```
MasterBase also has an overridable method
```
protected virtual void OnLanguageChanged(string NewCulture)
```
which just basically fires the event.
Each master page that inherits MasterBase overrides OnLanguageChanged and does the usual stuff like set the Thread's CurrentUICulture and the language cookie then does a
```
Server.Transfer(this.Page.AppRelativeVirtualPath, true);
```
to get the page to reload with localized values for the new culture. On the master page for logged in users it also updates the user's language pref in the db.
Each language option is currently a LinkButton on a master page that inherits from MasterBase. When the link is clicked it calls the base OnLanguagedChanged method passing in the correct culture info. E.g.
```
protected void btnEnglish_Click(object sender, EventArgs e) {
this.OnLanguageChanged("en-US");
}
```
Each page that needs to handle a language change then has some code in the page load that looks like...
```
((MasterBase)this.Master).LanguageChanged += this.Page_OnLanguageChanged;
// Where Page_OnLanguageChanged has the signature of LanguageChangedEventHandler
// and has stuff like reloading options in a drop down using the new language.
```
Quite a convoluted 'framework' =)
1. Firstly it's hard for new developers to know they have to hook up a method to the MasterBase's LanguageChanged event to handle language changes. Yes, we do document it. But still it's not something straightforward and obvious.
2. Secondly, all language changes are post backs. This is problematic especially when you want to navigate back with the browser Back button.
I'm looking for a more elegant solution. One that doesn't have both the problems above and also handles my current requirements.
Greatly appreciate any suggestions. Thanks.
|
How about [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/) for jQuery?
|
275,437 |
<p>I want to display the "infinity" symbol using </p>
<pre><code>CGContextSelectFont(context, "HelveticaNeue", textSize, kCGEncodingMacRoman);
CGContextShowTextAtPoint(context, myCenter.x, myCenter.y + textHeight, [sName cStringUsingEncoding:NSMacOSRomanStringEncoding], [sName length]);
</code></pre>
<p>It is displayed as a square box, or a circle. I have found out this symbol is in decimal 176 and 221E in Hexadecimal format. I am using Helvetica as my font, and have tried others with no luck. Is this a problem with the encoding I am using?</p>
|
[
{
"answer_id": 275447,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 5,
"selected": true,
"text": "<p>It turns out that CGContextSelectFont only supports MacRoman encoding, which is basically has only a small set of characters. In order to display Unicode characters in a string, you have to use CGSetFont or the Cocoa drawing system. CGSetFont requires that you use Cocoa anyway to map characters to glyphs and then draw the glyphs using CGContextShowGlyphsAtPoint. I recommend that you look into other ways to draw these strings if you really need to display Unicode characters.</p>\n\n<p>This code basically will display the infinity symbol:</p>\n\n<pre><code>- (void)drawRect:(CGRect)rect {\n unichar inf = 0x221E; // infinity symbol\n NSString* sName = [[NSString alloc] initWithCharacters:&inf length:1];\n UIFont* font = [UIFont fontWithName:@\"Helvetica\" size:32.0];\n [sName drawInRect:CGRectMake(20, 20, 40, 40)\n withFont:font];\n [sName release];\n}\n</code></pre>\n\n<p>Also note that on the iPhone (and on the Mac) Helvetica Neue actually does not exist... its name just maps back to standard Helvetica. See the table at <a href=\"http://daringfireball.net/misc/2007/07/iphone-osx-fonts\" rel=\"noreferrer\">http://daringfireball.net/misc/2007/07/iphone-osx-fonts</a> for more information on available fonts on the iPhone.</p>\n"
},
{
"answer_id": 392612,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth noting that you can still use the CGContext functions alongside -[NSString drawWithRect:] and its cousins. For example, the following code draws a string (which can include any characters, including the infinity symbol which started this thread) with 50%-opaque black:</p>\n\n<pre><code>CGContextSaveGState(context);\nCGContextSetRGBFillColor(context, 0, 0, 0, 0.5);\n[self.text drawInRect:targetRect withFont:self.font];\nCGContextRestoreGState(context);\n</code></pre>\n"
},
{
"answer_id": 3305772,
"author": "miguel.de.icaza",
"author_id": 16929,
"author_profile": "https://Stackoverflow.com/users/16929",
"pm_score": 0,
"selected": false,
"text": "<p>You want to avoid drawInRect:withFont: (in MonoTouch: DrawString (string, RectangelF, UIFont font) as this API up until iPhoneOS 4.0 does not render strings that might contain certain unicode characters (like dingbats) and will silently cut rendering at that point.</p>\n\n<p>Instead you must use drawInRect:withFont:lineBreakMode:alignment: (in MonoTouch this is the DrawString (string msg, RectangleF rect, UIFont font, UILineBreakMode breakMode, UITextAlignment align) method) as this renders properly.</p>\n\n<p>In addition, not all fonts on the iPhone is a complete set of fonts, you can use the following reference:</p>\n\n<p><a href=\"http://daringfireball.net/misc/2007/07/iphone-osx-fonts\" rel=\"nofollow noreferrer\">http://daringfireball.net/misc/2007/07/iphone-osx-fonts</a></p>\n\n<p>For a list of fonts that have the complete set of characters.</p>\n"
},
{
"answer_id": 17331764,
"author": "Ian Vink",
"author_id": 172861,
"author_profile": "https://Stackoverflow.com/users/172861",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the MonoTouch answer:</p>\n\n<pre><code>UIGraphics.PushContext (mBmpContext);\nmBmpContext.SetRGBFillColor(1f,1f,1f,1f);\nvar font = UIFont.FromName (\"Arial\", 30);\nusing (var nsstr = new NSString (\"äöü ÜÖÄ\")){\n nsstr.DrawString (new PointF (10, 400), font);\n}\nUIGraphics.PopContext ()\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29642/"
] |
I want to display the "infinity" symbol using
```
CGContextSelectFont(context, "HelveticaNeue", textSize, kCGEncodingMacRoman);
CGContextShowTextAtPoint(context, myCenter.x, myCenter.y + textHeight, [sName cStringUsingEncoding:NSMacOSRomanStringEncoding], [sName length]);
```
It is displayed as a square box, or a circle. I have found out this symbol is in decimal 176 and 221E in Hexadecimal format. I am using Helvetica as my font, and have tried others with no luck. Is this a problem with the encoding I am using?
|
It turns out that CGContextSelectFont only supports MacRoman encoding, which is basically has only a small set of characters. In order to display Unicode characters in a string, you have to use CGSetFont or the Cocoa drawing system. CGSetFont requires that you use Cocoa anyway to map characters to glyphs and then draw the glyphs using CGContextShowGlyphsAtPoint. I recommend that you look into other ways to draw these strings if you really need to display Unicode characters.
This code basically will display the infinity symbol:
```
- (void)drawRect:(CGRect)rect {
unichar inf = 0x221E; // infinity symbol
NSString* sName = [[NSString alloc] initWithCharacters:&inf length:1];
UIFont* font = [UIFont fontWithName:@"Helvetica" size:32.0];
[sName drawInRect:CGRectMake(20, 20, 40, 40)
withFont:font];
[sName release];
}
```
Also note that on the iPhone (and on the Mac) Helvetica Neue actually does not exist... its name just maps back to standard Helvetica. See the table at <http://daringfireball.net/misc/2007/07/iphone-osx-fonts> for more information on available fonts on the iPhone.
|
275,439 |
<p>Is there a problem using VMware on Windows to host a virtual linux box running iptables? I have a configuration that seems to work on physical hardware but is flaky under VMware.</p>
<p>I'm using VMware to run a virtual linux 2.6.24 machine on a Windows 2003 Server host. The linux application is essentially a NATting router that runs <code>iptables</code>. The rules in the <code>nat</code> table include:</p>
<pre><code>Chain foo_pre
target prot opt in out source destination
LOG all -- * * 0.0.0.0/0 0.0.0.0/0 [options here]
LOG all -- * * 0.0.0.0/0 10.10.1.33 [options here]
DNAT all -- * * 0.0.0.0/0 10.10.1.33 tcp dpt:80 to:192.168.0.33:8080
Chain PREROUTING
target prot opt in out source destination
foo_pre all -- * * 0.0.0.0/0 0.0.0.0/0
</code></pre>
<p>I'm seeing the incoming packets to 10.10.1.33:80 using <code>tcpdump</code>, and the first <code>LOG</code> generates messages, but neither the <code>DNAT</code> or the second <code>LOG</code> show the packets registering on their packet counters, the second <code>LOG</code> generates no messages, and <code>tcpdump</code> doesn't show the packets to 192.168.0.33.</p>
<p>The <code>eth0</code> adapter is on the 10.10.0.0/16 network with a default gateway of 10.10.1.1; it has a secondary address of 10.10.1.33/32. <code>/proc/sys/net/ipv4/config/eth0/forwarding</code> is set to 1.</p>
<p>Is VMware the culprit, or am I missing something? Thanks!</p>
<hr>
<p>Update: we've simplified the test environment. No NAT rules at all, just a linux VM running under a Win2k3 Server host. Test steps:</p>
<ol>
<li><p>VM is bridged to host NIC. VM and host are on the same subnet, with the same default gateway as above.</p></li>
<li><p>VM communicates with devices both on and off its subnet: ICMP, TCP, UDP. Communication is bidirectional: it doesn't matter which equipment initiates it.</p></li>
<li><p>Engineer power-cycled the default gateway while poking at the system.</p></li>
<li><p>VM now communicates <em>only</em> with devices on its subnet. Any attempt to communicate through the gateway to the <em>same equipment</em> from Step 2 <em>fails to put packets on the wire.</em> tcpdump on eth0 on the VM shows outgoing packets with no response; WireShark on the host shows <em>nothing</em> on the physical NIC.</p></li>
<li><p>Stopping and restarting the VM does not change its behavior. Stopping the VM and replacing it with a <em>different</em> VM with appropriate IP address, <em>etc. does not change the behavior.</em></p></li>
<li><p>The Win2k3 host continues to communicate normally, both on and off its subnet.</p></li>
</ol>
<p>I can only conclude from this that "something happens" between the VM and the host: in the VMware drivers, or in the host's network stacks. I'm off to scour the web again.... it's hard to imagine we're the first to observe this.</p>
<p>Updates as they come. Thanks for your thoughts and discussion.</p>
|
[
{
"answer_id": 279254,
"author": "Magus",
"author_id": 2188,
"author_profile": "https://Stackoverflow.com/users/2188",
"pm_score": 1,
"selected": false,
"text": "<p>Your second log line is trying to match packets sent to 10.10.1.33, but you changed the destination address to 192.168.0.33 on the line above it. </p>\n\n<p>I'm not sure why you don't see the outgoing packets in tcpdump yet. I assume you're running tcpdump on the linux VM itself. Is the VM sending packets on the same interface it's receiving, or is there a second virtual ethernet adapter? What machines are the various IP addresses assigned to (other than 10.10.1.33).</p>\n\n<p>Regarding update:\nI gather you're not using DHCP (people usually don't bother when using static IP addresses). Also, it sounds like the gateway sees one NIC using two IP addresses. Normally that should be ok, but it's always the details that get you. </p>\n\n<p>Is it possible the gateway will only assign one IP address to the NIC and is ignoring traffic from the VM?</p>\n"
},
{
"answer_id": 280030,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>After your edit, I suggest an experiment: on your physical machine, configure your NIC to disable all hardware acceleration.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29157/"
] |
Is there a problem using VMware on Windows to host a virtual linux box running iptables? I have a configuration that seems to work on physical hardware but is flaky under VMware.
I'm using VMware to run a virtual linux 2.6.24 machine on a Windows 2003 Server host. The linux application is essentially a NATting router that runs `iptables`. The rules in the `nat` table include:
```
Chain foo_pre
target prot opt in out source destination
LOG all -- * * 0.0.0.0/0 0.0.0.0/0 [options here]
LOG all -- * * 0.0.0.0/0 10.10.1.33 [options here]
DNAT all -- * * 0.0.0.0/0 10.10.1.33 tcp dpt:80 to:192.168.0.33:8080
Chain PREROUTING
target prot opt in out source destination
foo_pre all -- * * 0.0.0.0/0 0.0.0.0/0
```
I'm seeing the incoming packets to 10.10.1.33:80 using `tcpdump`, and the first `LOG` generates messages, but neither the `DNAT` or the second `LOG` show the packets registering on their packet counters, the second `LOG` generates no messages, and `tcpdump` doesn't show the packets to 192.168.0.33.
The `eth0` adapter is on the 10.10.0.0/16 network with a default gateway of 10.10.1.1; it has a secondary address of 10.10.1.33/32. `/proc/sys/net/ipv4/config/eth0/forwarding` is set to 1.
Is VMware the culprit, or am I missing something? Thanks!
---
Update: we've simplified the test environment. No NAT rules at all, just a linux VM running under a Win2k3 Server host. Test steps:
1. VM is bridged to host NIC. VM and host are on the same subnet, with the same default gateway as above.
2. VM communicates with devices both on and off its subnet: ICMP, TCP, UDP. Communication is bidirectional: it doesn't matter which equipment initiates it.
3. Engineer power-cycled the default gateway while poking at the system.
4. VM now communicates *only* with devices on its subnet. Any attempt to communicate through the gateway to the *same equipment* from Step 2 *fails to put packets on the wire.* tcpdump on eth0 on the VM shows outgoing packets with no response; WireShark on the host shows *nothing* on the physical NIC.
5. Stopping and restarting the VM does not change its behavior. Stopping the VM and replacing it with a *different* VM with appropriate IP address, *etc. does not change the behavior.*
6. The Win2k3 host continues to communicate normally, both on and off its subnet.
I can only conclude from this that "something happens" between the VM and the host: in the VMware drivers, or in the host's network stacks. I'm off to scour the web again.... it's hard to imagine we're the first to observe this.
Updates as they come. Thanks for your thoughts and discussion.
|
Your second log line is trying to match packets sent to 10.10.1.33, but you changed the destination address to 192.168.0.33 on the line above it.
I'm not sure why you don't see the outgoing packets in tcpdump yet. I assume you're running tcpdump on the linux VM itself. Is the VM sending packets on the same interface it's receiving, or is there a second virtual ethernet adapter? What machines are the various IP addresses assigned to (other than 10.10.1.33).
Regarding update:
I gather you're not using DHCP (people usually don't bother when using static IP addresses). Also, it sounds like the gateway sees one NIC using two IP addresses. Normally that should be ok, but it's always the details that get you.
Is it possible the gateway will only assign one IP address to the NIC and is ignoring traffic from the VM?
|
275,442 |
<p>How can I make a local drive visible to a Windows XP VMWare image?</p>
<p>Preferably, I'd like to make local drives available as Drive Letters within the VM Ware Image.</p>
|
[
{
"answer_id": 275443,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p>Use samba (linux host) or sharing (windows host), then map them as network drives on the virtual machine.</p>\n"
},
{
"answer_id": 275451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>If both OSs are windows:</p>\n\n<pre><code>vm > settings > options > shared folders\n</code></pre>\n\n<p>That way you can map a drive in the virtual machine as a folder on the host. :)</p>\n"
},
{
"answer_id": 10649033,
"author": "ntg",
"author_id": 508907,
"author_profile": "https://Stackoverflow.com/users/508907",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to really make the drive visible (e.g to use gparted etc.), and not just copy some files:</p>\n\n<p>You can create a pseudo-vmdk that will in fact be a link to an existing physical drive ( or one/more of its partitions)\nThe command is e.g.</p>\n\n<pre><code>VBoxManage internalcommands createrawvmdk -filename mydrive.vmdk -rawdisk \\\\.\\PhysicalDrive0\n</code></pre>\n\n<p>This maps the first physical drive as a whole.\nYou have to run this as root/admin (for win7 start a cmd.exe as admin, and cd to the directory where you have vmware)</p>\n\n<p>(To map partitions3,4 only: -partitions 3,4)</p>\n\n<p>Then map the vmdk to a drive in the vm, and presto!</p>\n"
},
{
"answer_id": 20390176,
"author": "user3063803",
"author_id": 3063803,
"author_profile": "https://Stackoverflow.com/users/3063803",
"pm_score": 0,
"selected": false,
"text": "<p>vm > settings > options > shared folders > In this tab you can choose which way it will work. Even do mapping!</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9467/"
] |
How can I make a local drive visible to a Windows XP VMWare image?
Preferably, I'd like to make local drives available as Drive Letters within the VM Ware Image.
|
If both OSs are windows:
```
vm > settings > options > shared folders
```
That way you can map a drive in the virtual machine as a folder on the host. :)
|
275,444 |
<p>What are the things that Medium Trust stops you from doing? For example, I've already learned that Medium Trust stops you from using System.IO.Path.GetTempPath(). What other things like that?</p>
|
[
{
"answer_id": 275445,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 2,
"selected": false,
"text": "<p>Who can be sure? That's why you should develop with a trust level of medium set in your web.config.</p>\n\n<pre><code> <trust level=\"Full|High|Medium|Low|Minimal\" />\n</code></pre>\n"
},
{
"answer_id": 275454,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>Most shared hosts don't use a true medium trust environment because it restricts some things that are just too vital. Others restrict some extra settings for their own anal reasons.</p>\n\n<p>The best thing you can do is ask your host what settings they use for ASPNET. Ask for the specs of the trust level they're using. Find out the memory limits. Once you've got those details you should be able to replicate the scenario at a local level.</p>\n\n<p>If they won't tell you, just set your app to run in medium trust but it (obviously) won't necessarily work if they're using a modified trust level.</p>\n\n<p>Here is <a href=\"http://learn.iis.net/page.aspx/50/aspnet/\" rel=\"nofollow noreferrer\">some information on setting trust levels in IIS</a>.</p>\n\n<p>In general the only issue I've run into is: If you're pushing assemblies, make sure you allow partially trusted requests (it's an Assembly meta-tag) otherwise you won't be able to use them.</p>\n\n<p>Here's an extract of <a href=\"http://help.godaddy.com/article/1039\" rel=\"nofollow noreferrer\">GoDaddy's Medium Trust information page</a>:</p>\n\n<blockquote>\n <p>Applications operating under a Medium\n trust level have no registry access,\n no access to the Windows event log,\n and cannot use ReflectionPermission\n (but can use Reflection). Such\n applications can communicate only with\n a defined range of network addresses\n and file system access is limited to\n the application's virtual directory\n hierarchy.</p>\n \n <p>Using a Medium trust level prevents\n applications from accessing shared\n system resources and eliminates the\n potential for application\n interference. Adding OleDbPermission\n and OdbcPermission allows applications\n to use those data providers to access\n databases. WebPermission is modified\n to allow outbound http and https\n traffic.</p>\n</blockquote>\n\n<p>That might not map exactly to what you'll have to work around with your host (unless you're with GoDaddy) but it's a typical example.</p>\n"
},
{
"answer_id": 275512,
"author": "Bless Yahu",
"author_id": 32120,
"author_profile": "https://Stackoverflow.com/users/32120",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure any third party libraries/frameworks (Castle comes to mind) are build (or can be built) in medium trust.</p>\n"
},
{
"answer_id": 275533,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 3,
"selected": true,
"text": "<p>Here's how to learn about and resolve trust issues.</p>\n\n<p>1) Search your Windows\\Microsoft.NET\\Framework[YOUR VERSION]\\CONFIG folders for the files:</p>\n\n<ul>\n<li>web.config (this is the root config file)</li>\n<li>web_mediumtrust.config </li>\n<li>web_hightrust.config </li>\n</ul>\n\n<p>2) Change the web.config to say </p>\n\n<pre><code><trust level=\"Medium\" originUrl=\"\" />\n</code></pre>\n\n<p>3) Try your ASP.NET app. Mine failed with a permission error. </p>\n\n<p>4) Diff the web_mediumtrust.config and web_hightrust.config in a diff tool, like WinMerge.</p>\n\n<p>5) Copy settings from the high to the medium one at a time and see how they affect your app. In my case, the error message referred to ConfigurationPermission, so it was easy to diagnose.</p>\n\n<p>If you can pin down the precise lines in the web_mediumtrust.config file that are blocking you, then maybe you can share that with your hosting company and have a better chance of working things out.</p>\n\n<p>More documentation here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/aa302425.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa302425.aspx</a></p>\n\n<p>@Oli, my app <em>IS</em> hosted at GoDaddy and I had to do some workarounds in code when I started using Lucene.NET. I had to modify the Lucene.NET source code to not use GetTempPath and System.IO.FileInfo.</p>\n"
},
{
"answer_id": 355093,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The system.runtime.serialization library is completely unavailable in medium trust. </p>\n\n<p>I coded around this for json serialization/deserialization and found out the hard way. It took a week to get an associate to confirm that medium trust restrictions were to blame. I ended up switching hosting companies as a result. </p>\n"
},
{
"answer_id": 446909,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 0,
"selected": false,
"text": "<p>In medium trust, at least at my host, P/INVOKE calls are unavailable, ie using <code>[DLLImport]</code> to call a COM component is not going to work.</p>\n\n<p>-Edoode</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
What are the things that Medium Trust stops you from doing? For example, I've already learned that Medium Trust stops you from using System.IO.Path.GetTempPath(). What other things like that?
|
Here's how to learn about and resolve trust issues.
1) Search your Windows\Microsoft.NET\Framework[YOUR VERSION]\CONFIG folders for the files:
* web.config (this is the root config file)
* web\_mediumtrust.config
* web\_hightrust.config
2) Change the web.config to say
```
<trust level="Medium" originUrl="" />
```
3) Try your ASP.NET app. Mine failed with a permission error.
4) Diff the web\_mediumtrust.config and web\_hightrust.config in a diff tool, like WinMerge.
5) Copy settings from the high to the medium one at a time and see how they affect your app. In my case, the error message referred to ConfigurationPermission, so it was easy to diagnose.
If you can pin down the precise lines in the web\_mediumtrust.config file that are blocking you, then maybe you can share that with your hosting company and have a better chance of working things out.
More documentation here:
<http://msdn.microsoft.com/en-us/library/aa302425.aspx>
@Oli, my app *IS* hosted at GoDaddy and I had to do some workarounds in code when I started using Lucene.NET. I had to modify the Lucene.NET source code to not use GetTempPath and System.IO.FileInfo.
|
275,453 |
<p>I can't seem to get a scrollbar to work in an inner stack/flow. Does anyone know how to?</p>
|
[
{
"answer_id": 281506,
"author": "Ben5e",
"author_id": 36333,
"author_profile": "https://Stackoverflow.com/users/36333",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not sure what exactly you mean by \"an inner stack/flow\", but we use iframes for our subpane windows which has a scrolling attribute you can set. Otherwise you can use a javascript framework like YUI to get subpane windows that can allow scrolling capabilities.</p>\n"
},
{
"answer_id": 358198,
"author": "user45200",
"author_id": 45200,
"author_profile": "https://Stackoverflow.com/users/45200",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a <code><div></code> tag, and then have CSS as such:</p>\n\n<pre><code>#my_div {\n width: [some_width]px;\n height: [some_height]px;\n overflow: auto;\n}\n</code></pre>\n"
},
{
"answer_id": 610273,
"author": "Sergei Silnov",
"author_id": 73642,
"author_profile": "https://Stackoverflow.com/users/73642",
"pm_score": 3,
"selected": false,
"text": "<p>Just fix height and add \":scroll => true\" parameter:</p>\n\n<pre><code>Shoes.app(:title => \"Scrolll!\" ) do\n flow :margin => 10 do\n stack :width => \"150px\", :height => \"200px\", :scroll => true do\n para \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\",\n end\n end\nend\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35852/"
] |
I can't seem to get a scrollbar to work in an inner stack/flow. Does anyone know how to?
|
Just fix height and add ":scroll => true" parameter:
```
Shoes.app(:title => "Scrolll!" ) do
flow :margin => 10 do
stack :width => "150px", :height => "200px", :scroll => true do
para "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love", "all you need is love",
end
end
end
```
|
275,456 |
<p>Working with a traditional listener callback model. I have several listeners that collect various stuff. Each listener's collected stuff is inside the listener in internal structures.</p>
<p>The problem is that I want some of the listeners to be aware of some of the "stuff" in the other listeners.</p>
<p>I enforce listener registration order, so if I knowingly register events in some order a later listener can be sure that a previously listener updated its stuff and somehow access it to do more stuff. </p>
<p>My first attempt at this is to have each listener store a reference to the listeners upon which it depends. So I register listeners in the order of those without dependencies to those with prior-registered dependencies, and then set the references between the listeners in various methods.</p>
<p>I am starting to realize how bad this feels and I was wondering if somehow has been down this road before. What would be a more appropriate pattern when one of the listeners needs to access stuff in another?</p>
<p>Here is some pseudocode to illustrate:</p>
<pre><code>interface Listener { onEvent(char e); }
class A implements Listener {
private int count;
public void onEvent(char e) { if(e == 'a') count++; }
public int getCount() { return count; }
}
class B implements Listener {
private int count;
// private A a;
// private void setA(A a) { this.a = a; }
public void onEvent(char e) { if(e == 'b') count++; }
public int getCount() { return count; }
public int getAPlusBCount() {
// We know B count, but we don't know A so how would we change this
// so B is A aware? Or not even aware, just somehow coupled? This
// is the question
// return a.getCount() + count;
}
public void doConditionalHere() {
// Do some condition in B that relies on the state of data in A
int acount = 0; // a.getCount(); ???
if(acount % 2 == 0) {
this.count--;
}
}
}
class Run {
A a = new A();
B b = new B();
List listeners = new List();
listeners.add(a);
listeners.add(b);
// The ugly way I add coupling right now is to keep a reference to A
// inside B. It's commented out because I am hoping there is a more intelligent approach
// b.setA(a);
for(char c : "ababbabab") {
for(listener : listeners) {
listener.onEvent(c);
}
}
}
</code></pre>
|
[
{
"answer_id": 275470,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "<p>You've describing a lot of coupling here. Best would be to eliminate all this back-channel dependency, but failing that maybe you could have those with dependencies listening not on the initial listener list, but on whatever they are dependent on. Or you could have them wait till they have all the signals.</p>\n\n<p>You could automate the dependency management by having the listeners identify who they are dependent upon. The listener list would be ordered not by insertion order, but to insure dependent objects follow their dependency. Your listener interface would look something like this:</p>\n\n<pre><code>interface Listener {\n String getId();\n Collection<String> getDependencies();\n onEvent(char e);\n}\n</code></pre>\n\n<p>Or just have the references, like so:</p>\n\n<pre><code>interface Listener {\n Collection<Listener> getDependencies();\n onEvent(char e);\n}\n</code></pre>\n"
},
{
"answer_id": 276958,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>\"How would we change this so that Listener B is Listener A aware? Or not even aware, just somehow coupled?\"</p>\n\n<p>You don't often want to couple two \"peer\" objects like this. You want two peers to depend on something common.</p>\n\n<p>The deeper question is what does Listener A or Listener B do with all the information they collect?</p>\n\n<p>A Listener often does two things: it collects data and it takes action. Often these two things need to be separated. Listeners should listen and collect and do little more. Some other object(s) can be activated by a Listener.</p>\n\n<p>What you may have is just one listener which has several actions (A and B). The listener can then provide appropriate counts to A as well as B. It provides an 'a' count to A. It provides an 'a' or 'b' count to B.</p>\n"
},
{
"answer_id": 279233,
"author": "Sandman",
"author_id": 19911,
"author_profile": "https://Stackoverflow.com/users/19911",
"pm_score": 2,
"selected": true,
"text": "<p>Why not have a central object that will keep track of how many times the onEvent method was fired for all the listener classes</p>\n\n<pre><code> public interface CountObserver {\n\n public void updateCount(String className);\n public int getCount(String className);\n}\n\npublic class CentralObserver implements CountObserver {\n\n private int aCount;\n private int bCount;\n\n public void updateCount(String className) {\n\n //There's probably a better way to do this than using\n //all these if-elses, but you'll get the idea.\n\n if (className.equals(\"AclassName\")) {\n aCount++;\n }\n else if (className.equals(\"BclassName\")) {\n bCount++;\n }\n }\n\n public int getCount(String className) {\n\n if (className.equals(\"AclassName\")) {\n return aCount;\n }\n else if (className.equals(\"BclassName\")) {\n return bCount;\n }\n}\n\nclass A implements Listener {\n\n CountObserver countObserver;\n\n public void registerObserver (CountObserver countObserver) {\n\n this.countObserver = countObserver;\n }\n\n public void onEvent(char e) {\n\n if(e == 'a') {\n\n countObserver.updateCount (this.getClass.getName);\n }\n }\n\n}\n\n//Same thing for B or any other class implementing Listener. Your Listener interface should, of \n\n//course, have a method signature for the registerObserver method which all the listener classes \n\n//will implement.\n\nclass Run {\n\n private A a;\n private B b; \n private CountObserver centralObserver;\n\n public runProgram () {\n\n centralObserver = new CentralObserver();\n a.registerObserver(centralObserver);\n b.registerObserver(centralObserver);\n\n //run OnEvent method for A a couple of times, then for B\n\n }\n\n public int getAcount () {\n\n return centralObserver.getCount(a.getClass.getName());\n }\n\n public int getBcount () {\n\n return centralObserver.getCount(b.getClass.getName());\n }\n} \n //To get the sum of all the counts just call getAcount + getBcount. Of course, you can always add more listeners and more getXCount methods\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
] |
Working with a traditional listener callback model. I have several listeners that collect various stuff. Each listener's collected stuff is inside the listener in internal structures.
The problem is that I want some of the listeners to be aware of some of the "stuff" in the other listeners.
I enforce listener registration order, so if I knowingly register events in some order a later listener can be sure that a previously listener updated its stuff and somehow access it to do more stuff.
My first attempt at this is to have each listener store a reference to the listeners upon which it depends. So I register listeners in the order of those without dependencies to those with prior-registered dependencies, and then set the references between the listeners in various methods.
I am starting to realize how bad this feels and I was wondering if somehow has been down this road before. What would be a more appropriate pattern when one of the listeners needs to access stuff in another?
Here is some pseudocode to illustrate:
```
interface Listener { onEvent(char e); }
class A implements Listener {
private int count;
public void onEvent(char e) { if(e == 'a') count++; }
public int getCount() { return count; }
}
class B implements Listener {
private int count;
// private A a;
// private void setA(A a) { this.a = a; }
public void onEvent(char e) { if(e == 'b') count++; }
public int getCount() { return count; }
public int getAPlusBCount() {
// We know B count, but we don't know A so how would we change this
// so B is A aware? Or not even aware, just somehow coupled? This
// is the question
// return a.getCount() + count;
}
public void doConditionalHere() {
// Do some condition in B that relies on the state of data in A
int acount = 0; // a.getCount(); ???
if(acount % 2 == 0) {
this.count--;
}
}
}
class Run {
A a = new A();
B b = new B();
List listeners = new List();
listeners.add(a);
listeners.add(b);
// The ugly way I add coupling right now is to keep a reference to A
// inside B. It's commented out because I am hoping there is a more intelligent approach
// b.setA(a);
for(char c : "ababbabab") {
for(listener : listeners) {
listener.onEvent(c);
}
}
}
```
|
Why not have a central object that will keep track of how many times the onEvent method was fired for all the listener classes
```
public interface CountObserver {
public void updateCount(String className);
public int getCount(String className);
}
public class CentralObserver implements CountObserver {
private int aCount;
private int bCount;
public void updateCount(String className) {
//There's probably a better way to do this than using
//all these if-elses, but you'll get the idea.
if (className.equals("AclassName")) {
aCount++;
}
else if (className.equals("BclassName")) {
bCount++;
}
}
public int getCount(String className) {
if (className.equals("AclassName")) {
return aCount;
}
else if (className.equals("BclassName")) {
return bCount;
}
}
class A implements Listener {
CountObserver countObserver;
public void registerObserver (CountObserver countObserver) {
this.countObserver = countObserver;
}
public void onEvent(char e) {
if(e == 'a') {
countObserver.updateCount (this.getClass.getName);
}
}
}
//Same thing for B or any other class implementing Listener. Your Listener interface should, of
//course, have a method signature for the registerObserver method which all the listener classes
//will implement.
class Run {
private A a;
private B b;
private CountObserver centralObserver;
public runProgram () {
centralObserver = new CentralObserver();
a.registerObserver(centralObserver);
b.registerObserver(centralObserver);
//run OnEvent method for A a couple of times, then for B
}
public int getAcount () {
return centralObserver.getCount(a.getClass.getName());
}
public int getBcount () {
return centralObserver.getCount(b.getClass.getName());
}
}
//To get the sum of all the counts just call getAcount + getBcount. Of course, you can always add more listeners and more getXCount methods
```
|
275,471 |
<p>I'm trying to use GDB to debug (to find an annoying segfault). When I run:</p>
<pre><code>gdb ./filename
</code></pre>
<p>from the command line, I get the following error:</p>
<pre><code>This GDB was configured as "i686-pc-linux-
gnu"..."/path/exec": not in executable
format: File format not recognized
</code></pre>
<p>When I execute:</p>
<pre><code>file /path/executable/
</code></pre>
<p>I get the following info:</p>
<pre><code> ELF 64-bit LSB executable, AMD x86-64,
version 1 (SYSV), for GNU/Linux 2.4.0,
dynamically linked (uses shared libs), not stripped
</code></pre>
<p>I am using GDB 6.1, and the executable is compiled with gcc version 3.4.6.</p>
<p>I'm a little out of my water in terms of using gdb, but as far as I can tell it should be working in this instance. Any ideas what's going wrong?</p>
|
[
{
"answer_id": 275472,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 5,
"selected": true,
"text": "<p>The executable is 64-bit (x86-64) and the debugger is a 32 bit (i686-pc-linux) build. You may need to install a 64-bit (x86-64) version of the debugger.</p>\n"
},
{
"answer_id": 275763,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>The question refers to \"./filename\" and to \"/path/executable\". Are these the same file?</p>\n\n<p>If you are doing a post-mortem analysis, you would run:</p>\n\n<pre><code>gdb executable-file core-file\n</code></pre>\n\n<p>If you are going to ignore the core file, you would run:</p>\n\n<pre><code>gdb executable-file\n</code></pre>\n\n<p>In both cases, '<code>executable-file</code>' means a pathname to the binary you want to debug. Most usually, that is actually a simple filename in the current directory, since you have the source code from your debug build there.</p>\n\n<p>On Solaris, a 64-bit build of GDB is supposed to be able to debug both 32-bit and 64-bit executables (though I've had some issues with recent versions of GDB). I'm not sure of the converse - that a 32-bit GDB can necessarily debug 64-bit executables.</p>\n"
},
{
"answer_id": 275839,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if this is your problem, but I faced this situation very often. The executable in the build tree, build by make/automake is not a binary, but a script, so you cannot use gdb with it. Try to install the application and change the directory, because else gdb tries to debug the script.</p>\n"
},
{
"answer_id": 1123312,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 2,
"selected": false,
"text": "<p>What you need to be checking, is really the bfd library. The <a href=\"http://www.linuxselfhelp.com/gnu/bfd/html_chapter/bfd_toc.html\" rel=\"nofollow noreferrer\">binary file descriptor</a> library is what binutils / gdb uses to actually parse and handle binaries (ELF/a.out etc..).</p>\n\n<p>You can see the current supported platforms via objdump;</p>\n\n<pre><code># objdump -H\n\nobjdump: supported targets: elf32-powerpc aixcoff-rs6000 elf32-powerpcle ppcboot elf64-powerpc elf64-powerpcle elf64-little elf64-big elf32-little elf32-big srec symbolsrec tekhex binary ihex\nobjdump: supported architectures: rs6000:6000 rs6000:rs1 rs6000:rsc rs6000:rs2 powerpc:common powerpc:common64 powerpc:603 powerpc:EC603e powerpc:604 powerpc:403 powerpc:601 powerpc:620 powerpc:630 powerpc:a35 powerpc:rs64ii powerpc:rs64iii powerpc:7400 powerpc:e500 powerpc:MPC8XX powerpc:750\n\nThe following PPC specific disassembler options are supported for use with\nthe -M switch:\n booke|booke32|booke64 Disassemble the BookE instructions\n e300 Disassemble the e300 instructions\n e500|e500x2 Disassemble the e500 instructions\n efs Disassemble the EFS instructions\n power4 Disassemble the Power4 instructions\n power5 Disassemble the Power5 instructions\n power6 Disassemble the Power6 instructions\n 32 Do not disassemble 64-bit instructions\n 64 Allow disassembly of 64-bit instructions\n</code></pre>\n"
},
{
"answer_id": 31819274,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 1,
"selected": false,
"text": "<p>It seems your GNU Debugger (<code>gdb</code>) doesn't support x86_64 architecture.</p>\n\n<p>So try <a href=\"https://en.wikipedia.org/wiki/LLDB_(debugger)\" rel=\"nofollow\">LLDB Debugger</a> (<code>lldb</code>) which aims to replace it. It supports i386, x86-64 and ARM instruction sets.</p>\n\n<p>It's available by default on BSD/OS X, on Linux install via: <code>sudo apt-get install lldb</code> (or use <code>yum</code>). </p>\n\n<p>See: <a href=\"http://lldb.llvm.org/lldb-gdb.html\" rel=\"nofollow\">gdb to lldb command map</a> page for more info.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266/"
] |
I'm trying to use GDB to debug (to find an annoying segfault). When I run:
```
gdb ./filename
```
from the command line, I get the following error:
```
This GDB was configured as "i686-pc-linux-
gnu"..."/path/exec": not in executable
format: File format not recognized
```
When I execute:
```
file /path/executable/
```
I get the following info:
```
ELF 64-bit LSB executable, AMD x86-64,
version 1 (SYSV), for GNU/Linux 2.4.0,
dynamically linked (uses shared libs), not stripped
```
I am using GDB 6.1, and the executable is compiled with gcc version 3.4.6.
I'm a little out of my water in terms of using gdb, but as far as I can tell it should be working in this instance. Any ideas what's going wrong?
|
The executable is 64-bit (x86-64) and the debugger is a 32 bit (i686-pc-linux) build. You may need to install a 64-bit (x86-64) version of the debugger.
|
275,484 |
<p>I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:</p>
<p>I want to output data onto the screen using <code>cout</code>. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:</p>
<pre><code>Test 1
Test2 2
Iamlongverylongblah 2
Etc 1
</code></pre>
<p>I am only concerned with the individual line so my line to output now (not working) is</p>
<p><code>cout << var1 << "\t\t" << var2 << endl;</code></p>
<p>Which gives me something like:</p>
<pre><code>Test 1
Test2 2
Iamlongverylongblah 2
Etc 1
</code></pre>
|
[
{
"answer_id": 275489,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": false,
"text": "<p>I advise using <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/format/index.html\" rel=\"noreferrer\">Boost Format</a>. Use something like this:</p>\n\n<pre><code>cout << format(\"%|1$30| %2%\") % var1 % var2;\n</code></pre>\n"
},
{
"answer_id": 275494,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://www.cplusplus.com/reference/iomanip/setw/\" rel=\"noreferrer\">setw</a>.</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nint main () {\n cout << setw(21) << left << \"Test\" << 1 << endl;\n cout << setw(21) << left << \"Test2\" << 2 << endl;\n cout << setw(21) << left << \"Iamlongverylongblah\" << 2 << endl;\n cout << setw(21) << left << \"Etc\" << 1 << endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 275496,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You must find the length of the longest string in the first column. Then you need to output each string in the first column in a field with the length being that of that longest string. This necessarily means you can't write anything until you've read each and every string.</p>\n"
},
{
"answer_id": 20597035,
"author": "avishayhajbi",
"author_id": 2580592,
"author_profile": "https://Stackoverflow.com/users/2580592",
"pm_score": -1,
"selected": false,
"text": "<p>you can do it with </p>\n\n<pre><code>string str = \"somthing\";\nprintf (\"%10s\",str);\nprintf (\"%10s\\n\",str);\nprintf (\"%10s\",str);\nprintf (\"%10s\\n\",str);\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33481/"
] |
I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:
I want to output data onto the screen using `cout`. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:
```
Test 1
Test2 2
Iamlongverylongblah 2
Etc 1
```
I am only concerned with the individual line so my line to output now (not working) is
`cout << var1 << "\t\t" << var2 << endl;`
Which gives me something like:
```
Test 1
Test2 2
Iamlongverylongblah 2
Etc 1
```
|
[setw](http://www.cplusplus.com/reference/iomanip/setw/).
```
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw(21) << left << "Test" << 1 << endl;
cout << setw(21) << left << "Test2" << 2 << endl;
cout << setw(21) << left << "Iamlongverylongblah" << 2 << endl;
cout << setw(21) << left << "Etc" << 1 << endl;
return 0;
}
```
|
275,493 |
<p>I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.</p>
<p>Is there a way to make it so these changes are available for undo/redo?</p>
|
[
{
"answer_id": 275621,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 3,
"selected": true,
"text": "<p>Here's just some code I decided to mess around with:</p>\n\n<pre><code> string buffer = String.Empty;\n string buffer2 = String.Empty;\n public Form3()\n {\n InitializeComponent();\n this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);\n this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);\n }\n\n void richTextBox1_TextChanged(object sender, EventArgs e)\n {\n buffer2 = buffer;\n buffer = richTextBox1.Text;\n }\n\n void richTextBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.Control && e.KeyCode == Keys.Z)\n {\n this.richTextBox1.Text = buffer2;\n }\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n richTextBox1.Text = \"Changed\";\n }\n</code></pre>\n\n<p>It's basically me writing my own Undo feature. All I'm doing is storing the old value in one buffer variable, and the new value in a second buffer variable. Every time the text changes, these values get update. Then, if the user hits \"CTRL-Z\" it replaces the text with the old value. Hack? A little. But, it works for the most part.</p>\n"
},
{
"answer_id": 59628129,
"author": "Morty",
"author_id": 1012586,
"author_profile": "https://Stackoverflow.com/users/1012586",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of replacing the text, you need to replace the selected text:</p>\n\n<pre><code>richTextBox.SelectAll();\nrichTextBox.SelectedText = NewText;\n</code></pre>\n\n<p>This was however tested with a current version of winforms, which has the same issue.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.
Is there a way to make it so these changes are available for undo/redo?
|
Here's just some code I decided to mess around with:
```
string buffer = String.Empty;
string buffer2 = String.Empty;
public Form3()
{
InitializeComponent();
this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);
this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);
}
void richTextBox1_TextChanged(object sender, EventArgs e)
{
buffer2 = buffer;
buffer = richTextBox1.Text;
}
void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Z)
{
this.richTextBox1.Text = buffer2;
}
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "Changed";
}
```
It's basically me writing my own Undo feature. All I'm doing is storing the old value in one buffer variable, and the new value in a second buffer variable. Every time the text changes, these values get update. Then, if the user hits "CTRL-Z" it replaces the text with the old value. Hack? A little. But, it works for the most part.
|
275,514 |
<p>Something is eluding me ... it seems obvious, but I can't quite figure it out.</p>
<p>I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ... </p>
<p>So if a user selects:</p>
<p>1 room, there is one text box</p>
<p>2 rooms, there are two text boxes</p>
<p>3 rooms, three text boxes </p>
<p>back to 2 rooms, two text boxes</p>
<p>and so on ...</p>
|
[
{
"answer_id": 275521,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>for your select list of rooms, add an onchange event handler that will show/hide the text boses.</p>\n\n<pre><code><script>\n //swap $ with applicable lib call (if avail)\n function $(id){\n return document.getElementById(id);\n }\n function adjustTexts(obj){\n var roomTotal = 4;\n var count = obj.selectedIndex;\n //show/hide unrequired text boxes...\n for(var i=0;i<roomTotal;i++){\n if(i < count){\n $('room'+ (i+1)).style.display = 'block';\n } else {\n $('room'+ (i+1)).style.display = 'none';\n }\n }\n }\n</script>\n\n\n<select name=\"rooms\" onchange=\"adjustTexts(this);\">\n <option>1</option>\n <option>2</option>\n <option>3</option>\n <option>4</option>\n</select>\n\n<div id=\"room1\">\n <label>Room 1</label>:<input type=\"text\" name=\"room1text\"/>\n</div>\n\n<div id=\"room2\" style=\"display:none;\">\n <label>Room 2</label>:<input type=\"text\" name=\"room2text\"/>\n</div>\n\n<div id=\"room3\" style=\"display:none;\">\n <label>Room 3</label>:<input type=\"text\" name=\"room3text\"/>\n</div>\n\n<div id=\"room4\" style=\"display:none;\">\n <label>Room 4</label>:<input type=\"text\" name=\"room4text\"/>\n</div>\n</code></pre>\n"
},
{
"answer_id": 275527,
"author": "ckramer",
"author_id": 20504,
"author_profile": "https://Stackoverflow.com/users/20504",
"pm_score": 3,
"selected": true,
"text": "<p>Using straight DOM and Javascript you would want to modify the InnterHtml property of a DOM object which will contain the text boxes...most likely a div. So it would look something like:</p>\n\n<pre><code>var container = document.getElementById(\"myContainerDiv\");\nvar html;\nfor(var i = 0; i < selectedRooms; i++)\n{\n html = html + \"<input type=text ... /><br />\";\n}\ncontainer.innerHtml = html;\n</code></pre>\n\n<p>Using a Javascript library like jQuery could make things slightly easier:</p>\n\n<pre><code>var html;\nfor(var i = 0; i < selectedRooms; i++)\n{\n html = html + \"<input type=text ... /><br />\";\n}\n\n$(\"#myContainerDiv\").append(html);\n</code></pre>\n"
},
{
"answer_id": 275528,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>given HTML:</p>\n\n<pre><code><select name=\"rooms\" id=\"rooms\">\n <option value=\"1\">1 room</option>\n <option value=\"2\">2 rooms</option>\n <option value=\"3\">3 rooms</option>\n</select>\n<div id=\"boxes\"></div>\n</code></pre>\n\n<p>javascript:</p>\n\n<pre><code>document.getElementById('rooms').onchange = function() {\n var e = document.getElementById('boxes');\n var count = parseInt(document.getElementById('rooms').value);\n e.innerHTML = '';\n\n for(i = 1; i <= count; i++) {\n e.innerHTML += 'Room '+i+' <input type=\"text\" name=\"room'+i+'\" /><br />';\n } \n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34770/"
] |
Something is eluding me ... it seems obvious, but I can't quite figure it out.
I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ...
So if a user selects:
1 room, there is one text box
2 rooms, there are two text boxes
3 rooms, three text boxes
back to 2 rooms, two text boxes
and so on ...
|
Using straight DOM and Javascript you would want to modify the InnterHtml property of a DOM object which will contain the text boxes...most likely a div. So it would look something like:
```
var container = document.getElementById("myContainerDiv");
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
container.innerHtml = html;
```
Using a Javascript library like jQuery could make things slightly easier:
```
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
$("#myContainerDiv").append(html);
```
|
275,536 |
<p>Where would the physical files be?</p>
|
[
{
"answer_id": 275538,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 6,
"selected": true,
"text": "<p>It depends on the OS and whether or not roaming user profiles are enabled.</p>\n\n<p>For example, on XP, with non-roaming profiles, the location is</p>\n\n<pre><code><SYSTEMDRIVE>\\Documents and Settings\\<user>\\Local Settings\\Application Data\\Microsoft\\IsolatedStorage \n</code></pre>\n\n<p>On Vista with roaming profile storage,</p>\n\n<pre><code><SYSTEMDRIVE>\\Users\\<user>\\AppData\\Roaming\\Microsoft\\IsolatedStorage\n</code></pre>\n\n<p>See an <a href=\"http://msdn.microsoft.com/en-us/library/3ak841sy.aspx\" rel=\"noreferrer\">Introduction to Isolated Storage</a> for more info.</p>\n"
},
{
"answer_id": 5008515,
"author": "Wonderbird",
"author_id": 598287,
"author_profile": "https://Stackoverflow.com/users/598287",
"pm_score": 2,
"selected": false,
"text": "<p>On my XP workstation I found it under c:\\Documents and Settings\\\\Local Settings\\Application Data\\Microsoft\\Silverlight\\is\\XXXXXXXXXXXXX\nWhere xxxxxxxx appears to be a random directory name. (under that if you wander around enough you should find the store for your particular app...)</p>\n"
},
{
"answer_id": 9560896,
"author": "Mark Sowul",
"author_id": 155892,
"author_profile": "https://Stackoverflow.com/users/155892",
"pm_score": 4,
"selected": false,
"text": "<p><code>%LocalAppData%\\IsolatedStorage</code> / <code>%AppData%\\IsolatedStorage.</code></p>\n\n<p>I didn't find them under \"Microsoft\"</p>\n"
},
{
"answer_id": 9923679,
"author": "arhsim",
"author_id": 580092,
"author_profile": "https://Stackoverflow.com/users/580092",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.Diagnostics.Process.Start(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + \n \"\\\\IsolatedStorage\"\n );\n</code></pre>\n"
},
{
"answer_id": 13053663,
"author": "Joshua",
"author_id": 549346,
"author_profile": "https://Stackoverflow.com/users/549346",
"pm_score": 2,
"selected": false,
"text": "<p>I've also seen it under <code>%ProgramData%\\IsolatedStorage</code> (so often C:\\ProgramData\\IsolatedStorage).</p>\n\n<p>This particular case was a Windows Server 2008 with IIS site-related data.</p>\n"
},
{
"answer_id": 22793833,
"author": "Mangesh",
"author_id": 3273962,
"author_profile": "https://Stackoverflow.com/users/3273962",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using Windows 8.1. On my PC its in <code>C:\\Users\\mangesh\\AppData\\LocalLow\\Microsoft\\Silverlight\\<followed by some random folder names></code></p>\n\n<p>In 'Silverlight' folder there are many random folders. You should find your files in one of these folders.</p>\n"
},
{
"answer_id": 50763705,
"author": "mybrave",
"author_id": 1755565,
"author_profile": "https://Stackoverflow.com/users/1755565",
"pm_score": 2,
"selected": false,
"text": "<p>Location differs per <code>IsolationStorage</code> scope</p>\n\n<pre><code>Local user [LocalApplicationData]\\IsolatedStorage\nRoaming user [ApplicationData]\\IsolatedStorage\nMachine [CommonApplicationData]\\IsolatedStorage\n</code></pre>\n\n<p>The folders can be retrieved by <code>Environment.GetFolderPath</code> method.</p>\n\n<p>Windows 2016 has it like this</p>\n\n<pre><code>Local user C:\\Users\\<user>\\AppData\\Local\\IsolatedStorage\nRoaming user C:\\Users\\<user>\\AppData\\Roaming\\IsolatedStorage\nMachine C:\\ProgramData\\IsolatedStorage\n</code></pre>\n\n<p>More details can be found <a href=\"http://www.albahari.com/nutshell/IsolatedStorage.pdf\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 69397820,
"author": "Rodolfo G.",
"author_id": 120764,
"author_profile": "https://Stackoverflow.com/users/120764",
"pm_score": 0,
"selected": false,
"text": "<p>When accessed/created by a system account, I found the folder here:</p>\n<pre><code>C:\\Windows\\SysWOW64\\config\\systemprofile\\AppData\\Local\\IsolatedStorage\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
Where would the physical files be?
|
It depends on the OS and whether or not roaming user profiles are enabled.
For example, on XP, with non-roaming profiles, the location is
```
<SYSTEMDRIVE>\Documents and Settings\<user>\Local Settings\Application Data\Microsoft\IsolatedStorage
```
On Vista with roaming profile storage,
```
<SYSTEMDRIVE>\Users\<user>\AppData\Roaming\Microsoft\IsolatedStorage
```
See an [Introduction to Isolated Storage](http://msdn.microsoft.com/en-us/library/3ak841sy.aspx) for more info.
|
275,540 |
<p>I would like to call an ejb3 at runtime. The name of the ejb and the method name will only be available at runtime, so I cannot include any remote interfaces at compile time.</p>
<pre><code>String bean = 'some/Bean';
String meth = 'doStuff';
//lookup the bean
Object remoteInterface = (Object) new InitialContext().lookup(bean);
//search the method ..
// foreach (methods)
// if method == meth, method.invoke(bean);
</code></pre>
<p>the beans should be distributed accross multiple application servers, and all beans are to be called remotely.</p>
<p>Any hints? specifically i do <strong>not</strong> want:</p>
<ol>
<li>dependency injection</li>
<li>inclusion of appliation specific ejb interfaces in the dispatcher (above)</li>
<li>webservices, thats like throwing out processing power for nothing, all the xml crap</li>
</ol>
<p>Is it possible to load an ejb3 remote interface over the network (if yes, how?), so I could cache the interface in some hashmap or something.</p>
<p>I have a solution with a remote dispatcher bean, which I can include in the above main dispatcher, which does essentially the same, but just relays the call to a local ejb (which I can lookup how? naming lookup fails). Given the remote dispatcher bean, I can use dependency injection.</p>
<p>thanks for any help</p>
<p>(netbeans and glassfish btw)</p>
|
[
{
"answer_id": 275662,
"author": "james",
"author_id": 17156,
"author_profile": "https://Stackoverflow.com/users/17156",
"pm_score": 1,
"selected": false,
"text": "<p>ejb3 calls use RMI. RMI supports remote class loading, so i'd suggest looking into that.</p>\n\n<p>also, JMX mbeans support fully untyped, remote invocations. so, if you could use mbeans instead of session beans, that could work. (JBoss, for instance, supports ejb3-like mbeans with some custom annotations).</p>\n\n<p>lastly, many app servers support CORBA invocations, and CORBA supports untyped method invocations.</p>\n"
},
{
"answer_id": 281332,
"author": "Dave",
"author_id": 3095,
"author_profile": "https://Stackoverflow.com/users/3095",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to use java.rmi.server.RMIClassLoader for the remote class loading. You'll also need to load any classes that the remote service returns or throws.</p>\n"
},
{
"answer_id": 450213,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 0,
"selected": false,
"text": "<p>It cannot be done. You will always get a \"class not found\" exception. That is in my opinion the biggest disadvantage of EJB/Java. You loose some of the dynamcis, because the meta-language features are limited.</p>\n\n<p>EJB3 supports RMI/IIOP, but not RMI/JRMP (standard RMI) so dynamic class loading is not supported.You loose some Java generality, but gain other features like being able to communicate about transactions and security.</p>\n"
},
{
"answer_id": 461625,
"author": "Pavel",
"author_id": 48340,
"author_profile": "https://Stackoverflow.com/users/48340",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use reflection for this, and it is very simple to do. Assuming that you're looking for a void method called <em>meth</em>:</p>\n\n<pre><code>Object ejb = ctx.lookup(bean);\nfor (Method m : ejb.getClass().getMethods()) {\n if (m.getName().equals(meth) && m.getParameterTypes().length == 0) {\n m.invoke(service);\n }\n}\n</code></pre>\n\n<p>If you're looking for a specific method signature just modify the m.getParameterTypes() test accordingly, e.g. for a method with a single String parameter you can try:</p>\n\n<pre><code>Arrays.equals(m.getParameterTypes(), new Class[]{String.class})\n</code></pre>\n\n<p>And then pass an Object[] array with the actual arguments to the m.invoke() call:</p>\n\n<pre><code>m.invoke(service, new Object[]{\"arg0\"})\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I would like to call an ejb3 at runtime. The name of the ejb and the method name will only be available at runtime, so I cannot include any remote interfaces at compile time.
```
String bean = 'some/Bean';
String meth = 'doStuff';
//lookup the bean
Object remoteInterface = (Object) new InitialContext().lookup(bean);
//search the method ..
// foreach (methods)
// if method == meth, method.invoke(bean);
```
the beans should be distributed accross multiple application servers, and all beans are to be called remotely.
Any hints? specifically i do **not** want:
1. dependency injection
2. inclusion of appliation specific ejb interfaces in the dispatcher (above)
3. webservices, thats like throwing out processing power for nothing, all the xml crap
Is it possible to load an ejb3 remote interface over the network (if yes, how?), so I could cache the interface in some hashmap or something.
I have a solution with a remote dispatcher bean, which I can include in the above main dispatcher, which does essentially the same, but just relays the call to a local ejb (which I can lookup how? naming lookup fails). Given the remote dispatcher bean, I can use dependency injection.
thanks for any help
(netbeans and glassfish btw)
|
ejb3 calls use RMI. RMI supports remote class loading, so i'd suggest looking into that.
also, JMX mbeans support fully untyped, remote invocations. so, if you could use mbeans instead of session beans, that could work. (JBoss, for instance, supports ejb3-like mbeans with some custom annotations).
lastly, many app servers support CORBA invocations, and CORBA supports untyped method invocations.
|
275,541 |
<p>In a latin-1 database i have '<code>\222\222\223\225</code>', when I try to pull this field from the django models I get back <code>u'\u2019\u2019\u201c\u2022'</code>.</p>
<pre><code>from django.db import connection
(Pdb)
cursor = connection.cursor()
(Pdb)
cursor.execute("SELECT Password from campaignusers WHERE UserID=26")
(Pdb)
row = cursor.fetchone()
</code></pre>
<p>So I step into that and get into </p>
<blockquote>
<p>/usr/local/python2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',) </p>
</blockquote>
<p>I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1.</p>
<p>Anyone have any clue whats going on?</p>
|
[
{
"answer_id": 276108,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 2,
"selected": false,
"text": "<p>A little browsing of already-asked questions would have led you to <a href=\"https://stackoverflow.com/questions/274361/utf-8-latin-1-conversion-issues-python-django\">UTF-8 latin-1 conversion issues</a>, which was asked and answered yesterday.</p>\n\n<p>BTW, I couldn't remember the exact title, so I just googled on django+'\\222\\222\\223\\225' and found it. Remember, kids, Google Is Your Friend (tm).</p>\n"
},
{
"answer_id": 303448,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 0,
"selected": false,
"text": "<p>Django uses UTF-8, unless you define DEFAULT_CHARSET being something other. Be aware that defining other charset will require you to encode all your templates in this charset and this charset will pop from here to there, like email encoding, in sitemaps and feeds and so on. So, IMO, the best you can do is to go UTF-8, this will save you much headaches with Django (internally it's all unicode, the problems are on the borders of your app, like templates and input).</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35697/"
] |
In a latin-1 database i have '`\222\222\223\225`', when I try to pull this field from the django models I get back `u'\u2019\u2019\u201c\u2022'`.
```
from django.db import connection
(Pdb)
cursor = connection.cursor()
(Pdb)
cursor.execute("SELECT Password from campaignusers WHERE UserID=26")
(Pdb)
row = cursor.fetchone()
```
So I step into that and get into
>
> /usr/local/python2.5/lib/python2.5/site-packages/MySQL\_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',)
>
>
>
I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1.
Anyone have any clue whats going on?
|
A little browsing of already-asked questions would have led you to [UTF-8 latin-1 conversion issues](https://stackoverflow.com/questions/274361/utf-8-latin-1-conversion-issues-python-django), which was asked and answered yesterday.
BTW, I couldn't remember the exact title, so I just googled on django+'\222\222\223\225' and found it. Remember, kids, Google Is Your Friend (tm).
|
275,544 |
<p>I know in a lot of asynchronous communication, the packet begins starts with a start bit.</p>
<p>But a start bit is just a 1 or 0. How do you differentiate a start bit from the end bit from the last packet?</p>
<p>Ex.
If I choose my start bit to be 0 and my end bit to be 1.
and I receive 0 (data stream A) 1 0 (data stream B) 1,
what's there to stop me from assuming there is a data stream C which contains the same contents of "(data stream A) 1 0 (data stream B)" ?</p>
<p>Isn't it more convenient to have a start BYTE and then check the data stream for that combination of bits? That will reduce the possibility of a confusing between the start/end bit.</p>
|
[
{
"answer_id": 275554,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": false,
"text": "<p>Great question! Most asynchronous communication also specifies a <em>stop</em> bit, which is the complement of the start bit, ensuring each new symbol begins with a stop-to-start transition.</p>\n\n<p>Example: let's transmit the characters <code>ABC</code>, which are ASCII 65, 66, and 67:</p>\n\n<pre><code>A = 65 = 0x41 = 0100 0001\nB = 66 = 0x42 = 0100 0010\nC = 67 = 0x43 = 0100 0011\n</code></pre>\n\n<p>Let's also assume (arbitrarily) that the start bit is <code>0</code> and the stop bit is <code>1</code>, and the data is transmitted from MSB to LSB. The transmitter will be in the stop (<code>1</code>) state when no data is transmitted. So the receiver might see this:</p>\n\n<pre><code>Data: ....1111 0010000011 111 0010000101 0010000111 11111....\n (quiet) ^ A $ ^ B $ ^ C $ (quiet)\n</code></pre>\n\n<p>With apologies for the ASCII graphics, the data consists of a series of stop (<code>1</code>) bits while the channel is idle. When the transmitter is ready to send a character, it sends a start (<code>0</code>) bit (marked with <code>^</code>), followed by the character code, and ending with a stop (<code>1</code>) bit (marked with <code>$</code>). It continues to send stop bits until the next character is transmitted, beginning with another start bit.</p>\n\n<p>The reason we use start <em>bits</em> instead of <em>bytes</em> is efficiency. The scheme above requires 10 bits (1<sub>start</sub> + 8<sub>data</sub> + 1<sub>stop</sub>) to transmit 8 bits of data, resulting in an <em>overhead</em> of (10 - 8) / 8 = 1/4 = 25%. If we used start and stop <em>bytes</em>, we'd need to transmit 3 bytes for each byte of data, which would be an overhead of (3 - 1)/1 = 2 = 200%. If the start, data, and stop bytes were each 8 bits, we'd have to transmit 24 bits instead of 10 for each character, so it would take almost 2 1/2 times as long to send the data!</p>\n"
},
{
"answer_id": 275557,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the way start and stop bits usually work:</p>\n\n<ol>\n<li>A start bit is sent, say 1. This indicates to the receiver that a specified number of bits of data will be transmitted, say 8.</li>\n<li>8 bits of data are sent.</li>\n<li>A stop bit is sent, say 0. This indicates that the 8 bits of data have been sent.</li>\n</ol>\n\n<p>If more data is to be sent, each byte must be initiated with a start bit and terminated with a stop bit. The transmitter and receiver must agree on how many bits of data are sent for each start bit so the receiver will be able to distinguish the stop bit from the data. Sometimes the start bit is actually multiple bits or even a byte, but the idea is the same. The receiver recognizes the end of the data frame when it sees the stop bit after receiving the pre-specified number of data bits. Sometimes a parity bit is sent before the stop bit to provide a simple error-detecting mechanism.</p>\n"
},
{
"answer_id": 275560,
"author": "Szere Dyeri",
"author_id": 33885,
"author_profile": "https://Stackoverflow.com/users/33885",
"pm_score": 0,
"selected": false,
"text": "<p>It is all protocol dependent. You can say that after start symbol you will expect N symbols or you will read until you encounter the stop symbol.</p>\n\n<p>Where symbol colud be any n-bit sequence (including bit and byte.) </p>\n\n<p>Indeed, your example with bits exactly apply to a protocol which uses bytes instead of bits. </p>\n\n<p>Say you send 00000000 stream A 11111111 00000000 stream B 11111111. In this case you may still confuse it with stream C = stream A 11111111 00000000 stream B.</p>\n\n<p>Usually a start bit is used because a voltage level change can trigger an event (See edge triggering in <a href=\"http://en.wikipedia.org/wiki/Flip-flop_(electronics)\" rel=\"nofollow noreferrer\">flip flops</a>.) On the other hand a start symbol with multiple bits will be used to synchronize clocks of two systems in addition to triggering an event. An example of it would be a PAL signal.</p>\n"
},
{
"answer_id": 275561,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": -1,
"selected": false,
"text": "<p>The start and stop bits come from the days of the <a href=\"http://en.wikipedia.org/wiki/ASR33\" rel=\"nofollow noreferrer\">teletypes</a>. They essentially were pulses that took up time to sort of let the mechanical hardware set. Dos text file lines are ended with CR LF which literally caused the carriage to return to column 1, and the platen to advance one line. I think it is in the order because it takes longer for the CR to occur, and the LF can effectively happen in parallel.</p>\n<p>Detecting it is a little bit harder. You sort of have to watch the bit stream go by.\nOver time you ought to be able to detect it, as the data is normally ASCII with the start/stop bits around it. Normally this isn't an issue, because it is handled by the <a href=\"http://en.wikipedia.org/wiki/UART\" rel=\"nofollow noreferrer\">UART</a> which runs the <a href=\"https://www.rfc-editor.org/rfc/rfc2217\" rel=\"nofollow noreferrer\">COM</a> port.</p>\n"
},
{
"answer_id": 276652,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 1,
"selected": false,
"text": "<p>One can always define a start byte as an indication that a message is beginning (and the ASCII SOH, STX, and ETX codes were intended for such purposes). However, the standard hardware and protocols for connection to data-transmission equipment (RS232C and later) operate at a lower level, and it is generally neither possible nor desirable to alter that arrangement (especially via software).</p>\n\n<p>High performance synchronous data transmission schemes, such as those used on local-area networks and wide-area transmission systems do use elaborate frame markers. The frame marker is a distinct pattern of bits that never occurs in the stream for message data. There is typically a special rewriting rule that essentially \"escapes\" any in-data occurrence of a similar bit pattern so that transmission equipment will not see it as a frame marker. These escaped patterns are reconstructed by the recipient so the sender and receiver never have to pay attention to this. These arrangements make specialized hardware even more important, such as in the typical Network Interface Card (these days, motherboard chip) on personal computers.</p>\n\n<p>BACKGROUND ON ASYNCHRONOUS SERIAL COMMUNICATION</p>\n\n<p>It is useful to think of asynchronous serial transmissions as asynchronous between character/data frames and synchronous within the span of the character frame (including the start bits and initial stop/fill). </p>\n\n<p>With this scheme, there is a constant fill signal between the frames and it is usually at least one data-bit wide, although some arrangements require a 1.5-bit or two-bit stop/fill. The stop \"bit\" uses the same signal level and can be considered the minimum fill period before another start bit will arrive.</p>\n\n<p>When a frame is arriving, it is necessary to synchronize with the predetermined number of bits it is expected to carry. The transition from the fill to an opposite level signal is accomplished by the start bit which is always opposite to the stop/fill level. The sampling of the bits can be timed to happen in the middle of subsequent bit-arrival periods.</p>\n\n<p>Technically, if frames were being sent at the maximum rate, it would not be necessary to send any stop/fill, proceeding to the start bit of the next frame immediately. However, counting on at least one bit worth of fill before the start-bit transition helps to keep the sender and receiver synchronized. </p>\n\n<p>If you think of the asynchronous streams as being encoded from key depressions using a keyboard, you can see the importance of allowing arbitrary fill between character frames. Once it is known what frame to send next, it can be inserted immediately, with its start bit, at the agreed bit rate, after there has been at least one bit worth of preceding stop/fill.</p>\n\n<p>It is also useful to notice that, in typical low-speed asynchronous transmissions, there are only two kinds of bits/levels, so the only way the presence of data as opposed to fill can be distinguished is by a marker scheme like this where the start of the frame is uniquelly detectable and the end of frame is predetermined (unless there is a more-sophisticated variable-length frame structure generally not used in asynchronous serial communication). It is actually rather difficult for a receiver to discover the bit rate of a transmitter without some additional agreement, such as looking for a recognizable data sequence from which one can estimate the bit rate which would have it arrive correctly when it arrives in incorrect form. </p>\n\n<p>Even though high-speed modems now transmit complex analog signals that aren't described in terms of two simple signal levels, the RS232C (and later-mode) digital communication between a computer UART and the data coupling on the modem is pretty much as described.</p>\n\n<p>High-speed modems also have additional capabilities for synchronizing with a distant end-point, as you can tell by listening to the signal audio while a connection starts up. In addition, There are separate signal lines in the serial cable to the computer that are used for pacing between the computer and the modem so that the sending party does not transmit new data frames faster than the receiving party (either computer or modem) can accept them. But a frame, once started, is always started at the agreed synchronous speed. </p>\n\n<p>Wikipedia has a good description of <a href=\"http://en.wikipedia.org/wiki/Asynchronous_serial_communication\" rel=\"nofollow noreferrer\">asynchronous serial communication</a>, what computer serial ports use. </p>\n\n<p>There is a common over-simplification that suggests the stop bit determines the length of the data. That's not the case. The stop bit looks just like a level for another data bit. The way the stop bit and the period until the next start bit, are recognized is by knowing the bit rate at which in-frame data and start/stop bits are being transmitted and knowing how many bits a frame contains. Otherwise, there is no way to distinguish a stop bit from just another bit of that polarity as part of the data frame.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
I know in a lot of asynchronous communication, the packet begins starts with a start bit.
But a start bit is just a 1 or 0. How do you differentiate a start bit from the end bit from the last packet?
Ex.
If I choose my start bit to be 0 and my end bit to be 1.
and I receive 0 (data stream A) 1 0 (data stream B) 1,
what's there to stop me from assuming there is a data stream C which contains the same contents of "(data stream A) 1 0 (data stream B)" ?
Isn't it more convenient to have a start BYTE and then check the data stream for that combination of bits? That will reduce the possibility of a confusing between the start/end bit.
|
Great question! Most asynchronous communication also specifies a *stop* bit, which is the complement of the start bit, ensuring each new symbol begins with a stop-to-start transition.
Example: let's transmit the characters `ABC`, which are ASCII 65, 66, and 67:
```
A = 65 = 0x41 = 0100 0001
B = 66 = 0x42 = 0100 0010
C = 67 = 0x43 = 0100 0011
```
Let's also assume (arbitrarily) that the start bit is `0` and the stop bit is `1`, and the data is transmitted from MSB to LSB. The transmitter will be in the stop (`1`) state when no data is transmitted. So the receiver might see this:
```
Data: ....1111 0010000011 111 0010000101 0010000111 11111....
(quiet) ^ A $ ^ B $ ^ C $ (quiet)
```
With apologies for the ASCII graphics, the data consists of a series of stop (`1`) bits while the channel is idle. When the transmitter is ready to send a character, it sends a start (`0`) bit (marked with `^`), followed by the character code, and ending with a stop (`1`) bit (marked with `$`). It continues to send stop bits until the next character is transmitted, beginning with another start bit.
The reason we use start *bits* instead of *bytes* is efficiency. The scheme above requires 10 bits (1start + 8data + 1stop) to transmit 8 bits of data, resulting in an *overhead* of (10 - 8) / 8 = 1/4 = 25%. If we used start and stop *bytes*, we'd need to transmit 3 bytes for each byte of data, which would be an overhead of (3 - 1)/1 = 2 = 200%. If the start, data, and stop bytes were each 8 bits, we'd have to transmit 24 bits instead of 10 for each character, so it would take almost 2 1/2 times as long to send the data!
|
275,550 |
<p>I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up.
I decided to go with the set_include_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.</p>
<p>Is there a guide somewhere that details path referencing for PHP?</p>
|
[
{
"answer_id": 275556,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>it's probably easier to just use an absolute path to reference:</p>\n\n<pre><code>set_include_path('/path/to/files');\n</code></pre>\n\n<p>this way you have a reference point for all your future includes. includes are handled relative to the point they were called, which can cause a bit of confusion in certain scenarios.</p>\n\n<p>as an example, given a sample folder structure (<code>/home/files</code>):</p>\n\n<pre><code>index.php\ntest/\n test.php\ntest2/\n test2.php\n\n// /home/files/index.php\ninclude('test/test.php');\n\n// /home/files/test/test.php\ninclude('../test2/test2.php');\n</code></pre>\n\n<p>if you call index.php, it will try to include the following files:</p>\n\n<pre><code>/home/files/test/test.php // expected\n/home/test2/test2.php // maybe not expected\n</code></pre>\n\n<p>which may not be what you expect. calling test.php will call <code>/home/files/test2/test.php</code> as expected.</p>\n\n<p>the conclusion being, the includes will be relative to the original calling point. to clarify, this affects <code>set_include_path()</code> if it is relative as well. consider the following (using the same directory structure):</p>\n\n<pre><code><?php\n// location: /home/files/index.php\n set_include_path('../'); // our include path is now /home/\n\n include('files/test/test.php'); // try to include /home/files/test/test.php\n include('test2/test2.php'); // try to include /home/test2/test2.php\n include('../test3.php'); // try to include /test3.php\n?>\n</code></pre>\n"
},
{
"answer_id": 275647,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to use <strong><a href=\"http://uk3.php.net/dirname\" rel=\"nofollow noreferrer\">dirname</a></strong> to get the current path and then use this as a base to calculate all future path names.</p>\n\n<p>For example,</p>\n\n<pre><code>$base = dirname( __FILE__ ); # Path to directory containing this file\ninclude( \"{$base}/includes/Common.php\" ); # Kick off some magic\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24416/"
] |
I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up.
I decided to go with the set\_include\_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.
Is there a guide somewhere that details path referencing for PHP?
|
I tend to use **[dirname](http://uk3.php.net/dirname)** to get the current path and then use this as a base to calculate all future path names.
For example,
```
$base = dirname( __FILE__ ); # Path to directory containing this file
include( "{$base}/includes/Common.php" ); # Kick off some magic
```
|
275,562 |
<p>I'm writing a simple time tracking program to manage my own projects. I'm a big fan of keeping reporting code in the database, so I've been attempting to create a few sprocs that generate the invoices and timesheets etc.</p>
<p>I have a table that contains Clock Actions, IE "Punch In", and "Punch Out". It also contains the user that did this action, the project associated with the action, and the current date/time.</p>
<p>I can select from this table to get clock in's for a specific time/project/and user, but I want to aggregate it down so that each clock in and out is converted from 2 rows to a single row containing total time.</p>
<p>For example, here is a sample output:</p>
<pre><code>ClockActionID ActionType DateTime
-------------------- ---------- -----------------------
17 1 2008-11-08 18:33:56.000
18 2 2008-11-08 18:33:59.587
19 1 2008-11-08 18:34:01.023
20 2 2008-11-08 18:34:02.037
21 1 2008-11-08 18:45:06.317
22 2 2008-11-08 18:46:14.597
23 1 2008-11-08 18:46:16.283
24 2 2008-11-08 18:46:17.173
25 1 2008-11-08 18:50:37.830
26 2 2008-11-08 18:50:39.737
27 1 2008-11-08 18:50:40.547
(11 row(s) affected)
</code></pre>
<p>Where ActionType 1 is "ClockIn" and ActionType 2 is "ClockOut". I also pruned out the User, Project, and Description columns for brevity.</p>
<p>I need to generate, in pure SQL, a result set like:</p>
<pre><code>Description | Total Time
</code></pre>
<p>For each ClockIn / ClockOut Pair.</p>
<p>I figure this will actually be fairly simple, I'm just not quite sure which way to approach it.</p>
<p>EDIT: The user will be able to clock into multiple projects simultaneously, though by first narrowing down the result set to a single project, this shouldn't make any difference to the logic here.</p>
|
[
{
"answer_id": 275570,
"author": "DevCodex",
"author_id": 35872,
"author_profile": "https://Stackoverflow.com/users/35872",
"pm_score": 1,
"selected": false,
"text": "<p>I think your original storage schema is flawed. You're looking at it from the perspective of the clock, hence ClockAction. Why not from the Project's perspective?</p>\n\n<p>TABLE ProjectAction (Projectid, Userid, Type, Start, End)</p>\n\n<p>Then a simple GROUP BY should do the trick.</p>\n"
},
{
"answer_id": 275615,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": true,
"text": "<p>I agree that the design isn't the greatest--an event based structure with a single row for start-end will probably save you a lot of time. In that case, you could create a record with a null end-date when someone clocks in. Then, fill in the end date when they clock out.</p>\n\n<p>But, that's not what you asked. This is the solution to your problem:</p>\n\n<pre><code>DECLARE @clock TABLE (ClockActionID INT PRIMARY KEY IDENTITY, ActionType INT, ActionDateTime DATETIME)\n\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:00:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:01:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:02:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:03:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:04:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:05:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:06:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:07:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:08:12')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:09:00')\n\n-- Get the range\nSELECT ActionDateTime CheckIn, \n (SELECT TOP 1 ActionDateTime \n FROM @clock C2 \n WHERE C2.ActionDateTime > C.ActionDateTime) CheckOut \nFROM @clock C\nWHERE ActionType = 1\n\n-- Get the duration\nSELECT DATEDIFF(second, ActionDateTime, \n (SELECT TOP 1 ActionDateTime \n FROM @clock C2 \n WHERE C2.ActionDateTime > C.ActionDateTime)\n ) / 60.0 Duration_Minutes\nFROM @clock C\nWHERE ActionType = 1\n</code></pre>\n\n<p>Note that I'm using a table variable which works with MS SQL Server just for testing. Change as needed. Also note that SQL Server 2000 <strong>does not perform well</strong> with queries like this. Here are the test results:</p>\n\n<pre><code>CheckIn CheckOut\n2008-01-01 00:00:00.000 2008-01-01 00:01:00.000\n2008-01-01 00:02:00.000 2008-01-01 00:03:00.000\n2008-01-01 00:04:00.000 2008-01-01 00:05:00.000\n2008-01-01 00:06:00.000 2008-01-01 00:07:00.000\n2008-01-01 00:08:12.000 2008-01-01 00:09:00.000\n\nDuration_Minutes\n1.000000\n1.000000\n1.000000\n1.000000\n0.800000\n</code></pre>\n"
},
{
"answer_id": 275829,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Have you thought about things like:</p>\n\n<ul>\n<li>someone forgets to clock out, and thus it appears they clocked in twice?</li>\n<li>someone forgets to clock in, and thus it appears they clocked out twice?</li>\n</ul>\n\n<p>In the first case, is it correct to simply ignore the second clock-in? The accepted answer will bind both clock-ins to the same clock-out. Is that correct?</p>\n\n<p>In the second case, the second clock-out will be ignored. Is that correct?</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
I'm writing a simple time tracking program to manage my own projects. I'm a big fan of keeping reporting code in the database, so I've been attempting to create a few sprocs that generate the invoices and timesheets etc.
I have a table that contains Clock Actions, IE "Punch In", and "Punch Out". It also contains the user that did this action, the project associated with the action, and the current date/time.
I can select from this table to get clock in's for a specific time/project/and user, but I want to aggregate it down so that each clock in and out is converted from 2 rows to a single row containing total time.
For example, here is a sample output:
```
ClockActionID ActionType DateTime
-------------------- ---------- -----------------------
17 1 2008-11-08 18:33:56.000
18 2 2008-11-08 18:33:59.587
19 1 2008-11-08 18:34:01.023
20 2 2008-11-08 18:34:02.037
21 1 2008-11-08 18:45:06.317
22 2 2008-11-08 18:46:14.597
23 1 2008-11-08 18:46:16.283
24 2 2008-11-08 18:46:17.173
25 1 2008-11-08 18:50:37.830
26 2 2008-11-08 18:50:39.737
27 1 2008-11-08 18:50:40.547
(11 row(s) affected)
```
Where ActionType 1 is "ClockIn" and ActionType 2 is "ClockOut". I also pruned out the User, Project, and Description columns for brevity.
I need to generate, in pure SQL, a result set like:
```
Description | Total Time
```
For each ClockIn / ClockOut Pair.
I figure this will actually be fairly simple, I'm just not quite sure which way to approach it.
EDIT: The user will be able to clock into multiple projects simultaneously, though by first narrowing down the result set to a single project, this shouldn't make any difference to the logic here.
|
I agree that the design isn't the greatest--an event based structure with a single row for start-end will probably save you a lot of time. In that case, you could create a record with a null end-date when someone clocks in. Then, fill in the end date when they clock out.
But, that's not what you asked. This is the solution to your problem:
```
DECLARE @clock TABLE (ClockActionID INT PRIMARY KEY IDENTITY, ActionType INT, ActionDateTime DATETIME)
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:00:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:01:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:02:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:03:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:04:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:05:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:06:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:07:00')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:08:12')
INSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:09:00')
-- Get the range
SELECT ActionDateTime CheckIn,
(SELECT TOP 1 ActionDateTime
FROM @clock C2
WHERE C2.ActionDateTime > C.ActionDateTime) CheckOut
FROM @clock C
WHERE ActionType = 1
-- Get the duration
SELECT DATEDIFF(second, ActionDateTime,
(SELECT TOP 1 ActionDateTime
FROM @clock C2
WHERE C2.ActionDateTime > C.ActionDateTime)
) / 60.0 Duration_Minutes
FROM @clock C
WHERE ActionType = 1
```
Note that I'm using a table variable which works with MS SQL Server just for testing. Change as needed. Also note that SQL Server 2000 **does not perform well** with queries like this. Here are the test results:
```
CheckIn CheckOut
2008-01-01 00:00:00.000 2008-01-01 00:01:00.000
2008-01-01 00:02:00.000 2008-01-01 00:03:00.000
2008-01-01 00:04:00.000 2008-01-01 00:05:00.000
2008-01-01 00:06:00.000 2008-01-01 00:07:00.000
2008-01-01 00:08:12.000 2008-01-01 00:09:00.000
Duration_Minutes
1.000000
1.000000
1.000000
1.000000
0.800000
```
|
275,566 |
<p>We are currently working on an application that will use a WCF service. The host (the client) is using the excellent <a href="http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx" rel="nofollow noreferrer">WCF Service Proxy Helper from Erwyn van der Meer</a>.</p>
<p>What I would like to know... is if I open this object multiple times... will it lead to multiple (expensive) connections or will WCF manage it and pool the connections.</p>
<p>The reason why I want to know this is because we will be calling methods of the service at different point in time within the same web request and we currently have wrapped the instanciation of the Service proxy class within the call.</p>
<p>Eg.:</p>
<pre><code>MyService.MyMethod1() // wraps the connection usage as well as the call to the service
</code></pre>
<p>Any suggestions about how I would go to minimize the amount of connection while keeping the code conform with <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow noreferrer">SRP</a> would be excellent.</p>
<p>So? Any idea?</p>
|
[
{
"answer_id": 275624,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 3,
"selected": true,
"text": "<p>You should try to minimize the number of proxy objects you create. Proxies in WCF are quite expensive to set up, so creating one and calling functions on it multiple times is definitely more efficient than creating a new one for each method invocation.</p>\n\n<p>The relationship between proxy objects and connections depends on the transport used. For http transports, an HTTP connection is initiated for each function invocation. For the net.tcp transport, the connection is established at Open() time and kept until a Close(). Certain binding settings (eg those supporting WS-SecureConversation) will incur extra \"housekeeping\" connections and message exchanges.</p>\n\n<p>AKAIK, none of the out-of-the-box bindings perform connection pooling.</p>\n"
},
{
"answer_id": 275762,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't do pooling like SqlConnection, if that is what you mean.</p>\n\n<p>[caveat: I use \"connection\" here loosely to mean a logical connection, not necessarily a physical connection]</p>\n\n<p>Between using a connection on-demand, and keeping one around, there are advantages and disadvantages to both approaches. There is some overhead in initializing a connection, so if you are doing 5 things you should try to do them on the same proxy - but I wouldn't keep a long term proxy around just for the sake of it.</p>\n\n<p>In particular, in terms of life-cycle management, once a proxy has faulted, it stays faulted - so you need to be able to recover from the occasional failure (which should be expected). Equally, in some configurations (some combinations of session/instancing), a connection has a definite footprint on the server - so to improve scalability you should keep connections short-lived. Of course, for <em>true</em> scalability you'd usually want to disable those options anyway!</p>\n\n<p>The cost of creating a connection also depends on things like the security mode. IIRC, it will be more expensive to open a two-way validated connection using message security than it will to set up a TransportWithMessageCredential connection - so \"YMMV\" is very much the case here.</p>\n\n<p>Personally, I find that the biggest common issue with proxy performance isn't anything to do with the time to set up a conncetion - it is the chattiness of the API. i.e.</p>\n\n<p>Scenario A:</p>\n\n<ul>\n<li>open a connection</li>\n<li>perform 1 operation with a large payload (i.e. a message that means \"do these 19 things\")</li>\n<li>close the proxy</li>\n</ul>\n\n<p>Scenario B:</p>\n\n<ul>\n<li>open a connecton</li>\n<li>perform 19 operations with small payloads</li>\n<li>close the connection</li>\n</ul>\n\n<p>Then scenario A will usually be <em>significantly</em> faster due to latency etc. And IMO don't even think about distributed transactions over WCF ;-p</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24975/"
] |
We are currently working on an application that will use a WCF service. The host (the client) is using the excellent [WCF Service Proxy Helper from Erwyn van der Meer](http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx).
What I would like to know... is if I open this object multiple times... will it lead to multiple (expensive) connections or will WCF manage it and pool the connections.
The reason why I want to know this is because we will be calling methods of the service at different point in time within the same web request and we currently have wrapped the instanciation of the Service proxy class within the call.
Eg.:
```
MyService.MyMethod1() // wraps the connection usage as well as the call to the service
```
Any suggestions about how I would go to minimize the amount of connection while keeping the code conform with [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle) would be excellent.
So? Any idea?
|
You should try to minimize the number of proxy objects you create. Proxies in WCF are quite expensive to set up, so creating one and calling functions on it multiple times is definitely more efficient than creating a new one for each method invocation.
The relationship between proxy objects and connections depends on the transport used. For http transports, an HTTP connection is initiated for each function invocation. For the net.tcp transport, the connection is established at Open() time and kept until a Close(). Certain binding settings (eg those supporting WS-SecureConversation) will incur extra "housekeeping" connections and message exchanges.
AKAIK, none of the out-of-the-box bindings perform connection pooling.
|
275,569 |
<p>This is kind of a brainteaser question, since the code works perfectly fine as-is, it just irritates my aesthetic sense ever so slightly. I'm turning to Stack Overflow because my own brain is failing me right now.</p>
<p>Here's a snippet of code that looks up an address using the Google Maps JS API and places a marker on a map. However, sometimes the initial lookup fails, so I want to repeat the process with a different address.</p>
<pre><code>geocoder.getLatLng(item.mapstring, function(point) {
if (!point) {
geocoder.getLatLng(item.backup_mapstring, function(point) {
if (!point) return;
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
return;
}
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
</code></pre>
<p>(The second parameter to <code>getLatLng</code> is a callback function.)</p>
<p>Of course you can see that the three lines that center and zoom the map and add the marker are duplicated, once in the primary callback and once in the "fallback callback" (ha ha). Can you find a way to express the whole thing without any redundancy? You earn bonus points, and my adulation, if your solution works for an arbitrary number of backup map strings.</p>
|
[
{
"answer_id": 275582,
"author": "Jay Kominek",
"author_id": 32878,
"author_profile": "https://Stackoverflow.com/users/32878",
"pm_score": 1,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>function place_point(mapstrings,idx)\n{\n if(idx>=mapstrings.length) return;\n geocoder.getLatLng(mapstrings[idx],\n function(point)\n {\n if(!point)\n {\n place_point(mapstrings,idx+1);\n return;\n }\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n });\n}\n</code></pre>\n\n<p>As many backup strings as you want. Just call it with a 0 as the second argument the first time.</p>\n"
},
{
"answer_id": 275590,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<p>Yep, factor it out into a function :)</p>\n\n<pre><code>geocoder.getLatLng(item.mapstring, function(point) {\n if (!point) {\n geocoder.getLatLng(item.backup_mapstring, function(point) {\n if (point) {\n setPoint(point);\n }\n })\n return;\n }\n\n function setPoint(point) {\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n }\n\n setPoint(point);\n});\n</code></pre>\n"
},
{
"answer_id": 275601,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "<p>There is an exceedingly nice method for performing recursion in language constructs that don't explicitly support recursion called a <em>fixed point combinator</em>. The most well known is the <a href=\"http://en.wikipedia.org/wiki/Fixed_point_combinator\" rel=\"nofollow noreferrer\">Y-Combinator</a>.</p>\n\n<p><a href=\"http://www.cs.cityu.edu.hk/~hwchun/31337/blog/2005/09/y-combinator-in-javascript.php\" rel=\"nofollow noreferrer\">Here is the Y combinator for a function of one parameter in Javascript</a>:</p>\n\n<pre><code>function Y(le, a) {\n return function (f) {\n return f(f);\n }(function (f) {\n return le(function (x) {\n return f(f)(x);\n }, a);\n });\n}\n</code></pre>\n\n<p>This looks a little scary but you only have to write that once. Using it is actually pretty simple. Basically, you take your original lambda of one parameter, and you turn it into a new function of two parameters - the first parameter is now the actual lambda expression that you can do the recursive call on, the second parameter is the original first parameter (<code>point</code>) that you want to use.</p>\n\n<p>This is how you might use it in your example. Note that I am using <code>mapstrings</code> as a list of strings to look up and the pop function would destructively remove an element from the head.</p>\n\n<pre><code>geocoder.getLatLng(pop(mapstrings), Y(\n function(getLatLongCallback, point)\n {\n if (!point)\n {\n if (length(mapstrings) > 0)\n geocoder.getLatLng(pop(mapstrings), getLatLongCallback);\n return;\n }\n\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n });\n</code></pre>\n"
},
{
"answer_id": 275678,
"author": "tway",
"author_id": 35890,
"author_profile": "https://Stackoverflow.com/users/35890",
"pm_score": 5,
"selected": true,
"text": "<p>The other answers are good, but here's one more option. This allows you to keep the same form you started with but uses the trick of naming your lambda function so that you can refer to it recursively:</p>\n\n<pre><code>mapstrings = ['mapstring1', 'mapstring2', 'mapstring3'];\n\ngeocoder.getLatLng(mapstrings.shift(), function lambda(point) {\n if(point) {\n // success\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n }\n else if(mapstrings.length > 0) {\n // Previous mapstring failed... try next mapstring\n geocoder.getLatLng(mapstrings.shift(), lambda);\n }\n else {\n // Take special action if no mapstring succeeds?\n }\n})\n</code></pre>\n\n<p>The first time the symbol \"lambda\" is used, it is to introduce it as a new function literal name. The second time it is used, it is a recursive reference.</p>\n\n<p>function literal naming works in Chrome, and I assume it works in most modern browsers, but I haven't tested it and I don't know about older browsers.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56817/"
] |
This is kind of a brainteaser question, since the code works perfectly fine as-is, it just irritates my aesthetic sense ever so slightly. I'm turning to Stack Overflow because my own brain is failing me right now.
Here's a snippet of code that looks up an address using the Google Maps JS API and places a marker on a map. However, sometimes the initial lookup fails, so I want to repeat the process with a different address.
```
geocoder.getLatLng(item.mapstring, function(point) {
if (!point) {
geocoder.getLatLng(item.backup_mapstring, function(point) {
if (!point) return;
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
return;
}
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
```
(The second parameter to `getLatLng` is a callback function.)
Of course you can see that the three lines that center and zoom the map and add the marker are duplicated, once in the primary callback and once in the "fallback callback" (ha ha). Can you find a way to express the whole thing without any redundancy? You earn bonus points, and my adulation, if your solution works for an arbitrary number of backup map strings.
|
The other answers are good, but here's one more option. This allows you to keep the same form you started with but uses the trick of naming your lambda function so that you can refer to it recursively:
```
mapstrings = ['mapstring1', 'mapstring2', 'mapstring3'];
geocoder.getLatLng(mapstrings.shift(), function lambda(point) {
if(point) {
// success
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
}
else if(mapstrings.length > 0) {
// Previous mapstring failed... try next mapstring
geocoder.getLatLng(mapstrings.shift(), lambda);
}
else {
// Take special action if no mapstring succeeds?
}
})
```
The first time the symbol "lambda" is used, it is to introduce it as a new function literal name. The second time it is used, it is a recursive reference.
function literal naming works in Chrome, and I assume it works in most modern browsers, but I haven't tested it and I don't know about older browsers.
|
275,577 |
<p>If I have a char which holds a hex value such has 0x53, (S), how can I display this as "S"?</p>
<p>Code:</p>
<pre><code>char test = 0x53;
cout << test << endl;
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 275646,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>There's no such thing as a variable that stores a hex value, or a decimal or octal value. Hex, octal, and decimal are just different ways of representing numbers to the compiler. The compiled code will represent everything in binary.</p>\n\n<p>These statements all have the <strong>exact</strong> same effect (assuming the charset is ASCII):</p>\n\n<pre><code>test = 0x53; // hex\ntest = 'S'; // literal constant\ntest = 83; // decimal\ntest = 0123; // octal\n</code></pre>\n\n<p>So print the character the same way you would with any character, no matter how you assign it a value.</p>\n"
},
{
"answer_id": 275669,
"author": "gagneet",
"author_id": 35416,
"author_profile": "https://Stackoverflow.com/users/35416",
"pm_score": 1,
"selected": false,
"text": "<p>Just use the following, you have already answered your question:</p>\n\n<pre><code>using namespace std;\n\nint main() {\n char test = 0x53;\n std::cout << test << std::endl;\n return 0;\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33481/"
] |
If I have a char which holds a hex value such has 0x53, (S), how can I display this as "S"?
Code:
```
char test = 0x53;
cout << test << endl;
```
Thanks!
|
There's no such thing as a variable that stores a hex value, or a decimal or octal value. Hex, octal, and decimal are just different ways of representing numbers to the compiler. The compiled code will represent everything in binary.
These statements all have the **exact** same effect (assuming the charset is ASCII):
```
test = 0x53; // hex
test = 'S'; // literal constant
test = 83; // decimal
test = 0123; // octal
```
So print the character the same way you would with any character, no matter how you assign it a value.
|
275,625 |
<pre><code>var pattern = /^0+$/;
</code></pre>
<p>My guess is this:</p>
<p>"Take a look at both the beginning and the end of the string, and if there's a pattern of one or more zeros at the beginning and the end, then return that pattern."</p>
<p>I'm sure that's wrong, though, because when I run the expression with this string:</p>
<pre><code>var string = "0000009000000";
</code></pre>
<p>It comes up <code>null</code>.</p>
<p>So what's it really saying? And while I'm asking, what/how does JavaScript consider the beginning, middle and end of a string? </p>
<p><strong>UPDATE #1:</strong> Thanks for the responses! I think I understand this now. My confusion stemmed from the fact that I'm visualizing the string as having a beginning, a middle and an end. Like this:</p>
<p>[beginning][middle][end]</p>
<p>In other words, for the given string above, the following expressions work as I expect them to:</p>
<p><code>/^0+/;</code> returns "000000" (a pattern of one or more zeros at the beginning of the string)</p>
<p>and</p>
<p><code>/0+$/</code>; returns "000000" (a pattern of one or more zeros at the end of the string)</p>
<p><strong>UPDATE #2:</strong> I up-voted all the responses to this point, because they're all helpful, and I compiled the answers into one great big one:</p>
<p>Given the following JavaScript code:</p>
<pre><code>var string = "0000009000000";
var regExp = /^0+$/;
alert(regExp.exec(string));
</code></pre>
<p>It reads, in part, like this: </p>
<p>"If the exact character(s) followed by the ^ modifier and preceded by the $ modifier in the regular expression are not SIMULTANEOUSLY sitting in the first position(s) of the string AND the last position(s) of the string (i.e., they are not the only character(s) in the string), then return <code>null</code>. Else, return the character(s)."</p>
<p>In other words, let's say the given string is six zeros "000000". This results in a match because the exact same group of "0" characters are sitting in BOTH the first positions (<strong>1st 2nd 3rd</strong> 4th 5th 6th) AND the last positions (1st 2nd 3rd <strong>4th 5th 6th</strong>) of the string.</p>
<p>However, in the original given string, there are six zeros, followed by a nine, followed by six zeros ("0000009000000"). Now, the six zeros in the first positions of the string (1st, 2nd, 3rd, 4th, 5th, 6th) are NOT the exact same six zeros sitting in the last positions of the string (8th, 9th, 10th, 11th, 12th, 13th). Hence, a <code>null</code> is returned.</p>
|
[
{
"answer_id": 275628,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 3,
"selected": false,
"text": "<p>It's saying your string contains only 0... it must begin, then have 1 or more 0's, then end.</p>\n"
},
{
"answer_id": 275634,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<p>^0+$</p>\n\n<ul>\n<li>Assert position at the beginning of the string «^»</li>\n<li>Match the character “0” literally «0+»\n\n<ul>\n<li>Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»</li>\n</ul></li>\n<li>Assert position at the end of the string (or before the line break at the end of the string, if any) «$»</li>\n</ul>\n"
},
{
"answer_id": 275636,
"author": "Nate Parsons",
"author_id": 34910,
"author_profile": "https://Stackoverflow.com/users/34910",
"pm_score": 2,
"selected": false,
"text": "<p>If you want it to match your string, you want your regexp to be something like:</p>\n\n<pre><code>var pattern = /^0+.*0+$/\n</code></pre>\n\n<p>This will match 1 or more '0's at the beginning, 1 or more '0's at the end, and 0 or more of anything in the middle.</p>\n"
},
{
"answer_id": 275638,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 2,
"selected": false,
"text": "<p>A pattern of at least one <strong>0</strong>, anchored to both the beginning (<strong>^</strong>) and end (<strong>$</strong>) of a line; in other words, the string consists of one or more zeroes.</p>\n\n<p>To match a string consisting of digits 0 to 9, and starting and ending with at least one zero, the pattern</p>\n\n<pre><code>/^0+[0-9]+0$/\n</code></pre>\n\n<p>would work, i.e. match one or more zeroes, then one or more digits 0-9, ending in a zero.</p>\n\n<p>Unless otherwise instructed, JavaScript will treat the entire string as one line, ignoring newline characters; to force it to consider multiple separate lines, use the <strong>m</strong> modifier, e.g.</p>\n\n<pre><code>/regex/m\n</code></pre>\n\n<p><strong>See also:</strong> <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\">JavaScript regular expression overview on Mozilla Developer Center</a></p>\n"
},
{
"answer_id": 275677,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/(^0+|0+$)/\n</code></pre>\n"
},
{
"answer_id": 275859,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>Responding to your update -- you're kind of right. The string the regex will try to match does have a beginning, a middle and an end. </p>\n\n<p>But you know what? All strings have a beginning and an end.</p>\n\n<p>Your regex says, the string must have a beginning, an end, and <em>in between the two</em>, <strong>only</strong> a string of zeros.</p>\n\n<p>Don't think of your <code>000000</code> as being at the start, or your <code>900000</code> as being at the end.\nIn fact, ignore the idea of beginning and end for a moment.</p>\n\n<ul>\n<li>This regex matches \"must have some zeros in it somewhere\": <code>/0+/</code></li>\n<li>This regex matches \"must have some zeros in it <em>and nothing else</em>: <code>/^0+$/</code></li>\n</ul>\n\n<p>why do we add the ^ and the $? </p>\n\n<p>Because there's no regex notation for \"and nothing else\", so we have to specify \"start of string, some zeros, end of string\", which comes to the same thing.</p>\n\n<p>By the way, you got this wrong too: </p>\n\n<blockquote>\n <p>if there's a pattern of one or more zeros at the beginning and the end, then return that pattern</p>\n</blockquote>\n\n<p>your regex won't return \"that pattern\", it will only return <code>true</code>. You need brackets to get hold of the pattern: <code>/^(0+)$/</code></p>\n"
},
{
"answer_id": 275865,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 0,
"selected": false,
"text": "<p>I always put my Regex's into human words to make sure it's what I meant.</p>\n\n<p>This: ^0+$</p>\n\n<p>Would read as follows: \"If from the start (^) of my string, you find at least one (+) zero (0), and nothing else until the end ($) of the string.\"</p>\n\n<p>Remember, a regex is basically a bunch of \"If\" statements. So first, it has to be \"true\", and THEN it will return the best possible result. A Regex won't ever return a \"somewhat-true\", or a \"mostly-true\" result.</p>\n"
},
{
"answer_id": 279397,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "<p>@CodeCurious, you're still making it more complicated than it needs to be. The regex <code>/^0+$/</code> merely means the entire string consists of one or more zeros. Regexes offer plenty of opportunities for confusion, so accept simplicity wherever you can find it.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
var pattern = /^0+$/;
```
My guess is this:
"Take a look at both the beginning and the end of the string, and if there's a pattern of one or more zeros at the beginning and the end, then return that pattern."
I'm sure that's wrong, though, because when I run the expression with this string:
```
var string = "0000009000000";
```
It comes up `null`.
So what's it really saying? And while I'm asking, what/how does JavaScript consider the beginning, middle and end of a string?
**UPDATE #1:** Thanks for the responses! I think I understand this now. My confusion stemmed from the fact that I'm visualizing the string as having a beginning, a middle and an end. Like this:
[beginning][middle][end]
In other words, for the given string above, the following expressions work as I expect them to:
`/^0+/;` returns "000000" (a pattern of one or more zeros at the beginning of the string)
and
`/0+$/`; returns "000000" (a pattern of one or more zeros at the end of the string)
**UPDATE #2:** I up-voted all the responses to this point, because they're all helpful, and I compiled the answers into one great big one:
Given the following JavaScript code:
```
var string = "0000009000000";
var regExp = /^0+$/;
alert(regExp.exec(string));
```
It reads, in part, like this:
"If the exact character(s) followed by the ^ modifier and preceded by the $ modifier in the regular expression are not SIMULTANEOUSLY sitting in the first position(s) of the string AND the last position(s) of the string (i.e., they are not the only character(s) in the string), then return `null`. Else, return the character(s)."
In other words, let's say the given string is six zeros "000000". This results in a match because the exact same group of "0" characters are sitting in BOTH the first positions (**1st 2nd 3rd** 4th 5th 6th) AND the last positions (1st 2nd 3rd **4th 5th 6th**) of the string.
However, in the original given string, there are six zeros, followed by a nine, followed by six zeros ("0000009000000"). Now, the six zeros in the first positions of the string (1st, 2nd, 3rd, 4th, 5th, 6th) are NOT the exact same six zeros sitting in the last positions of the string (8th, 9th, 10th, 11th, 12th, 13th). Hence, a `null` is returned.
|
It's saying your string contains only 0... it must begin, then have 1 or more 0's, then end.
|
275,630 |
<p>I'm trying to automate some stuff in MS Excel. When I try to set the Calculation property I get the following error message: 'Unable to set the Calculation property of the Application class'</p>
<p>I believe this property should be settable.</p>
<p>Any advice appreciated!</p>
|
[
{
"answer_id": 275635,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you are setting it to a proper value.</p>\n\n<pre><code> Application.Calculation = xlCalculationManual\n</code></pre>\n\n<p>or one of the following values:</p>\n\n<p>xlCalculationAutomatic: Excel controls recalculation. <br>\nxlCalculationManual: Calculation is done when the user requests it. <br>\nxlCalculationSemiautomatic: Excel controls recalculation but ignores changes in tables. <br></p>\n"
},
{
"answer_id": 275743,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 4,
"selected": true,
"text": "<p>You need to have an open workbook, ie</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import win32com\n\n# Create new Excel instance\nxl = win32com.client.DispatchEx(\"Excel.Application\") \n\n# Open blank workbook\nxl.Workbooks.Add()\n\n# Set property\nxl.Calculation = win32com.client.constants.xlCalculationManual\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to automate some stuff in MS Excel. When I try to set the Calculation property I get the following error message: 'Unable to set the Calculation property of the Application class'
I believe this property should be settable.
Any advice appreciated!
|
You need to have an open workbook, ie
```py
import win32com
# Create new Excel instance
xl = win32com.client.DispatchEx("Excel.Application")
# Open blank workbook
xl.Workbooks.Add()
# Set property
xl.Calculation = win32com.client.constants.xlCalculationManual
```
|
275,683 |
<p>Using <a href="http://imdbpy.sourceforge.net" rel="noreferrer">IMDbPy</a> it is painfully easy to access movies from the IMDB site:</p>
<pre><code>import imdb
access = imdb.IMDb()
movie = access.get_movie(3242) # random ID
print "title: %s year: %s" % (movie['title'], movie['year'])
</code></pre>
<p>However I see no way to get the picture or thumbnail of the movie cover. Suggestions?</p>
|
[
{
"answer_id": 275774,
"author": "Tim Kersten",
"author_id": 33514,
"author_profile": "https://Stackoverflow.com/users/33514",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Note:</strong></p>\n\n<ul>\n<li>Not every movie has a cover url. (The random ID in your example doesn't.)</li>\n<li>Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)</li>\n</ul>\n\n<p>...</p>\n\n<pre><code>import imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\nprint \"title: %s year: %s\" % (movie['title'], movie['year'])\nprint \"Cover url: %s\" % movie['cover url']\n</code></pre>\n\n<p>If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\nimport imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\npage = urllib2.urlopen(access.get_imdbURL(movie))\nsoup = BeautifulSoup(page)\ncover_div = soup.find(attrs={\"class\" : \"photo\"})\ncover_url = (photo_div.find('img'))['src']\nprint \"Cover url: %s\" % cover_url\n</code></pre>\n"
},
{
"answer_id": 275826,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 2,
"selected": false,
"text": "<p>Response from the IMDbPy mailing list:</p>\n\n<blockquote>\n <p>If present, the url is accessible\n through movie['cover url']. Beware\n that it could be missing, so you must\n first test it with something like:<br>\n if 'cover url' in movie:\n ...</p>\n \n <p>After that, you can use the urllib\n module to fetch the image itself.</p>\n \n <p>To provide a complete example,\n something like that should do the\n trick:</p>\n\n<pre><code>import urllib\nfrom imdb import IMDb\n\nia = IMDb(#yourParameters)\nmovie = ia.get_movie(#theMovieID)\n\nif 'cover url' in movie:\n urlObj = urllib.urlopen(movie['cover url'])\n imageData = urlObj.read()\n urlObj.close()\n # now you can save imageData in a file (open it in binary mode).\n</code></pre>\n \n <p>In the same way, a person's headshot\n is stored in person['headshot'].</p>\n \n <p>Things to be aware of:</p>\n \n <ul>\n <li>covers and headshots are available only fetching the data from the web server (via the 'http' or 'mobile' data access systems), and not in the plain text data files ('sql' or 'local').</li>\n <li>using the images, you must respect the terms of the IMDb's policy; see <a href=\"http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt\" rel=\"nofollow noreferrer\">http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt</a></li>\n <li>the images you'll get will vary in size; you can use the python-imaging module to rescale them, if needed.</li>\n </ul>\n</blockquote>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
Using [IMDbPy](http://imdbpy.sourceforge.net) it is painfully easy to access movies from the IMDB site:
```
import imdb
access = imdb.IMDb()
movie = access.get_movie(3242) # random ID
print "title: %s year: %s" % (movie['title'], movie['year'])
```
However I see no way to get the picture or thumbnail of the movie cover. Suggestions?
|
**Note:**
* Not every movie has a cover url. (The random ID in your example doesn't.)
* Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)
...
```
import imdb
access = imdb.IMDb()
movie = access.get_movie(1132626)
print "title: %s year: %s" % (movie['title'], movie['year'])
print "Cover url: %s" % movie['cover url']
```
If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.
```
from BeautifulSoup import BeautifulSoup
import imdb
access = imdb.IMDb()
movie = access.get_movie(1132626)
page = urllib2.urlopen(access.get_imdbURL(movie))
soup = BeautifulSoup(page)
cover_div = soup.find(attrs={"class" : "photo"})
cover_url = (photo_div.find('img'))['src']
print "Cover url: %s" % cover_url
```
|
275,689 |
<p>There's a part in my apps that displays the file path loaded by the user through OpenFileDialog. It's taking up too much space to display the whole path, but I don't want to display only the filename as it might be ambiguous. So I would prefer to show the file path relative to the assembly/exe directory.</p>
<p>For example, the assembly resides at <code>C:\Program Files\Dummy Folder\MyProgram</code> and the file at <code>C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat</code> then I would like it to show <code>.\Data\datafile1.dat</code>. If the file is in <code>C:\Program Files\Dummy Folder\datafile1.dat</code>, then I would want <code>..\datafile1.dat</code>. But if the file is at the root directory or 1 directory below root, then display the full path. </p>
<p>What solution would you recommend? Regex?</p>
<p>Basically I want to display useful file path info without taking too much screen space.</p>
<p>EDIT: Just to clarify a little bit more. The purpose of this solution is to help user or myself knowing which file did I loaded last and roughly from which directory was it from. I'm using a readonly textbox to display the path. Most of the time, the file path is much longer than the display space of the textbox. The path is supposed to be informative but not important enough as to take up more screen space.</p>
<p>Alex Brault comment was good, so is Jonathan Leffler. The Win32 function provided by DavidK only help with part of the problem, not the whole of it, but thanks anyway. As for James Newton-King solution, I'll give it a try later when I'm free.</p>
|
[
{
"answer_id": 275691,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 2,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>RelPath = AbsPath.Replace(ApplicationPath, \".\")\n</code></pre>\n"
},
{
"answer_id": 275703,
"author": "3Doubloons",
"author_id": 25818,
"author_profile": "https://Stackoverflow.com/users/25818",
"pm_score": 1,
"selected": false,
"text": "<p>I'd split both of your paths at the directory level. From there, find the point of divergence and work your way back to the assembly folder, prepending a '../' everytime you pass a directory.</p>\n\n<p>Keep in mind however, that an absolute path works everywhere and is usually easier to read than a relative one. I personally wouldn't show an user a relative path unless it was absolutely necessary.</p>\n"
},
{
"answer_id": 275740,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 5,
"selected": false,
"text": "<p>There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: <a href=\"http://msdn.microsoft.com/en-us/library/bb773740(VS.85).aspx\" rel=\"noreferrer\"><code>PathRelativePathTo()</code></a></p>\n\n<p>I'm not aware of any way to access this from .NET other than to P/Invoke it, though.</p>\n"
},
{
"answer_id": 275744,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.</p>\n\n<p>Shouldn't your OpenFileDialog use a regular tree-browser structure?</p>\n\n<p>To get some nomenclature in place, the <strong>RefDir</strong> is the directory relative to which you want to specify the path; the <strong>AbsName</strong> is the absolute path name that you want to map; and the <strong>RelPath</strong> is the resulting relative path.</p>\n\n<p>Take the first of these options that matches:</p>\n\n<ul>\n<li>If you have different drive letters, there is no relative path from RefDir to AbsName; you must use the AbsName.</li>\n<li>If the AbsName is in a sub-directory of RefDir or is a file within RefDir then simply remove the RefDir from the start of AbsName to create RelPath; optionally prepend \"./\" (or \".\\\" since you are on Windows).</li>\n<li>Find the longest common prefix of RefDir and AbsName (where D:\\Abc\\Def and D:\\Abc\\Default share D:\\Abc as the longest common prefix; it has to be a mapping of name components, not a simple longest common substring); call it LCP. Remove LCP from AbsName and RefDir. For each path component left in (RefDir - LCP), prepend \"..\\\" to (AbsName - LCP) to yield RelPath.</li>\n</ul>\n\n<p>To illustrate the last rule (which is, of course, by far the most complex), start with:</p>\n\n<pre><code>RefDir = D:\\Abc\\Def\\Ghi\nAbsName = D:\\Abc\\Default\\Karma\\Crucible\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>LCP = D:\\Abc\n(RefDir - LCP) = Def\\Ghi\n(Absname - LCP) = Default\\Karma\\Crucible\nRelPath = ..\\..\\Default\\Karma\\Crucible\n</code></pre>\n\n<p>While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. <strong>Use it.</strong> But there's no harm in being able to think your way through from first principles, either.</p>\n\n<p>Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.</p>\n"
},
{
"answer_id": 275749,
"author": "James Newton-King",
"author_id": 11829,
"author_profile": "https://Stackoverflow.com/users/11829",
"pm_score": 3,
"selected": false,
"text": "<p>I have used this in the past.</p>\n\n<pre><code>/// <summary>\n/// Creates a relative path from one file\n/// or folder to another.\n/// </summary>\n/// <param name=\"fromDirectory\">\n/// Contains the directory that defines the\n/// start of the relative path.\n/// </param>\n/// <param name=\"toPath\">\n/// Contains the path that defines the\n/// endpoint of the relative path.\n/// </param>\n/// <returns>\n/// The relative path from the start\n/// directory to the end path.\n/// </returns>\n/// <exception cref=\"ArgumentNullException\"></exception>\npublic static string MakeRelative(string fromDirectory, string toPath)\n{\n if (fromDirectory == null)\n throw new ArgumentNullException(\"fromDirectory\");\n\n if (toPath == null)\n throw new ArgumentNullException(\"toPath\");\n\n bool isRooted = (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath));\n\n if (isRooted)\n {\n bool isDifferentRoot = (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0);\n\n if (isDifferentRoot)\n return toPath;\n }\n\n List<string> relativePath = new List<string>();\n string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);\n\n string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);\n\n int length = Math.Min(fromDirectories.Length, toDirectories.Length);\n\n int lastCommonRoot = -1;\n\n // find common root\n for (int x = 0; x < length; x++)\n {\n if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)\n break;\n\n lastCommonRoot = x;\n }\n\n if (lastCommonRoot == -1)\n return toPath;\n\n // add relative folders in from path\n for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)\n {\n if (fromDirectories[x].Length > 0)\n relativePath.Add(\"..\");\n }\n\n // add to folders to path\n for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)\n {\n relativePath.Add(toDirectories[x]);\n }\n\n // create relative path\n string[] relativeParts = new string[relativePath.Count];\n relativePath.CopyTo(relativeParts, 0);\n\n string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);\n\n return newPath;\n}\n</code></pre>\n"
},
{
"answer_id": 337156,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a readonly text box, could you not not make it a label and set AutoEllipsis=true?</p>\n\n<p>alternatively there are posts with code for generating the autoellipsis yourself: (this does it for a grid, you would need to pass i the width for the text box instead. It isn't quite right as it hacks off a bit more than is necessary, and I haven;t got around to finding where the calculation is incorrect.\nit would be easy enough to modify to remove the first part of the directory rather than the last if you desire.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function AddEllipsisPath(ByVal text As String, ByVal colIndex As Integer, ByVal grid As DataGridView) As String\n 'Get the size with the column's width \n Dim colWidth As Integer = grid.Columns(colIndex).Width\n\n 'Calculate the dimensions of the text with the current font\n Dim textSize As SizeF = MeasureString(text, grid.Font)\n\n Dim rawText As String = text\n Dim FileNameLen As Integer = text.Length - text.LastIndexOf(\"\\\")\n Dim ReplaceWith As String = \"\\...\"\n\n Do While textSize.Width > colWidth\n ' Trim to make room for the ellipsis\n Dim LastFolder As Integer = rawText.LastIndexOf(\"\\\", rawText.Length - FileNameLen - 1)\n\n If LastFolder < 0 Then\n Exit Do\n End If\n\n rawText = rawText.Substring(0, LastFolder) + ReplaceWith + rawText.Substring(rawText.Length - FileNameLen)\n\n If ReplaceWith.Length > 0 Then\n FileNameLen += 4\n ReplaceWith = \"\"\n End If\n textSize = MeasureString(rawText, grid.Font)\n Loop\n\n Return rawText\nEnd Function\n\nPrivate Function MeasureString(ByVal text As String, ByVal fontInfo As Font) As SizeF\n Dim size As SizeF\n Dim emSize As Single = fontInfo.Size\n If emSize = 0 Then emSize = 12\n\n Dim stringFont As New Font(fontInfo.Name, emSize)\n\n Dim bmp As New Bitmap(1000, 100)\n Dim g As Graphics = Graphics.FromImage(bmp)\n\n size = g.MeasureString(text, stringFont)\n g.Dispose()\n Return size\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 337180,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 2,
"selected": false,
"text": "<p>It's a long way around, but System.Uri class has a method named MakeRelativeUri. Maybe you could use that. It's a shame really that System.IO.Path doesn't have this.</p>\n"
},
{
"answer_id": 340454,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>.NET Core 2.0 has <code>Path.GetRelativePath</code>, else, use this.</p>\n\n<pre><code>/// <summary>\n/// Creates a relative path from one file or folder to another.\n/// </summary>\n/// <param name=\"fromPath\">Contains the directory that defines the start of the relative path.</param>\n/// <param name=\"toPath\">Contains the path that defines the endpoint of the relative path.</param>\n/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>\n/// <exception cref=\"ArgumentNullException\"></exception>\n/// <exception cref=\"UriFormatException\"></exception>\n/// <exception cref=\"InvalidOperationException\"></exception>\npublic static String MakeRelativePath(String fromPath, String toPath)\n{\n if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(\"fromPath\");\n if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException(\"toPath\");\n\n Uri fromUri = new Uri(fromPath);\n Uri toUri = new Uri(toPath);\n\n if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.\n\n Uri relativeUri = fromUri.MakeRelativeUri(toUri);\n String relativePath = Uri.UnescapeDataString(relativeUri.ToString());\n\n if (toUri.Scheme.Equals(\"file\", StringComparison.InvariantCultureIgnoreCase))\n {\n relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);\n }\n\n return relativePath;\n}\n</code></pre>\n"
},
{
"answer_id": 485516,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 6,
"selected": false,
"text": "<p>A bit late to the question, but I just needed this feature as well. I agree with DavidK that since there is a <a href=\"http://msdn.microsoft.com/en-us/library/bb773740(VS.85).aspx\" rel=\"noreferrer\">built-in API function</a> that provides this, you should use it. Here's a managed wrapper for it:</p>\n\n<pre><code>public static string GetRelativePath(string fromPath, string toPath)\n{\n int fromAttr = GetPathAttribute(fromPath);\n int toAttr = GetPathAttribute(toPath);\n\n StringBuilder path = new StringBuilder(260); // MAX_PATH\n if(PathRelativePathTo(\n path,\n fromPath,\n fromAttr,\n toPath,\n toAttr) == 0)\n {\n throw new ArgumentException(\"Paths must have a common prefix\");\n }\n return path.ToString();\n}\n\nprivate static int GetPathAttribute(string path)\n{\n DirectoryInfo di = new DirectoryInfo(path);\n if (di.Exists)\n {\n return FILE_ATTRIBUTE_DIRECTORY;\n }\n\n FileInfo fi = new FileInfo(path);\n if(fi.Exists)\n {\n return FILE_ATTRIBUTE_NORMAL;\n }\n\n throw new FileNotFoundException();\n}\n\nprivate const int FILE_ATTRIBUTE_DIRECTORY = 0x10;\nprivate const int FILE_ATTRIBUTE_NORMAL = 0x80;\n\n[DllImport(\"shlwapi.dll\", SetLastError = true)]\nprivate static extern int PathRelativePathTo(StringBuilder pszPath, \n string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);\n</code></pre>\n"
},
{
"answer_id": 485561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you're sure that your absolute path 2 is always relative to absolute path, just remove the first N characters from path2, where N is the length of path1.</p>\n"
},
{
"answer_id": 1599260,
"author": "AMissico",
"author_id": 163921,
"author_profile": "https://Stackoverflow.com/users/163921",
"pm_score": 2,
"selected": false,
"text": "<p>You want to use the <code>CommonPath</code> method of this <code>RelativePath</code> class. Once you have the common path, just strip it out of the path you want to display.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Namespace IO.Path\n\n Public NotInheritable Class RelativePath\n\n Private Declare Function PathRelativePathTo Lib \"shlwapi\" Alias \"PathRelativePathToA\" ( _\n ByVal pszPath As String, _\n ByVal pszFrom As String, _\n ByVal dwAttrFrom As Integer, _\n ByVal pszTo As String, _\n ByVal dwAttrTo As Integer) As Integer\n\n Private Declare Function PathCanonicalize Lib \"shlwapi\" Alias \"PathCanonicalizeA\" ( _\n ByVal pszBuf As String, _\n ByVal pszPath As String) As Integer\n\n Private Const FILE_ATTRIBUTE_DIRECTORY As Short = &H10S\n\n Private Const MAX_PATH As Short = 260\n\n Private _path As String\n Private _isDirectory As Boolean\n\n#Region \" Constructors \"\n\n Public Sub New()\n\n End Sub\n\n Public Sub New(ByVal path As String)\n _path = path\n End Sub\n\n Public Sub New(ByVal path As String, ByVal isDirectory As Boolean)\n _path = path\n _isDirectory = isDirectory\n End Sub\n\n#End Region\n\n Private Shared Function StripNulls(ByVal value As String) As String\n StripNulls = value\n If (InStr(value, vbNullChar) > 0) Then\n StripNulls = Left(value, InStr(value, vbNullChar) - 1)\n End If\n End Function\n\n Private Shared Function TrimCurrentDirectory(ByVal path As String) As String\n TrimCurrentDirectory = path\n If Len(path) >= 2 And Left(path, 2) = \".\\\" Then\n TrimCurrentDirectory = Mid(path, 3)\n End If\n End Function\n\n ''' <summary>\n ''' 3. conforming to general principles: conforming to accepted principles or standard practice\n ''' </summary>\n Public Shared Function Canonicalize(ByVal path As String) As String\n Dim sPath As String\n\n sPath = New String(Chr(0), MAX_PATH)\n\n If PathCanonicalize(sPath, path) = 0 Then\n Canonicalize = vbNullString\n Else\n Canonicalize = StripNulls(sPath)\n End If\n\n End Function\n\n ''' <summary>\n ''' Returns the most common path between two paths.\n ''' </summary>\n ''' <remarks>\n ''' <para>returns the path that is common between two paths</para>\n ''' <para>c:\\FolderA\\FolderB\\FolderC</para>\n ''' c:\\FolderA\\FolderD\\FolderE\\File.Ext\n ''' \n ''' results in:\n ''' c:\\FolderA\\\n ''' </remarks>\n Public Shared Function CommonPath(ByVal path1 As String, ByVal path2 As String) As String\n 'returns the path that is common between two paths\n '\n ' c:\\FolderA\\FolderB\\FolderC\n ' c:\\FolderA\\FolderD\\FolderE\\File.Ext\n '\n ' results in:\n ' c:\\FolderA\\\n\n Dim sResult As String = String.Empty\n Dim iPos1, iPos2 As Integer\n path1 = Canonicalize(path1)\n path2 = Canonicalize(path2)\n Do\n If Left(path1, iPos1) = Left(path2, iPos2) Then\n sResult = Left(path1, iPos1)\n End If\n iPos1 = InStr(iPos1 + 1, path1, \"\\\")\n iPos2 = InStr(iPos2 + 1, path1, \"\\\")\n Loop While Left(path1, iPos1) = Left(path2, iPos2)\n\n Return sResult\n\n End Function\n\n Public Function CommonPath(ByVal path As String) As String\n Return CommonPath(_path, path)\n End Function\n\n Public Shared Function RelativePathTo(ByVal source As String, ByVal isSourceDirectory As Boolean, ByVal target As String, ByVal isTargetDirectory As Boolean) As String\n 'DEVLIB\n ' 05/23/05 1:47PM - Fixed call to PathRelativePathTo, iTargetAttribute is now passed to dwAttrTo instead of IsTargetDirectory.\n ' For Visual Basic 6.0, the fix does not change testing results,\n ' because when the Boolean IsTargetDirectory is converted to the Long dwAttrTo it happens to contain FILE_ATTRIBUTE_DIRECTORY,\n '\n Dim sRelativePath As String\n Dim iSourceAttribute, iTargetAttribute As Integer\n\n sRelativePath = New String(Chr(0), MAX_PATH)\n source = Canonicalize(source)\n target = Canonicalize(target)\n\n If isSourceDirectory Then\n iSourceAttribute = FILE_ATTRIBUTE_DIRECTORY\n End If\n\n If isTargetDirectory Then\n iTargetAttribute = FILE_ATTRIBUTE_DIRECTORY\n End If\n\n If PathRelativePathTo(sRelativePath, source, iSourceAttribute, target, iTargetAttribute) = 0 Then\n RelativePathTo = vbNullString\n Else\n RelativePathTo = TrimCurrentDirectory(StripNulls(sRelativePath))\n End If\n\n End Function\n\n Public Function RelativePath(ByVal target As String) As String\n Return RelativePathTo(_path, _isDirectory, target, False)\n End Function\n\n End Class\n\nEnd Namespace\n</code></pre>\n"
},
{
"answer_id": 5891810,
"author": "Cameron Stone",
"author_id": 642311,
"author_profile": "https://Stackoverflow.com/users/642311",
"pm_score": 1,
"selected": false,
"text": "<p>If you know that toPath is contained by fromPath then you can keep it simple. I'll leave out the asserts for brevity.</p>\n\n<pre><code>public static string MakeRelativePath(string fromPath, string toPath)\n{\n // use Path.GetFullPath to canonicalise the paths (deal with multiple directory seperators, etc)\n return Path.GetFullPath(toPath).Substring(Path.GetFullPath(fromPath).Length + 1);\n}\n</code></pre>\n"
},
{
"answer_id": 19817301,
"author": "Szybki",
"author_id": 2572796,
"author_profile": "https://Stackoverflow.com/users/2572796",
"pm_score": 1,
"selected": false,
"text": "<p>The function that uses URI returned \"almost\" relative path. It included directory that directly contains the file which relative path I wanted to get.</p>\n\n<p>Some time ago I wrote a simple function that returns relative path of folder or file, and even if it's on another drive, it includes the drive letter as well.</p>\n\n<p>Please take a look:</p>\n\n<pre><code> public static string GetRelativePath(string BasePath, string AbsolutePath)\n {\n char Separator = Path.DirectorySeparatorChar;\n if (string.IsNullOrWhiteSpace(BasePath)) BasePath = Directory.GetCurrentDirectory();\n var ReturnPath = \"\";\n var CommonPart = \"\";\n var BasePathFolders = BasePath.Split(Separator);\n var AbsolutePathFolders = AbsolutePath.Split(Separator);\n var i = 0;\n while (i < BasePathFolders.Length & i < AbsolutePathFolders.Length)\n {\n if (BasePathFolders[i].ToLower() == AbsolutePathFolders[i].ToLower())\n {\n CommonPart += BasePathFolders[i] + Separator;\n }\n else\n {\n break;\n }\n i += 1;\n }\n if (CommonPart.Length > 0)\n {\n var parents = BasePath.Substring(CommonPart.Length - 1).Split(Separator);\n foreach (var ParentDir in parents)\n {\n if (!string.IsNullOrEmpty(ParentDir))\n ReturnPath += \"..\" + Separator;\n }\n }\n ReturnPath += AbsolutePath.Substring(CommonPart.Length);\n return ReturnPath;\n }\n</code></pre>\n"
},
{
"answer_id": 29119169,
"author": "Maxence",
"author_id": 200443,
"author_profile": "https://Stackoverflow.com/users/200443",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using this:</p>\n\n<pre><code>public static class StringExtensions\n{\n /// <summary>\n /// Creates a relative path from one file or folder to another.\n /// </summary>\n /// <param name=\"absPath\">Absolute path.</param>\n /// <param name=\"relTo\">Directory that defines the start of the relative path.</param> \n /// <returns>The relative path from the start directory to the end path.</returns>\n public static string MakeRelativePath(this string absPath, string relTo)\n {\n string[] absParts = absPath.Split(Path.DirectorySeparatorChar);\n string[] relParts = relTo.Split(Path.DirectorySeparatorChar);\n\n // Get the shortest of the two paths\n int len = absParts.Length < relParts.Length\n ? absParts.Length : relParts.Length;\n\n // Use to determine where in the loop we exited\n int lastCommonRoot = -1;\n int index;\n\n // Find common root\n for (index = 0; index < len; index++)\n {\n if (absParts[index].Equals(relParts[index], StringComparison.OrdinalIgnoreCase))\n lastCommonRoot = index;\n else \n break;\n }\n\n // If we didn't find a common prefix then throw\n if (lastCommonRoot == -1)\n throw new ArgumentException(\"The path of the two files doesn't have any common base.\");\n\n // Build up the relative path\n var relativePath = new StringBuilder();\n\n // Add on the ..\n for (index = lastCommonRoot + 1; index < relParts.Length; index++)\n {\n relativePath.Append(\"..\");\n relativePath.Append(Path.DirectorySeparatorChar);\n }\n\n // Add on the folders\n for (index = lastCommonRoot + 1; index < absParts.Length - 1; index++)\n {\n relativePath.Append(absParts[index]);\n relativePath.Append(Path.DirectorySeparatorChar);\n }\n relativePath.Append(absParts[absParts.Length - 1]);\n\n return relativePath.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32113484,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 6,
"selected": false,
"text": "<h1>.NET Core 2.0 Answer</h1>\n\n<p>.NET Core 2.0 has <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath?view=netcore-3.1\" rel=\"noreferrer\">Path.GetRelativePath</a> which can be used like so:</p>\n\n<pre><code>var relativePath = Path.GetRelativePath(\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\",\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\");\n</code></pre>\n\n<p>In the above example, the <code>relativePath</code> variable is equal to <code>Data\\datafile1.dat</code>.</p>\n\n<h1>Alternative .NET Answer</h1>\n\n<p>@Dave's solution does not work when the file paths do not end with a forward slash character (<code>/</code>) which can happen if the path is a directory path. My solution fixes that problem and also makes use of the <code>Uri.UriSchemeFile</code> constant instead of hard coding <code>\"FILE\"</code>.</p>\n\n<pre><code>/// <summary>\n/// Creates a relative path from one file or folder to another.\n/// </summary>\n/// <param name=\"fromPath\">Contains the directory that defines the start of the relative path.</param>\n/// <param name=\"toPath\">Contains the path that defines the endpoint of the relative path.</param>\n/// <returns>The relative path from the start directory to the end path.</returns>\n/// <exception cref=\"ArgumentNullException\"><paramref name=\"fromPath\"/> or <paramref name=\"toPath\"/> is <c>null</c>.</exception>\n/// <exception cref=\"UriFormatException\"></exception>\n/// <exception cref=\"InvalidOperationException\"></exception>\npublic static string GetRelativePath(string fromPath, string toPath)\n{\n if (string.IsNullOrEmpty(fromPath))\n {\n throw new ArgumentNullException(\"fromPath\");\n }\n\n if (string.IsNullOrEmpty(toPath))\n {\n throw new ArgumentNullException(\"toPath\");\n }\n\n Uri fromUri = new Uri(AppendDirectorySeparatorChar(fromPath));\n Uri toUri = new Uri(AppendDirectorySeparatorChar(toPath));\n\n if (fromUri.Scheme != toUri.Scheme)\n {\n return toPath;\n }\n\n Uri relativeUri = fromUri.MakeRelativeUri(toUri);\n string relativePath = Uri.UnescapeDataString(relativeUri.ToString());\n\n if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))\n {\n relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);\n }\n\n return relativePath;\n}\n\nprivate static string AppendDirectorySeparatorChar(string path)\n{\n // Append a slash only if the path is a directory and does not have a slash.\n if (!Path.HasExtension(path) &&\n !path.EndsWith(Path.DirectorySeparatorChar.ToString()))\n {\n return path + Path.DirectorySeparatorChar;\n }\n\n return path;\n}\n</code></pre>\n\n<h1>Windows Interop Answer</h1>\n\n<p>There is a Windows API called <a href=\"https://learn.microsoft.com/en-gb/windows/win32/api/shlwapi/nf-shlwapi-pathrelativepathtoa?redirectedfrom=MSDN\" rel=\"noreferrer\">PathRelativePathToA</a> that can be used to find a relative path. Please note that the file or directory paths that you pass to the function must exist for it to work.</p>\n\n<pre><code>var relativePath = PathExtended.GetRelativePath(\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\",\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\");\n\npublic static class PathExtended\n{\n private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;\n private const int FILE_ATTRIBUTE_NORMAL = 0x80;\n private const int MaximumPath = 260;\n\n public static string GetRelativePath(string fromPath, string toPath)\n {\n var fromAttribute = GetPathAttribute(fromPath);\n var toAttribute = GetPathAttribute(toPath);\n\n var stringBuilder = new StringBuilder(MaximumPath);\n if (PathRelativePathTo(\n stringBuilder,\n fromPath,\n fromAttribute,\n toPath,\n toAttribute) == 0)\n {\n throw new ArgumentException(\"Paths must have a common prefix.\");\n }\n\n return stringBuilder.ToString();\n }\n\n private static int GetPathAttribute(string path)\n {\n var directory = new DirectoryInfo(path);\n if (directory.Exists)\n {\n return FILE_ATTRIBUTE_DIRECTORY;\n }\n\n var file = new FileInfo(path);\n if (file.Exists)\n {\n return FILE_ATTRIBUTE_NORMAL;\n }\n\n throw new FileNotFoundException(\n \"A file or directory with the specified path was not found.\",\n path);\n }\n\n [DllImport(\"shlwapi.dll\", SetLastError = true)]\n private static extern int PathRelativePathTo(\n StringBuilder pszPath,\n string pszFrom,\n int dwAttrFrom,\n string pszTo,\n int dwAttrTo);\n}\n</code></pre>\n"
},
{
"answer_id": 33079341,
"author": "user626528",
"author_id": 626528,
"author_profile": "https://Stackoverflow.com/users/626528",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public static string ToRelativePath(string filePath, string refPath)\n {\n var pathNormalized = Path.GetFullPath(filePath);\n\n var refNormalized = Path.GetFullPath(refPath);\n refNormalized = refNormalized.TrimEnd('\\\\', '/');\n\n if (!pathNormalized.StartsWith(refNormalized))\n throw new ArgumentException();\n var res = pathNormalized.Substring(refNormalized.Length + 1);\n return res;\n }\n</code></pre>\n"
},
{
"answer_id": 41189926,
"author": "excanoe",
"author_id": 474967,
"author_profile": "https://Stackoverflow.com/users/474967",
"pm_score": 0,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>private string rel(string path) {\n string[] cwd = new Regex(@\"[\\\\]\").Split(Directory.GetCurrentDirectory());\n string[] fp = new Regex(@\"[\\\\]\").Split(path);\n\n int common = 0;\n\n for (int n = 0; n < fp.Length; n++) {\n if (n < cwd.Length && n < fp.Length && cwd[n] == fp[n]) {\n common++;\n }\n }\n\n if (common > 0) {\n List<string> rp = new List<string>();\n\n for (int n = 0; n < (cwd.Length - common); n++) {\n rp.Add(\"..\");\n }\n\n for (int n = common; n < fp.Length; n++) {\n rp.Add(fp[n]);\n }\n\n return String.Join(\"/\", rp.ToArray());\n } else {\n return String.Join(\"/\", fp);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45590737,
"author": "Alexey Makarenya",
"author_id": 2043898,
"author_profile": "https://Stackoverflow.com/users/2043898",
"pm_score": 0,
"selected": false,
"text": "<p>Way with Uri not worked on linux/macOS systems. Path '/var/www/root' can't be converted to Uri. More universal way - do all by hands.</p>\n\n<pre><code>public static string MakeRelativePath(string fromPath, string toPath, string sep = \"/\")\n{\n var fromParts = fromPath.Split(new[] { '/', '\\\\'},\n StringSplitOptions.RemoveEmptyEntries);\n var toParts = toPath.Split(new[] { '/', '\\\\'},\n StringSplitOptions.RemoveEmptyEntries);\n\n var matchedParts = fromParts\n .Zip(toParts, (x, y) => string.Compare(x, y, true) == 0)\n .TakeWhile(x => x).Count();\n\n return string.Join(\"\", Enumerable.Range(0, fromParts.Length - matchedParts)\n .Select(x => \"..\" + sep)) +\n string.Join(sep, toParts.Skip(matchedParts));\n} \n</code></pre>\n\n<p>PS: i use \"/\" as a default value of separator instead of Path.DirectorySeparatorChar, because result of this method used as uri in my app.</p>\n"
},
{
"answer_id": 47233440,
"author": "Spongman",
"author_id": 204555,
"author_profile": "https://Stackoverflow.com/users/204555",
"pm_score": 0,
"selected": false,
"text": "<p>here's mine:</p>\n\n<pre><code>public static string RelativePathTo(this System.IO.DirectoryInfo @this, string to)\n{\n var rgFrom = @this.FullName.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);\n var rgTo = to.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);\n var cSame = rgFrom.TakeWhile((p, i) => i < rgTo.Length && string.Equals(p, rgTo[i])).Count();\n\n return Path.Combine(\n Enumerable.Range(0, rgFrom.Length - cSame)\n .Select(_ => \"..\")\n .Concat(rgTo.Skip(cSame))\n .ToArray()\n );\n}\n</code></pre>\n"
},
{
"answer_id": 47340368,
"author": "Sergey Orlov",
"author_id": 1588592,
"author_profile": "https://Stackoverflow.com/users/1588592",
"pm_score": 0,
"selected": false,
"text": "<p>Play with something like:</p>\n\n<pre><code>private String GetRelativePath(Int32 level, String directory, out String errorMessage) {\n if (level < 0 || level > 5) {\n errorMessage = \"Find some more smart input data\";\n return String.Empty;\n }\n // ==========================\n while (level != 0) {\n directory = Path.GetDirectoryName(directory);\n level -= 1;\n }\n // ==========================\n errorMessage = String.Empty;\n return directory;\n }\n</code></pre>\n\n<p>And test it</p>\n\n<pre><code>[Test]\n public void RelativeDirectoryPathTest() {\n var relativePath =\n GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);\n Console.WriteLine(relativePath);\n if (String.IsNullOrEmpty(errorMessage) == false) {\n Console.WriteLine(errorMessage);\n Assert.Fail(\"Can not find relative path\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 48756531,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath\" rel=\"noreferrer\">.NET Core 2.0, <code>Path.GetRelativePath()</code></a> is available providing this specific functionality:</p>\n\n<pre><code> var relativeTo = @\"C:\\Program Files\\Dummy Folder\\MyProgram\";\n var path = @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\";\n\n string relativePath = System.IO.Path.GetRelativePath(relativeTo, path);\n\n System.Console.WriteLine(relativePath);\n // output --> Data\\datafile1.dat \n</code></pre>\n\n<p>Otherwise, for .NET full framework (as of v4.7) recommend using one of the other suggested answers.</p>\n"
},
{
"answer_id": 51181785,
"author": "Anton Krouglov",
"author_id": 2746150,
"author_profile": "https://Stackoverflow.com/users/2746150",
"pm_score": 3,
"selected": false,
"text": "<p>As pointed <a href=\"https://stackoverflow.com/a/48756531/2746150\">above</a> .NET Core 2.x has implementation of <code>Path.GetRelativePath</code>. </p>\n\n<p>Code below is adapted from sources and works fine with .NET 4.7.1 Framework.</p>\n\n<pre><code>// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n//Adapted from https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Path.cs#L697\n// by Anton Krouglov\n\nusing System.Runtime.CompilerServices;\nusing System.Diagnostics;\nusing System.Text;\nusing Xunit;\n\nnamespace System.IO {\n // Provides methods for processing file system strings in a cross-platform manner.\n // Most of the methods don't do a complete parsing (such as examining a UNC hostname), \n // but they will handle most string operations.\n public static class PathNetCore {\n\n /// <summary>\n /// Create a relative path from one path to another. Paths will be resolved before calculating the difference.\n /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix).\n /// </summary>\n /// <param name=\"relativeTo\">The source path the output should be relative to. This path is always considered to be a directory.</param>\n /// <param name=\"path\">The destination path.</param>\n /// <returns>The relative path or <paramref name=\"path\"/> if the paths don't share the same root.</returns>\n /// <exception cref=\"ArgumentNullException\">Thrown if <paramref name=\"relativeTo\"/> or <paramref name=\"path\"/> is <c>null</c> or an empty string.</exception>\n public static string GetRelativePath(string relativeTo, string path) {\n return GetRelativePath(relativeTo, path, StringComparison);\n }\n\n private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) {\n if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo));\n if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));\n Debug.Assert(comparisonType == StringComparison.Ordinal ||\n comparisonType == StringComparison.OrdinalIgnoreCase);\n\n relativeTo = Path.GetFullPath(relativeTo);\n path = Path.GetFullPath(path);\n\n // Need to check if the roots are different- if they are we need to return the \"to\" path.\n if (!PathInternalNetCore.AreRootsEqual(relativeTo, path, comparisonType))\n return path;\n\n int commonLength = PathInternalNetCore.GetCommonPathLength(relativeTo, path,\n ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);\n\n // If there is nothing in common they can't share the same root, return the \"to\" path as is.\n if (commonLength == 0)\n return path;\n\n // Trailing separators aren't significant for comparison\n int relativeToLength = relativeTo.Length;\n if (PathInternalNetCore.EndsInDirectorySeparator(relativeTo))\n relativeToLength--;\n\n bool pathEndsInSeparator = PathInternalNetCore.EndsInDirectorySeparator(path);\n int pathLength = path.Length;\n if (pathEndsInSeparator)\n pathLength--;\n\n // If we have effectively the same path, return \".\"\n if (relativeToLength == pathLength && commonLength >= relativeToLength) return \".\";\n\n // We have the same root, we need to calculate the difference now using the\n // common Length and Segment count past the length.\n //\n // Some examples:\n //\n // C:\\Foo C:\\Bar L3, S1 -> ..\\Bar\n // C:\\Foo C:\\Foo\\Bar L6, S0 -> Bar\n // C:\\Foo\\Bar C:\\Bar\\Bar L3, S2 -> ..\\..\\Bar\\Bar\n // C:\\Foo\\Foo C:\\Foo\\Bar L7, S1 -> ..\\Bar\n\n StringBuilder\n sb = new StringBuilder(); //StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length));\n\n // Add parent segments for segments past the common on the \"from\" path\n if (commonLength < relativeToLength) {\n sb.Append(\"..\");\n\n for (int i = commonLength + 1; i < relativeToLength; i++) {\n if (PathInternalNetCore.IsDirectorySeparator(relativeTo[i])) {\n sb.Append(DirectorySeparatorChar);\n sb.Append(\"..\");\n }\n }\n }\n else if (PathInternalNetCore.IsDirectorySeparator(path[commonLength])) {\n // No parent segments and we need to eat the initial separator\n // (C:\\Foo C:\\Foo\\Bar case)\n commonLength++;\n }\n\n // Now add the rest of the \"to\" path, adding back the trailing separator\n int differenceLength = pathLength - commonLength;\n if (pathEndsInSeparator)\n differenceLength++;\n\n if (differenceLength > 0) {\n if (sb.Length > 0) {\n sb.Append(DirectorySeparatorChar);\n }\n\n sb.Append(path, commonLength, differenceLength);\n }\n\n return sb.ToString(); //StringBuilderCache.GetStringAndRelease(sb);\n }\n\n // Public static readonly variant of the separators. The Path implementation itself is using\n // internal const variant of the separators for better performance.\n public static readonly char DirectorySeparatorChar = PathInternalNetCore.DirectorySeparatorChar;\n public static readonly char AltDirectorySeparatorChar = PathInternalNetCore.AltDirectorySeparatorChar;\n public static readonly char VolumeSeparatorChar = PathInternalNetCore.VolumeSeparatorChar;\n public static readonly char PathSeparator = PathInternalNetCore.PathSeparator;\n\n /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary>\n internal static StringComparison StringComparison => StringComparison.OrdinalIgnoreCase;\n }\n\n /// <summary>Contains internal path helpers that are shared between many projects.</summary>\n internal static class PathInternalNetCore {\n internal const char DirectorySeparatorChar = '\\\\';\n internal const char AltDirectorySeparatorChar = '/';\n internal const char VolumeSeparatorChar = ':';\n internal const char PathSeparator = ';';\n\n internal const string ExtendedDevicePathPrefix = @\"\\\\?\\\";\n internal const string UncPathPrefix = @\"\\\\\";\n internal const string UncDevicePrefixToInsert = @\"?\\UNC\\\";\n internal const string UncExtendedPathPrefix = @\"\\\\?\\UNC\\\";\n internal const string DevicePathPrefix = @\"\\\\.\\\";\n\n //internal const int MaxShortPath = 260;\n\n // \\\\?\\, \\\\.\\, \\??\\\n internal const int DevicePrefixLength = 4;\n\n /// <summary>\n /// Returns true if the two paths have the same root\n /// </summary>\n internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) {\n int firstRootLength = GetRootLength(first);\n int secondRootLength = GetRootLength(second);\n\n return firstRootLength == secondRootLength\n && string.Compare(\n strA: first,\n indexA: 0,\n strB: second,\n indexB: 0,\n length: firstRootLength,\n comparisonType: comparisonType) == 0;\n }\n\n /// <summary>\n /// Gets the length of the root of the path (drive, share, etc.).\n /// </summary>\n internal static int GetRootLength(string path) {\n int i = 0;\n int volumeSeparatorLength = 2; // Length to the colon \"C:\"\n int uncRootLength = 2; // Length to the start of the server name \"\\\\\"\n\n bool extendedSyntax = path.StartsWith(ExtendedDevicePathPrefix);\n bool extendedUncSyntax = path.StartsWith(UncExtendedPathPrefix);\n if (extendedSyntax) {\n // Shift the position we look for the root from to account for the extended prefix\n if (extendedUncSyntax) {\n // \"\\\\\" -> \"\\\\?\\UNC\\\"\n uncRootLength = UncExtendedPathPrefix.Length;\n }\n else {\n // \"C:\" -> \"\\\\?\\C:\"\n volumeSeparatorLength += ExtendedDevicePathPrefix.Length;\n }\n }\n\n if ((!extendedSyntax || extendedUncSyntax) && path.Length > 0 && IsDirectorySeparator(path[0])) {\n // UNC or simple rooted path (e.g. \"\\foo\", NOT \"\\\\?\\C:\\foo\")\n\n i = 1; // Drive rooted (\\foo) is one character\n if (extendedUncSyntax || (path.Length > 1 && IsDirectorySeparator(path[1]))) {\n // UNC (\\\\?\\UNC\\ or \\\\), scan past the next two directory separators at most\n // (e.g. to \\\\?\\UNC\\Server\\Share or \\\\Server\\Share\\)\n i = uncRootLength;\n int n = 2; // Maximum separators to skip\n while (i < path.Length && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;\n }\n }\n else if (path.Length >= volumeSeparatorLength &&\n path[volumeSeparatorLength - 1] == PathNetCore.VolumeSeparatorChar) {\n // Path is at least longer than where we expect a colon, and has a colon (\\\\?\\A:, A:)\n // If the colon is followed by a directory separator, move past it\n i = volumeSeparatorLength;\n if (path.Length >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;\n }\n\n return i;\n }\n\n /// <summary>\n /// True if the given character is a directory separator.\n /// </summary>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n internal static bool IsDirectorySeparator(char c) {\n return c == PathNetCore.DirectorySeparatorChar || c == PathNetCore.AltDirectorySeparatorChar;\n }\n\n /// <summary>\n /// Get the common path length from the start of the string.\n /// </summary>\n internal static int GetCommonPathLength(string first, string second, bool ignoreCase) {\n int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);\n\n // If nothing matches\n if (commonChars == 0)\n return commonChars;\n\n // Or we're a full string and equal length or match to a separator\n if (commonChars == first.Length\n && (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))\n return commonChars;\n\n if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))\n return commonChars;\n\n // It's possible we matched somewhere in the middle of a segment e.g. C:\\Foodie and C:\\Foobar.\n while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))\n commonChars--;\n\n return commonChars;\n }\n\n /// <summary>\n /// Gets the count of common characters from the left optionally ignoring case\n /// </summary>\n internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) {\n if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0;\n\n int commonChars = 0;\n\n fixed (char* f = first)\n fixed (char* s = second) {\n char* l = f;\n char* r = s;\n char* leftEnd = l + first.Length;\n char* rightEnd = r + second.Length;\n\n while (l != leftEnd && r != rightEnd\n && (*l == *r || (ignoreCase &&\n char.ToUpperInvariant((*l)) == char.ToUpperInvariant((*r))))) {\n commonChars++;\n l++;\n r++;\n }\n }\n\n return commonChars;\n }\n\n /// <summary>\n /// Returns true if the path ends in a directory separator.\n /// </summary>\n internal static bool EndsInDirectorySeparator(string path)\n => path.Length > 0 && IsDirectorySeparator(path[path.Length - 1]);\n }\n\n /// <summary> Tests for PathNetCore.GetRelativePath </summary>\n public static class GetRelativePathTests {\n [Theory]\n [InlineData(@\"C:\\\", @\"C:\\\", @\".\")]\n [InlineData(@\"C:\\a\", @\"C:\\a\\\", @\".\")]\n [InlineData(@\"C:\\A\", @\"C:\\a\\\", @\".\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\a\", @\".\")]\n [InlineData(@\"C:\\\", @\"C:\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\", @\"..\\b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\\\", @\"..\\b\\\")]\n [InlineData(@\"C:\\a\\b\", @\"C:\\a\", @\"..\")]\n [InlineData(@\"C:\\a\\b\", @\"C:\\a\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\\", @\"C:\\a\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\\", @\"C:\\a\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\b\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\b\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\b\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\b\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\b\", @\"..\\b\")]\n [InlineData(@\"C:\\a\", @\"C:\\a\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\A\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\\c\", @\"..\\b\\c\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\a\\b\", @\"b\")]\n [InlineData(@\"C:\\\", @\"D:\\\", @\"D:\\\")]\n [InlineData(@\"C:\\\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\\", @\"D:\\b\\\", @\"D:\\b\\\")]\n [InlineData(@\"C:\\a\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\a\\\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\ab\", @\"C:\\a\", @\"..\\a\")]\n [InlineData(@\"C:\\a\", @\"C:\\ab\", @\"..\\ab\")]\n [InlineData(@\"C:\\\", @\"\\\\LOCALHOST\\Share\\b\", @\"\\\\LOCALHOST\\Share\\b\")]\n [InlineData(@\"\\\\LOCALHOST\\Share\\a\", @\"\\\\LOCALHOST\\Share\\b\", @\"..\\b\")]\n //[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths\n public static void GetRelativePath_Windows(string relativeTo, string path, string expected) {\n string result = PathNetCore.GetRelativePath(relativeTo, path);\n Assert.Equal(expected, result);\n\n // Check that we get the equivalent path when the result is combined with the sources\n Assert.Equal(\n Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar),\n Path.GetFullPath(Path.Combine(Path.GetFullPath(relativeTo), result))\n .TrimEnd(Path.DirectorySeparatorChar),\n ignoreCase: true,\n ignoreLineEndingDifferences: false,\n ignoreWhiteSpaceDifferences: false);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 58657062,
"author": "Dragos Durlut",
"author_id": 249895,
"author_profile": "https://Stackoverflow.com/users/249895",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>ASP.NET Core 2</code>, if you want the relative path to <code>bin\\Debug\\netcoreapp2.2</code> you can use the following combination: </p>\n\n<pre><code>using Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Configuration;\npublic class RenderingService : IRenderingService\n{\n\n private readonly IHostingEnvironment _hostingEnvironment;\n public RenderingService(IHostingEnvironment hostingEnvironment)\n {\n _hostingEnvironment = hostingEnvironment;\n }\n\n public string RelativeAssemblyDirectory()\n {\n var contentRootPath = _hostingEnvironment.ContentRootPath;\n string executingAssemblyDirectoryAbsolutePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n string executingAssemblyDirectoryRelativePath = System.IO.Path.GetRelativePath(contentRootPath, executingAssemblyDirectoryAbsolutePath);\n return executingAssemblyDirectoryRelativePath;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73768911,
"author": "Chris Schaller",
"author_id": 1690217,
"author_profile": "https://Stackoverflow.com/users/1690217",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>Adapted answer from duplicate: <a href=\"https://stackoverflow.com/a/41578297/1690217\">How to make an absolute path relative to a particular folder?</a> and updated to match parameter sequence as the <a href=\"https://GetRelativePath\" rel=\"nofollow noreferrer\">.Net standard implementation</a></p>\n</blockquote>\n<p>This is a more concise implementation for .Net Framework that has thorough guidance in the doc comments and accounts for absolute paths that have relative folder links which is missing from many other solutions.</p>\n<blockquote>\n<p>Tested against <a href=\"https://stackoverflow.com/a/51181785/1690217\">Anton Krouglov's</a> test cases in .Net 6 all cases match <a href=\"https://GetRelativePath\" rel=\"nofollow noreferrer\"><code>System.IO.Path.GetRelativePath</code></a> :)</p>\n</blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code>public static partial class PathUtilities\n{\n /// <summary>\n /// Rebases file with <paramref name="path"/> to the folder specified by <paramref name="relativeTo"/>.\n /// </summary>\n /// <param name="path">Full file path (absolute)</param>\n /// <param name="relativeTo">Full base directory path (absolute) the result should be relative to. This path is always considered to be a directory.</param>\n /// <returns>Relative path to file with respect to <paramref name="relativeTo"/></returns>\n /// <remarks>Paths are resolved by calling the <seealso cref="System.IO.Path.GetFullPath(string)"/> method before calculating the difference. This will resolve relative path fragments:\n /// <code>\n /// "c:\\test\\..\\test2" => "c:\\test2"\n /// </code>\n /// These path framents are expected to be created by concatenating a root folder with a relative path such as this:\n /// <code>\n /// var baseFolder = @"c:\\test\\";\n /// var virtualPath = @"..\\test2";\n /// var fullPath = System.IO.Path.Combine(baseFolder, virtualPath);\n /// </code>\n /// The default file path for the current executing environment will be used for the base resolution for this operation, which may not be appropriate if the input paths are fully relative or relative to different\n /// respective base paths. For this reason we should attempt to resolve absolute input paths <i>before</i> passing through as arguments to this method.\n /// </remarks>\n static public string GetRelativePath(string relativeTo, string path)\n {\n String pathSep = "\\\\";\n String itemPath = Path.GetFullPath(path);\n String baseDirPath = Path.GetFullPath(relativeTo); // If folder contains upper folder references, they get resolved here. "c:\\test\\..\\test2" => "c:\\test2"\n bool isDirectory = path.EndsWith(pathSep);\n\n String[] p1 = Regex.Split(itemPath, "[\\\\\\\\/]").Where(x => x.Length != 0).ToArray();\n String[] p2 = Regex.Split(relativeTo, "[\\\\\\\\/]").Where(x => x.Length != 0).ToArray();\n int i = 0;\n\n for (; i < p1.Length && i < p2.Length; i++)\n if (String.Compare(p1[i], p2[i], true) != 0) // Case insensitive match\n break;\n\n if (i == 0) // Cannot make relative path, for example if resides on different drive\n return itemPath;\n\n String r = String.Join(pathSep, Enumerable.Repeat("..", p2.Length - i).Concat(p1.Skip(i).Take(p1.Length - i)));\n if (String.IsNullOrEmpty(r)) return ".";\n else if (isDirectory && p1.Length >= p2.Length) // only append on forward traversal, to match .Net Standard Implementation of System.IO.Path.GetRelativePath\n r += pathSep;\n\n return r;\n }\n}\n</code></pre>\n<p>Usage of this method:</p>\n<pre><code>string itemPath = @"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat";\nstring baseDirectory = @"C:\\Program Files\\Dummy Folder\\MyProgram";\nstring result = PathUtilities.GetRelativePath(baseDirectory, itemPath);\nConsole.WriteLine(result);\n</code></pre>\n<p>Results in:</p>\n<pre><code>Data\\datafile1.dat\n</code></pre>\n<blockquote>\n<p><strong>RE:</strong> But if the file is at the root directory or <strong>1 directory below root, then display the full path.</strong><br />\nIn this case we could modify the method, or simply perform an additional check:</p>\n<pre><code> string itemPath = @"C:\\Program Files\\Dummy Folder\\datafile1.dat";\n string baseDirectory = @"C:\\Program Files\\Dummy Folder\\MyProgram";\n string result = PathUtilities.GetRelativePath(baseDirectory, itemPath);\n Console.WriteLine("Before Check: '{0}'", result);\n if (result.StartsWith("..\\\\"))\n result = itemPath;\n Console.WriteLine("After Check: '{0}'", result);\n</code></pre>\n<p>Result:</p>\n<pre><code> Before Check: '..\\datafile1.dat'\n After Check: 'C:\\Program Files\\Dummy Folder\\datafile1.dat'\n</code></pre>\n</blockquote>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20007/"
] |
There's a part in my apps that displays the file path loaded by the user through OpenFileDialog. It's taking up too much space to display the whole path, but I don't want to display only the filename as it might be ambiguous. So I would prefer to show the file path relative to the assembly/exe directory.
For example, the assembly resides at `C:\Program Files\Dummy Folder\MyProgram` and the file at `C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat` then I would like it to show `.\Data\datafile1.dat`. If the file is in `C:\Program Files\Dummy Folder\datafile1.dat`, then I would want `..\datafile1.dat`. But if the file is at the root directory or 1 directory below root, then display the full path.
What solution would you recommend? Regex?
Basically I want to display useful file path info without taking too much screen space.
EDIT: Just to clarify a little bit more. The purpose of this solution is to help user or myself knowing which file did I loaded last and roughly from which directory was it from. I'm using a readonly textbox to display the path. Most of the time, the file path is much longer than the display space of the textbox. The path is supposed to be informative but not important enough as to take up more screen space.
Alex Brault comment was good, so is Jonathan Leffler. The Win32 function provided by DavidK only help with part of the problem, not the whole of it, but thanks anyway. As for James Newton-King solution, I'll give it a try later when I'm free.
|
.NET Core 2.0 has `Path.GetRelativePath`, else, use this.
```
/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static String MakeRelativePath(String fromPath, String toPath)
{
if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
String relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
```
|
275,707 |
<p>Create a file called Valid[File].txt and stick some text in it. Start powershell and go to the directory.<br>
<PRE>
gc Valid[File].txt
</PRE>
should display the value in the file. It returns blank. If you use tab auto-completion it escapes the name:
<PRE>
gc 'Valid<code>[File</code>].txt'
</PRE>
but still returns nothing.</p>
<p>How do I reference files with brackets in their names?</p>
|
[
{
"answer_id": 275718,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 0,
"selected": false,
"text": "<p>You probably need to enclose it in quotation marks: gc \"Valid[File].txt\"</p>\n"
},
{
"answer_id": 275719,
"author": "Brian Adams",
"author_id": 32992,
"author_profile": "https://Stackoverflow.com/users/32992",
"pm_score": 4,
"selected": true,
"text": "<p>Turns out the key was <code>-literalpath</code>. For details see <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/pstips/jun08/pstip0620.mspx\" rel=\"nofollow noreferrer\">this technet article</a></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32992/"
] |
Create a file called Valid[File].txt and stick some text in it. Start powershell and go to the directory.
```
gc Valid[File].txt
```
should display the value in the file. It returns blank. If you use tab auto-completion it escapes the name:
```
gc 'Valid[File].txt'
```
but still returns nothing.
How do I reference files with brackets in their names?
|
Turns out the key was `-literalpath`. For details see [this technet article](http://www.microsoft.com/technet/scriptcenter/resources/pstips/jun08/pstip0620.mspx)
|
275,711 |
<p>Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)</p>
<pre><code>static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
</code></pre>
|
[
{
"answer_id": 275715,
"author": "begray",
"author_id": 12123,
"author_profile": "https://Stackoverflow.com/users/12123",
"pm_score": 12,
"selected": true,
"text": "<p>String.format (<a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax\" rel=\"noreferrer\">https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax</a>)</p>\n\n<p>In your case it will be: </p>\n\n<pre><code>String formatted = String.format(\"%03d\", num);\n</code></pre>\n\n<ul>\n<li>0 - to pad with zeros</li>\n<li>3 - to set width to 3</li>\n</ul>\n"
},
{
"answer_id": 275716,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 7,
"selected": false,
"text": "<p>Since Java 1.5 you can use the <code>String.format</code> method. For example, to do the same thing as your example:</p>\n<pre><code>String format = String.format("%0%d", digits);\nString result = String.format(format, num);\nreturn result;\n</code></pre>\n<p>In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:</p>\n<pre><code>%% --> %\n0 --> 0\n%d --> <value of digits>\nd --> d\n</code></pre>\n<p>So if digits is equal to 5, the format string becomes <code>%05d</code> which specifies an integer with a width of 5 printing leading zeroes. See the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.util.Locale,%20java.lang.String,%20java.lang.Object...)\" rel=\"nofollow noreferrer\">java docs</a> for <code>String.format</code> for more information on the conversion specifiers.</p>\n"
},
{
"answer_id": 275799,
"author": "Elijah",
"author_id": 33611,
"author_profile": "https://Stackoverflow.com/users/33611",
"pm_score": 5,
"selected": false,
"text": "<p>Another option is to use <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat</a> to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:</p>\n\n<pre><code>static String intToString(int num, int digits) {\n assert digits > 0 : \"Invalid number of digits\";\n\n // create variable length array of zeros\n char[] zeros = new char[digits];\n Arrays.fill(zeros, '0');\n // format number as String\n DecimalFormat df = new DecimalFormat(String.valueOf(zeros));\n\n return df.format(num);\n}\n</code></pre>\n"
},
{
"answer_id": 3758787,
"author": "Madhu Subramanian",
"author_id": 453694,
"author_profile": "https://Stackoverflow.com/users/453694",
"pm_score": -1,
"selected": false,
"text": "<p>In case of your jdk version less than 1.5, following option can be used.</p>\n\n<pre><code> int iTest = 2;\n StringBuffer sTest = new StringBuffer(\"000000\"); //if the string size is 6\n sTest.append(String.valueOf(iTest));\n System.out.println(sTest.substring(sTest.length()-6, sTest.length()));\n</code></pre>\n"
},
{
"answer_id": 5427138,
"author": "Torin Rudeen",
"author_id": 675942,
"author_profile": "https://Stackoverflow.com/users/675942",
"pm_score": 3,
"selected": false,
"text": "<p>How about just:</p>\n\n<pre><code>public static String intToString(int num, int digits) {\n String output = Integer.toString(num);\n while (output.length() < digits) output = \"0\" + output;\n return output;\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34910/"
] |
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
```
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
```
|
String.format (<https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax>)
In your case it will be:
```
String formatted = String.format("%03d", num);
```
* 0 - to pad with zeros
* 3 - to set width to 3
|
275,717 |
<p>I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:</p>
<pre>
1) read a byte from the serial port
2) store each char into tagBuffer as they are read
3) run a query using tagBuffer to see what type of tag it is (book or shelf tag)
4) depending on the type of tag, output a series of bytes corresponding to the type of tag
</pre>
<p>Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.</p>
<p>The lines are the two lines at the very bottom:
<code></p>
<pre><code> sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
</code></pre>
<p></code></p>
<p>If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().</p>
<p>I thought sprintf and WriteFile are I/O functions and would have no effect on variables.
I'm stuck and I need help to fix this.</p>
<p><code></p>
<pre><code>//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= PACKET_LENGTH )
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if( str == "book" )
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
</code></pre>
<p></code></p>
<p>With those two lines, my output looks like this:
s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001</p>
<p>Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.</p>
<p>Any help at all will be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 275723,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>Where are you allocating tagbuffer, how large is it?<br>\nIt's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.</p>\n"
},
{
"answer_id": 275725,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>It seems unlikely that those two lines would have that effect on a correct program - maybe you haven't allocated sufficient space in <code>buf</code> for the whole length of the string in <code>tagBuffer</code>? This might cause a buffer overrun that is disguising the real problem?</p>\n"
},
{
"answer_id": 275732,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 1,
"selected": false,
"text": "<p>The first thing I'd say is a piece of general advice: bugs aren't always where you think they are. If you've got something going on that doesn't seem to make sense, it often means that your assumptions somewhere else are wrong.</p>\n\n<p>Here, it does seem very unlikely that an sprintf() and a WriteFile() will change the state of the \"buf\" array variable. However, those two lines of test code do write to \"hSerial\", while your main loop also reads from \"hSerial\". That sounds like a recipie for changing the behaviour of your program.</p>\n\n<p>Suggestion: Change your lines of debugging output to store the output somewhere else: to a dialog box, or to a log file, or similar. Debugging output should generally not go to files used in the core logic, as that's too likely to change how the core logic behaves.</p>\n"
},
{
"answer_id": 275864,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 0,
"selected": false,
"text": "<p>In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:</p>\n\n<ul>\n<li><a href=\"http://www.flounder.com/serial.htm\" rel=\"nofollow noreferrer\">Serial Port I/O</a> from Joseph Newcomer's website.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms810467.aspx\" rel=\"nofollow noreferrer\">Serial Communications in Win32</a> from MSDN.</li>\n</ul>\n\n<p>In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.</p>\n\n<p>This may sound more complex than your current design, but really it isn't, as Newcomer explains.</p>\n\n<p>I hope this helps!</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:
```
1) read a byte from the serial port
2) store each char into tagBuffer as they are read
3) run a query using tagBuffer to see what type of tag it is (book or shelf tag)
4) depending on the type of tag, output a series of bytes corresponding to the type of tag
```
Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.
The lines are the two lines at the very bottom:
```
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
```
If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().
I thought sprintf and WriteFile are I/O functions and would have no effect on variables.
I'm stuck and I need help to fix this.
```
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= PACKET_LENGTH )
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if( str == "book" )
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
```
With those two lines, my output looks like this:
s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001
Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.
Any help at all will be greatly appreciated. Thanks.
|
Where are you allocating tagbuffer, how large is it?
It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.
|
275,736 |
<p>I use the dark-blue2 color theme but it seems ugly under console.
So I want to use no color theme under terminal, what can I do then?</p>
|
[
{
"answer_id": 275755,
"author": "Samuel Tardieu",
"author_id": 22890,
"author_profile": "https://Stackoverflow.com/users/22890",
"pm_score": 2,
"selected": true,
"text": "<p>Set a \"TERM\" variable corresponding to a monochrome terminal before launching Emacs. For example, if you are in an xterm, use:</p>\n\n<pre><code>TERM=xterm-mono emacs -nw\n</code></pre>\n\n<p>If by \"console\" you mean the Linux console in text mode, you can try using \"vt100\" (or \"vt320\") instead.</p>\n"
},
{
"answer_id": 275812,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 1,
"selected": false,
"text": "<p>I use this, which works well because I use the <a href=\"http://www.emacswiki.org/emacs/MultiTTYSupport\" rel=\"nofollow noreferrer\">multi-tty</a> stuff from Emacs CVS (the future 23):</p>\n\n<pre>\n(defun mrc-xwin-look (frame)\n \"Setup to use if running in an X window\"\n (color-theme-deep-blue))\n\n(defun mrc-terminal-look (frame)\n \"Setup to use if running in a terminal\"\n (color-theme-charcoal-black))\n\n(defun mrc-setup-frame (frame)\n (set-variable 'color-theme-is-global nil)\n (select-frame frame)\n (cond\n ((window-system)\n (mrc-xwin-look frame)\n (tool-bar-mode -1)\n (mrc-maximize-frame))\n (t (mrc-terminal-look frame))))\n\n(add-hook 'after-make-frame-functions 'mrc-setup-frame)\n\n(add-hook 'after-init-hook\n (lambda ()\n (mrc-setup-frame (selected-frame))))\n</pre>\n\n<p>It picks a different color theme depending on whether the frame is running in a console or an X window. (I don't want to lose color syntax highlighting in a console.)</p>\n\n<p>By the way, maximize looks like this:</p>\n\n<pre>\n(defun mrc-maximize-frame ()\n \"Toggle frame maximized state\"\n ;; from http://paste.lisp.org/display/54627/raw\n (interactive)\n (cond\n ((eq 'x (window-system))\n (progn\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_HORZ\" 0))\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_VERT\" 0))))\n (t\n (message \"Window system %s is not supported by maximize\"\n (symbol-name (window-system))))))\n</pre>\n"
},
{
"answer_id": 276586,
"author": "quodlibetor",
"author_id": 25616,
"author_profile": "https://Stackoverflow.com/users/25616",
"pm_score": 4,
"selected": false,
"text": "<p>To be slightly shorter than those guys, the variable <strong><code>window-system</code></strong> is <em><code>something</code></em> if you're in a window-system, and <code>nil</code> if you're in a terminal, So if i wanted to load color-theme-darkblue2 i would have:</p>\n\n<pre><code>(if window-system\n (progn\n (load \"color-theme\")\n (color-theme-darkblue2)))\n</code></pre>\n\n<p>and it will just use the default colors in the terminal. Of course, you could obviously load a term-friendly theme in the else-part if you wanted to:</p>\n\n<pre><code>(load \"color-theme\")\n(if window-system\n (color-theme-darkblue2)\n (some-term-theme)))\n</code></pre>\n"
},
{
"answer_id": 25536380,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another simple one I use:</p>\n\n<pre><code>(when window-system\n (load-theme '<myThemeName>))\n</code></pre>\n\n<p>So this will load the theme in all cases where window-system is not nil, which is basically any kind of gui. </p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34924/"
] |
I use the dark-blue2 color theme but it seems ugly under console.
So I want to use no color theme under terminal, what can I do then?
|
Set a "TERM" variable corresponding to a monochrome terminal before launching Emacs. For example, if you are in an xterm, use:
```
TERM=xterm-mono emacs -nw
```
If by "console" you mean the Linux console in text mode, you can try using "vt100" (or "vt320") instead.
|
275,737 |
<pre><code>DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008 10:45:30',?)
SELECT *
FROM table1
WHERE column_datetime = @p_date
</code></pre>
<p>I need to compare date time like:</p>
<pre><code>@p_date=14 AUG 2008 10:45:30
column_datetime=14 AUG 2008 10:45:30
</code></pre>
<p>How can I do this?</p>
|
[
{
"answer_id": 275766,
"author": "Kaniu",
"author_id": 3236,
"author_profile": "https://Stackoverflow.com/users/3236",
"pm_score": 0,
"selected": false,
"text": "<p>I don't quite understand your problem, but <a href=\"http://msdn.microsoft.com/en-us/library/ms189794.aspx\" rel=\"nofollow noreferrer\">DateDiff</a> can be used to compare dates.</p>\n"
},
{
"answer_id": 275776,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>The question is unclear, but it looks like you are trying to do the equality match that isn't returning the rows you expect, so I'm guessing that the problem is that the milliseconds are being problematic. There are several approaches here:</p>\n\n<ol>\n<li>format both values (as varchar\netc) using CONVERT : expensive for\nCPU, can't use index </li>\n<li>use DATEDIFF/DATEPART to do the\nmath - similar, but not <em>quite</em> as\nexpensive</li>\n<li>create a range to search between</li>\n</ol>\n\n<p>The 3rd option is almost always the most efficient, since it can make good use of indexing, and doesn't require masses of CPU.</p>\n\n<p>For example, in the above, since your precision is seconds*, I would use:</p>\n\n<pre><code>DECLARE @end datetime\nSET @end = DATEADD(ss,1,@p_date)\n</code></pre>\n\n<p>then add a WHERE of the form:</p>\n\n<pre><code>WHERE column_datetime >= @p_date AND column_datetime < @end\n</code></pre>\n\n<p>This will work best if you have a clustered index on column_datetime, but should still work OK if you have a non-clustered index on column_datetime.</p>\n\n<p>[*=if @p_date includes milliseconds you'd need to think more about whether to trim those ms via <code>DATEADD</code>, or do a smaller range, etc]</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008 10:45:30',?)
SELECT *
FROM table1
WHERE column_datetime = @p_date
```
I need to compare date time like:
```
@p_date=14 AUG 2008 10:45:30
column_datetime=14 AUG 2008 10:45:30
```
How can I do this?
|
The question is unclear, but it looks like you are trying to do the equality match that isn't returning the rows you expect, so I'm guessing that the problem is that the milliseconds are being problematic. There are several approaches here:
1. format both values (as varchar
etc) using CONVERT : expensive for
CPU, can't use index
2. use DATEDIFF/DATEPART to do the
math - similar, but not *quite* as
expensive
3. create a range to search between
The 3rd option is almost always the most efficient, since it can make good use of indexing, and doesn't require masses of CPU.
For example, in the above, since your precision is seconds\*, I would use:
```
DECLARE @end datetime
SET @end = DATEADD(ss,1,@p_date)
```
then add a WHERE of the form:
```
WHERE column_datetime >= @p_date AND column_datetime < @end
```
This will work best if you have a clustered index on column\_datetime, but should still work OK if you have a non-clustered index on column\_datetime.
[\*=if @p\_date includes milliseconds you'd need to think more about whether to trim those ms via `DATEADD`, or do a smaller range, etc]
|
275,761 |
<p>I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.</p>
<p>How can I do it?</p>
<hr />
<p>When I click the submit button for the textbox below, the message box must show <em>Lorem ipsum</em>. Because "Lorem ipsum" is selected in the area.</p>
<hr />
<p>If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.</p>
<p>Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.</p>
<p>How is it to be done?</p>
|
[
{
"answer_id": 275797,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<p>For Opera, Firefox and Safari, you can use the following function:</p>\n\n<pre><code>function getTextFieldSelection(textField) {\n return textField.value.substring(textField.selectionStart, textField.selectionEnd);\n}\n</code></pre>\n\n<p>Then, you just pass a reference to a text field element (like a textarea or input element) to the function:</p>\n\n<pre><code>alert(getTextFieldSelection(document.getElementsByTagName(\"textarea\")[0]));\n</code></pre>\n\n<p>Or, if you want <textarea> and <input> to have a getSelection() function of their own:</p>\n\n<pre><code>HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {\n var ss = this.selectionStart;\n var se = this.selectionEnd;\n if (typeof ss === \"number\" && typeof se === \"number\") {\n return this.value.substring(this.selectionStart, this.selectionEnd);\n }\n return \"\";\n};\n</code></pre>\n\n<p>Then, you'd just do:</p>\n\n<pre><code>alert(document.getElementsByTagName(\"textarea\")[0].getSelection());\nalert(document.getElementsByTagName(\"input\")[0].getSelection());\n</code></pre>\n\n<p>for example.</p>\n"
},
{
"answer_id": 275825,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": true,
"text": "<p>OK, here is the code I have:</p>\n<pre><code>function ShowSelection()\n{\n var textComponent = document.getElementById('Editor');\n var selectedText;\n\n if (textComponent.selectionStart !== undefined)\n { // Standards-compliant version\n var startPos = textComponent.selectionStart;\n var endPos = textComponent.selectionEnd;\n selectedText = textComponent.value.substring(startPos, endPos);\n }\n else if (document.selection !== undefined)\n { // Internet Explorer version\n textComponent.focus();\n var sel = document.selection.createRange();\n selectedText = sel.text;\n }\n\n alert("You selected: " + selectedText);\n}\n</code></pre>\n<p>The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_6\" rel=\"nofollow noreferrer\">Internet Explorer 6</a> on my current system. Perhaps it will work for you, and that's why I give it.</p>\n<p>The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.</p>\n<p>I got the right result (the selection content) with the <em>onKeyDown</em> event:</p>\n<pre><code>document.onkeydown = function (e) { ShowSelection(); }\n</code></pre>\n<p>So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.</p>\n<p>I didn't have any success with a button drawn with a <code>li</code> tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple <code>input</code> button, though...</p>\n"
},
{
"answer_id": 22434042,
"author": "prat3ik-patel",
"author_id": 3340034,
"author_profile": "https://Stackoverflow.com/users/3340034",
"pm_score": 2,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function disp() {\r\n var text = document.getElementById(\"text\");\r\n var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);\r\n alert(t);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><TEXTAREA id=\"text\">Hello, How are You?</TEXTAREA><BR>\r\n<INPUT type=\"button\" onclick=\"disp()\" value=\"Select text and click here\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 24025245,
"author": "fishjd",
"author_id": 321747,
"author_profile": "https://Stackoverflow.com/users/321747",
"pm_score": 1,
"selected": false,
"text": "<p>I am a <em>big fan</em> of <a href=\"https://github.com/dwieeb/jquery-textrange\" rel=\"nofollow noreferrer\">jQuery-textrange</a>.</p>\n<p>Below is a very small, self-contained, example. Download <em>jquery-textrange.js</em> and copy it to the same folder.</p>\n<pre><code><!doctype html>\n<html>\n\n<head>\n <meta charset="UTF-8">\n <title>jquery-textrange</title>\n <script src="http://code.jquery.com/jquery-latest.min.js"></script>\n <script src="jquery-textrange.js"></script>\n\n <script>\n /* Run on document load */\n $(document).ready(function() {\n /* Run on any change of 'textarea' **/\n $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {\n\n /* The magic is on this line **/\n var range = $(this).textrange();\n\n /* Stuff into selectedId. I wanted to\n store this is a input field so it\n can be submitted in a form. */\n $('#selectedId').val(range.text);\n });\n });\n </script>\n</head>\n\n<body>\n The smallest example possible using\n <a href="https://github.com/dwieeb/jquery-textrange">\n jquery-textrange\n </a><br/>\n <textarea id="textareaId">Some random content.</textarea><br/>\n <input type="text" id="selectedId"></input>\n\n</body>\n\n</html>\n</code></pre>\n"
},
{
"answer_id": 32397146,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelector('textarea').addEventListener('mouseup', function () {\r\n window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)\r\n // window.getSelection().toString();\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><textarea>\r\n Select some text\r\n</textarea>\r\n<a href=\"#\" onclick=alert(mySelection);>Click here to display the selected text</a></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This works in all browsers.</p>\n\n<p>If you also want to handle selection via the keyboard, add another event listener for <code>keyup</code>, with the same code.</p>\n\n<p>If it weren't for this <a href=\"https://stackoverflow.com/questions/20419515/window-getselection-of-textarea-not-working-in-firefox#comment52700249_20419515\">Firefox bug filed back in 2001</a> (yes, 14 years ago), we could replace the value assigned to <code>window.mySelection</code> with <code>window.getSelection().toString()</code>, which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.</p>\n"
},
{
"answer_id": 61967743,
"author": "Optimaz ID",
"author_id": 5719038,
"author_profile": "https://Stackoverflow.com/users/5719038",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// jQuery\nvar textarea = $('#post-content');\nvar selectionStart = textarea.prop('selectionStart');\nvar selectionEnd = textarea.prop('selectionEnd');\nvar selection = (textarea.val()).substring(selectionStart, selectionEnd);\n\n// JavaScript\nvar textarea = document.getElementById("post-content");\nvar selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439507/"
] |
I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.
How can I do it?
---
When I click the submit button for the textbox below, the message box must show *Lorem ipsum*. Because "Lorem ipsum" is selected in the area.
---
If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.
Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.
How is it to be done?
|
OK, here is the code I have:
```
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
```
The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of [Internet Explorer 6](https://en.wikipedia.org/wiki/Internet_Explorer_6) on my current system. Perhaps it will work for you, and that's why I give it.
The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.
I got the right result (the selection content) with the *onKeyDown* event:
```
document.onkeydown = function (e) { ShowSelection(); }
```
So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.
I didn't have any success with a button drawn with a `li` tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple `input` button, though...
|
275,771 |
<p>I need to get the values in the registers with GCC.</p>
<p>Something similar to this:</p>
<pre>
EAX=00000002 EBX=00000001 ECX=00000005 EDX=BFFC94C0
ESI=8184C544 EDI=00000000 EBP=0063FF78 ESP=0063FE3C
CF=0 SF=0 ZF=0 OF=0
</pre>
<p>Getting the 32-bit registers is easy enough, but I'm not sure what the simplest way to get the flags is.</p>
<p>In the examples for this book: <a href="http://kipirvine.com/asm/" rel="nofollow noreferrer">http://kipirvine.com/asm/</a></p>
<p>They do it by getting the whole EFLAGS register and shifting for the bit in question. I also thought of doing it using Jcc's and CMOVcc's. </p>
<p>Any other suggestions on how to do it? Some test cases to verify would also be useful.</p>
|
[
{
"answer_id": 275775,
"author": "Marcos Lara",
"author_id": 30626,
"author_profile": "https://Stackoverflow.com/users/30626",
"pm_score": 0,
"selected": false,
"text": "<p>I think using Jcc's would be longer and not as clear using inline assembly.</p>\n\n<p>Here is what I currently have, using CMOVcc's:</p>\n\n<pre>\nvoid dump_regs()\n{\n int eax = 0;\n int ebx = 0;\n int ecx = 0;\n int edx = 0;\n\n int esi = 0;\n int edi = 0;\n int ebp = 0;\n int esp = 0;\n\n int cf = 0;\n int sf = 0;\n int zf = 0;\n int of = 0;\n\n int set = 1; // -52(%ebp)\n\n asm( \n \"movl %eax, -4(%ebp)\\n\\t\"\n \"movl %ebx, -8(%ebp)\\n\\t\"\n \"movl %ecx, -12(%ebp)\\n\\t\"\n \"movl %edx, -16(%ebp)\\n\\t\"\n \"movl %esi, -20(%ebp)\\n\\t\"\n \"movl %edi, -24(%ebp)\\n\\t\"\n \"movl %ebp, -28(%ebp)\\n\\t\"\n \"movl %esp, -32(%ebp)\\n\\t\"\n\n \"movl $0, %eax\\n\\t\"\n \"cmovb -52(%ebp),%eax\\n\\t\" // mov if CF = 1\n \"movl %eax, -36(%ebp) \\n\\t\" // cf\n\n \"movl $0, %eax\\n\\t\"\n \"cmovs -52(%ebp),%eax\\n\\t\" // mov if SF = 1\n \"movl %eax, -40(%ebp)\\n\\t\" // sf\n\n \"movl $0, %eax\\n\\t\"\n \"cmove -52(%ebp),%eax\\n\\t\" // mov if ZF = 1\n \"movl %eax, -44(%ebp)\\n\\t\" // zf\n\n \"movl $0, %eax\\n\\t\"\n \"cmovo -52(%ebp),%eax\\n\\t\" // mov if OF = 1\n \"movl %eax, -48(%ebp)\\n\\t\" // of\n\n \"movl -4(%ebp), %eax\\n\\t\" // restore EAX\n );\n\n printf(\"EAX = %#08x\\tEBX = %#08x\\tECX = %#08x\\tEDX = %#08x\\n\",eax,ebx,ecx,edx);\n printf(\"ESI = %#08x\\tEDI = %#08x\\tEBP = %#08x\\tESP = %#08x\\n\",esi,edi,ebp,esp);\n printf(\"CF = %d\\tSF = %d\\tZF = %d\\tOF = %d\\n\",cf,sf,zf,of);\n}\n</pre>\n\n<p>One important thing I haven't worked out yet are side-effects, I want to be able to call this without disturbing the state, any tips in that direction are welcome.</p>\n"
},
{
"answer_id": 275782,
"author": "Alon L",
"author_id": 30884,
"author_profile": "https://Stackoverflow.com/users/30884",
"pm_score": 0,
"selected": false,
"text": "<p>Of the top of my head, and correct me if I'm wrong, but you could just allocate some memory, get the address allocated, and simply write the register contents in there with an asm bracket...\nOr you could just push it into the stack and read it manually somehow...\nI guess it would take some good asm code and its probably not the ideal way to do something like that, but it'll work.</p>\n"
},
{
"answer_id": 275837,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 3,
"selected": true,
"text": "<p>There is no need to use assembler just to get the registers.</p>\n\n<p>You can just use setjmp. That will write all registers into a stucture of type jmp_buf. It even kind of Works cross platform except for the fact that jmp_buf itself is different for each architecture.</p>\n\n<p>However, calling setjmp (and calling your assembler code as well) will change some of the registers, so you can't really trust them.</p>\n\n<p>There is a way to get a real snapshot, but that's a bit more difficult and highly OS dependent: </p>\n\n<ol>\n<li><p>install an exception handler for the illegal illegal opcode extension. The handler can be either a real interrupt, a signal handler or a OS exception handler (the try/except blocks form C++ will not work). </p></li>\n<li><p>Emit an illegal opcode in your code.</p></li>\n</ol>\n\n<p>The trick here is, that the illegal opcode has no register side-effects. The exception handler can copy the registers either from the stack or from a exception info structure.</p>\n\n<p>The same trick may work with breakpoint interrupts forced overflows, traps or so. There is usually more than one way to raise an interrupt from a piece of code.</p>\n\n<hr>\n\n<p>Regarding the EFLAGS: You can get them via a stack operation:</p>\n\n<pre><code> PUSHFD\n POP EAX \n , eax now contains the EFLAG data\n</code></pre>\n"
},
{
"answer_id": 275854,
"author": "plan9assembler",
"author_id": 1710672,
"author_profile": "https://Stackoverflow.com/users/1710672",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO, using gdb is better than gcc.</p>\n\n<p><a href=\"http://www.unknownroad.com/rtfm/gdbtut/gdbadvanced.html\" rel=\"nofollow noreferrer\">http://www.unknownroad.com/rtfm/gdbtut/gdbadvanced.html</a></p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 6405090,
"author": "jww",
"author_id": 608639,
"author_profile": "https://Stackoverflow.com/users/608639",
"pm_score": 1,
"selected": false,
"text": "<p>The follow was tested for a 64-bit machine. If you have a 32-bit machine, remove the 64-bit gear, and change flag64 -> flag32 (and use <code>pushfd</code> instead of <code>pushfq</code>). In practice, I find I only need to inspect CY (carry) and OV (overflow) from the flags register (and I usually do it with <code>jc</code>, <code>jnc</code>, <code>jo</code>, and <code>jno</code>).</p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n\n#define HIGH32(x) ((uint32_t)(((uint64_t)x)>>32))\n#define LOW32(x) ((uint32_t)(((uint64_t)x)& 0xFFFFFFFF))\n\nint main(int argc, char** argv)\n{\n uint32_t eax32, ebx32, ecx32, edx32;\n uint64_t rax64, rbx64, rcx64, rdx64;\n\n asm (\n \"movl %%eax, %[a1] ;\"\n \"movl %%ebx, %[b1] ;\"\n \"movl %%ecx, %[c1] ;\"\n \"movl %%edx, %[d1] ;\"\n\n \"movq %%rax, %[a2] ;\"\n \"movq %%rbx, %[b2] ;\"\n \"movq %%rcx, %[c2] ;\"\n \"movq %%rdx, %[d2] ;\"\n :\n [a1] \"=m\" (eax32), [b1] \"=m\" (ebx32), [c1] \"=m\" (ecx32), [d1] \"=m\" (edx32), \n [a2] \"=m\" (rax64), [b2] \"=m\" (rbx64), [c2] \"=m\" (rcx64), [d2] \"=m\" (rdx64)\n );\n\n printf(\"eax=%08x\\n\", eax32);\n printf(\"ebx=%08x\\n\", ebx32);\n printf(\"ecx=%08x\\n\", ecx32);\n printf(\"edx=%08x\\n\", edx32);\n\n printf(\"rax=%08x%08x\\n\", HIGH32(rax64), LOW32(rax64));\n printf(\"bax=%08x%08x\\n\", HIGH32(rbx64), LOW32(rbx64));\n printf(\"cax=%08x%08x\\n\", HIGH32(rcx64), LOW32(rcx64));\n printf(\"dax=%08x%08x\\n\", HIGH32(rdx64), LOW32(rdx64));\n\n uint64_t flags;\n\n asm (\n \"pushfq ;\"\n \"pop %[f1] ;\"\n :\n [f1] \"=m\" (flags)\n );\n\n printf(\"flags=%08x%08x\", HIGH32(flags), LOW32(flags));\n\n if(flags & (1 << 0)) // Carry\n printf(\" (C1\"); \n else\n printf(\" (C0\");\n\n if(flags & (1 << 2)) // Parity\n printf(\" P1\");\n else\n printf(\" P0\");\n\n if(flags & (1 << 4)) // Adjust\n printf(\" A1\");\n else\n printf(\" A0\");\n\n if(flags & (1 << 6)) // Zero\n printf(\" Z1\");\n else\n printf(\" Z0\");\n\n if(flags & (1 << 7)) // Sign\n printf(\" S1\");\n else\n printf(\" S0\");\n\n if(flags & (1 << 11)) // Overflow\n printf(\" O1)\\n\");\n else\n printf(\" O0)\\n\");\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30626/"
] |
I need to get the values in the registers with GCC.
Something similar to this:
```
EAX=00000002 EBX=00000001 ECX=00000005 EDX=BFFC94C0
ESI=8184C544 EDI=00000000 EBP=0063FF78 ESP=0063FE3C
CF=0 SF=0 ZF=0 OF=0
```
Getting the 32-bit registers is easy enough, but I'm not sure what the simplest way to get the flags is.
In the examples for this book: <http://kipirvine.com/asm/>
They do it by getting the whole EFLAGS register and shifting for the bit in question. I also thought of doing it using Jcc's and CMOVcc's.
Any other suggestions on how to do it? Some test cases to verify would also be useful.
|
There is no need to use assembler just to get the registers.
You can just use setjmp. That will write all registers into a stucture of type jmp\_buf. It even kind of Works cross platform except for the fact that jmp\_buf itself is different for each architecture.
However, calling setjmp (and calling your assembler code as well) will change some of the registers, so you can't really trust them.
There is a way to get a real snapshot, but that's a bit more difficult and highly OS dependent:
1. install an exception handler for the illegal illegal opcode extension. The handler can be either a real interrupt, a signal handler or a OS exception handler (the try/except blocks form C++ will not work).
2. Emit an illegal opcode in your code.
The trick here is, that the illegal opcode has no register side-effects. The exception handler can copy the registers either from the stack or from a exception info structure.
The same trick may work with breakpoint interrupts forced overflows, traps or so. There is usually more than one way to raise an interrupt from a piece of code.
---
Regarding the EFLAGS: You can get them via a stack operation:
```
PUSHFD
POP EAX
, eax now contains the EFLAG data
```
|
275,778 |
<p>How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change.
Thanks </p>
|
[
{
"answer_id": 275783,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>To my knowledge, no, unless there is a trick with transparent overlays.</p>\n\n<p>Most graphical applications I saw (and did) just re-draw the whole panel on each repaint. Now, you can do that once, in a graphic buffer, and then just paint the whole background at once, quickly, by copying the graphic buffer to the JPanel. It should be faster than calling all graphical primitives to draw the road.</p>\n\n<p>Or, the way some 2D games do, perhaps paint it once and update the moving parts, like sprites: it needs to erase the old place used by the sprites (restore the background there) and re-draw the sprites at the new place. So you still have a copy of the road in a graphic buffer but instead of re-drawing it whole each time, you update only some small parts. Can be slightly faster.</p>\n"
},
{
"answer_id": 275785,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure you actually want your road to never be repainted - repaint events fire (for example) when your window is resized, or when it becomes visible following another window obstructing it. If your panel never repaints then it'll look peculiar.</p>\n\n<p>As far as I remember, Swing will only fire appropriate paint events for these circumstances, so you should be OK following the usual method of subclassing JPanel with a suitable override:</p>\n\n<pre><code>public class RoadPanel extends JPanel {\n\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n // your drawing code here\n }\n}\n</code></pre>\n\n<p>If you cache your road into an image or another graphics format (to save calculating the display data multiple times) once drawn once, this might save you some time on subsequent paints.</p>\n"
},
{
"answer_id": 275999,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 1,
"selected": false,
"text": "<p>What I do is set a boolean value to whether or not a certain part needs to be redrawn. Then, in the <code>paintComponent()</code> method I can check the value and redraw the certain thing, or not.</p>\n\n<pre><code>protected void paintComponent(Graphics g){\n super.paintComponent(g);\n if (drawRoad) {\n drawRoadMethod(g);\n }\n drawTheRest(g);\n}\n</code></pre>\n\n<p>Kinda like that.</p>\n"
},
{
"answer_id": 276067,
"author": "Ben Page",
"author_id": 29924,
"author_profile": "https://Stackoverflow.com/users/29924",
"pm_score": 2,
"selected": false,
"text": "<p>The component will need to be repainted every time that the panel is obscured (ie frame minimized/another window put on top). Therefore drawing something only once will not work as you want it to. To make parts that do not change be drawn more efficiently you can draw them once to a 'buffer' image, and then just draw this buffer each time that the panel or component needs to be redrawn.</p>\n\n<pre><code>// Field that stores the image so it is always accessible\nprivate Image roadImage = null;\n// ...\n// ...\n// Override paintComponent Method\npublic void paintComponent(Graphics g){\n\n if (roadImage == null) {\n // Create the road image if it doesn't exist\n roadImage = createImage(width, height);\n // draw the roads to the image\n Graphics roadG = roadImage.getGraphics();\n // Use roadG like you would any other graphics\n // object to draw the roads to an image\n } else {\n // If the buffer image exists, you just need to draw it.\n // Draw the road buffer image\n g.drawImage(roadImage, 0, 0, null);\n }\n // Draw everything else ...\n // g.draw...\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4885/"
] |
How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change.
Thanks
|
I'm not sure you actually want your road to never be repainted - repaint events fire (for example) when your window is resized, or when it becomes visible following another window obstructing it. If your panel never repaints then it'll look peculiar.
As far as I remember, Swing will only fire appropriate paint events for these circumstances, so you should be OK following the usual method of subclassing JPanel with a suitable override:
```
public class RoadPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// your drawing code here
}
}
```
If you cache your road into an image or another graphics format (to save calculating the display data multiple times) once drawn once, this might save you some time on subsequent paints.
|
275,781 |
<p>Can anyone explain the difference between <code>Server.MapPath(".")</code>, <code>Server.MapPath("~")</code>, <code>Server.MapPath(@"\")</code> and <code>Server.MapPath("/")</code>?</p>
|
[
{
"answer_id": 275791,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 11,
"selected": true,
"text": "<p><strong>Server.MapPath</strong> specifies the relative or virtual path to map <strong>to a physical directory</strong>.</p>\n\n<ul>\n<li><code>Server.MapPath(\".\")</code><sup>1</sup> returns the current physical directory of the file (e.g. aspx) being executed</li>\n<li><code>Server.MapPath(\"..\")</code> returns the parent directory</li>\n<li><code>Server.MapPath(\"~\")</code> returns the physical path to the root of the application</li>\n<li><code>Server.MapPath(\"/\")</code> returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)</li>\n</ul>\n\n<p><em>An example:</em></p>\n\n<p>Let's say you pointed a web site application (<code>http://www.example.com/</code>) to</p>\n\n<pre><code>C:\\Inetpub\\wwwroot\n</code></pre>\n\n<p>and installed your shop application (sub web as virtual directory in IIS, marked as application) in </p>\n\n<pre><code>D:\\WebApps\\shop\n</code></pre>\n\n<p>For example, if you call <code>Server.MapPath()</code> in following request:</p>\n\n<pre><code>http://www.example.com/shop/products/GetProduct.aspx?id=2342\n</code></pre>\n\n<p>then:</p>\n\n<ul>\n<li><code>Server.MapPath(\".\")</code><sup>1</sup> returns <code>D:\\WebApps\\shop\\products</code></li>\n<li><code>Server.MapPath(\"..\")</code> returns <code>D:\\WebApps\\shop</code></li>\n<li><code>Server.MapPath(\"~\")</code> returns <code>D:\\WebApps\\shop</code></li>\n<li><code>Server.MapPath(\"/\")</code> returns <code>C:\\Inetpub\\wwwroot</code></li>\n<li><code>Server.MapPath(\"/shop\")</code> returns <code>D:\\WebApps\\shop</code></li>\n</ul>\n\n<p>If Path starts with either a forward slash (<code>/</code>) or backward slash (<code>\\</code>), the <code>MapPath()</code> returns a path as if Path was a full, virtual path. </p>\n\n<p>If Path doesn't start with a slash, the <code>MapPath()</code> returns a path relative to the directory of the request being processed.</p>\n\n<p><em>Note: in C#, <code>@</code> is the verbatim literal string operator meaning that the string should be used \"as is\" and not be processed for escape sequences.</em></p>\n\n<p><em>Footnotes</em></p>\n\n<ol>\n<li><code>Server.MapPath(null)</code> and <code>Server.MapPath(\"\")</code> will <a href=\"https://stackoverflow.com/a/17616488/1185053\">produce this effect too</a>.</li>\n</ol>\n"
},
{
"answer_id": 17616488,
"author": "dav_i",
"author_id": 1185053,
"author_profile": "https://Stackoverflow.com/users/1185053",
"pm_score": 5,
"selected": false,
"text": "<p>Just to expand on @splattne's answer a little:</p>\n\n<p><code>MapPath(string virtualPath)</code> calls the following:</p>\n\n<pre><code>public string MapPath(string virtualPath)\n{\n return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));\n}\n</code></pre>\n\n<p><code>MapPath(VirtualPath virtualPath)</code> in turn calls <code>MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping)</code> which contains the following:</p>\n\n<pre><code>//...\nif (virtualPath == null)\n{\n virtualPath = VirtualPath.Create(\".\");\n}\n//...\n</code></pre>\n\n<p>So if you call <code>MapPath(null)</code> or <code>MapPath(\"\")</code>, you are effectively calling <code>MapPath(\".\")</code></p>\n"
},
{
"answer_id": 48148734,
"author": "Vaibhav_Welcomes_You",
"author_id": 7845508,
"author_profile": "https://Stackoverflow.com/users/7845508",
"pm_score": 2,
"selected": false,
"text": "<p>1) <code>Server.MapPath(\".\")</code> -- Returns the \"Current Physical Directory\" of the file (e.g. <code>aspx</code>) being executed.</p>\n\n<p>Ex. Suppose <code>D:\\WebApplications\\Collage\\Departments</code></p>\n\n<p>2) <code>Server.MapPath(\"..\")</code> -- Returns the \"Parent Directory\"</p>\n\n<p>Ex. <code>D:\\WebApplications\\Collage</code></p>\n\n<p>3) <code>Server.MapPath(\"~\")</code> -- Returns the \"Physical Path to the Root of the Application\"</p>\n\n<p>Ex. <code>D:\\WebApplications\\Collage</code></p>\n\n<p>4) <code>Server.MapPath(\"/\")</code> -- Returns the physical path to the root of the Domain Name </p>\n\n<p>Ex. <code>C:\\Inetpub\\wwwroot</code></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
] |
Can anyone explain the difference between `Server.MapPath(".")`, `Server.MapPath("~")`, `Server.MapPath(@"\")` and `Server.MapPath("/")`?
|
**Server.MapPath** specifies the relative or virtual path to map **to a physical directory**.
* `Server.MapPath(".")`1 returns the current physical directory of the file (e.g. aspx) being executed
* `Server.MapPath("..")` returns the parent directory
* `Server.MapPath("~")` returns the physical path to the root of the application
* `Server.MapPath("/")` returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
*An example:*
Let's say you pointed a web site application (`http://www.example.com/`) to
```
C:\Inetpub\wwwroot
```
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
```
D:\WebApps\shop
```
For example, if you call `Server.MapPath()` in following request:
```
http://www.example.com/shop/products/GetProduct.aspx?id=2342
```
then:
* `Server.MapPath(".")`1 returns `D:\WebApps\shop\products`
* `Server.MapPath("..")` returns `D:\WebApps\shop`
* `Server.MapPath("~")` returns `D:\WebApps\shop`
* `Server.MapPath("/")` returns `C:\Inetpub\wwwroot`
* `Server.MapPath("/shop")` returns `D:\WebApps\shop`
If Path starts with either a forward slash (`/`) or backward slash (`\`), the `MapPath()` returns a path as if Path was a full, virtual path.
If Path doesn't start with a slash, the `MapPath()` returns a path relative to the directory of the request being processed.
*Note: in C#, `@` is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.*
*Footnotes*
1. `Server.MapPath(null)` and `Server.MapPath("")` will [produce this effect too](https://stackoverflow.com/a/17616488/1185053).
|
275,795 |
<p>E.g.</p>
<p>What's best out of these:</p>
<pre><code>std::string f() {}
</code></pre>
<p>or </p>
<pre><code>const std::string& f() {}
</code></pre>
|
[
{
"answer_id": 275802,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": false,
"text": "<p>If you return a reference to a variable that is local to the function then you're going to end up with issues (depending on the compiler and its settings).</p>\n\n<p>If you return a reference to an instance that's still in scope when the function returns then it will be faster, as no copy of the string is being created.</p>\n\n<p>So the latter is more efficient (technically) but may not function as expected depending on what you return a reference to.</p>\n"
},
{
"answer_id": 275811,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 5,
"selected": false,
"text": "<p>A function <strong>should never return</strong> a reference to a local object/variable since such objects go out of the scope and get destroyed when the function returns. </p>\n\n<p>Differently, the function can return a const or non const reference to an object whose scope is not limited by the function context. Typical example is a custom <code>operator<<</code>:</p>\n\n<pre><code>std::ostream & operator<<(std::ostream &out, const object &obj)\n{\n out << obj.data();\n return out;\n}\n</code></pre>\n\n<p>Unfortunately, returning-by-value has its performance drawback. As Chris mentioned, returning an object by value involves the copy of a temporary object and its subsequent destruction. The copy takes place by means of either copy constructor or <code>operator=</code>. To avoid these inefficiencies, smart compilers may apply the RVO or the NRVO optimizations, but there are cases in which they can't -- multiple returns.</p>\n\n<p>The upcoming C++0x standard, partially available in gnu gcc-4.3, introduces the rvalue reference [&&] that can be used to distinguish a lvalue from a rvalue reference. By means of that, it's possible to implement the <strong>move constructor</strong>, useful to return an object partially avoiding the cost of copy constructor and the destructor of the temporary.</p>\n\n<p>The move constructor is basically what Andrei envisioned some years ago in the article <a href=\"http://www.ddj.com/database/184403855\" rel=\"nofollow noreferrer\">http://www.ddj.com/database/184403855</a> suggested by Chris.</p>\n\n<p>A <em>move constructor</em> has the following signature:</p>\n\n<pre><code>// move constructor\nobject(object && obj)\n{}\n</code></pre>\n\n<p>and it's supposed to take the ownership of the internals of the passed object leaving the latter in a default state. By doing that, copies of internals are avoided and the destruction of the temporary made easy. A typical function factory will then have the following form:</p>\n\n<pre><code>object factory()\n{\n object obj;\n return std::move(obj);\n}\n</code></pre>\n\n<p>The <code>std::move()</code> returns a rvalue reference from an object. Last but not least, move constructors allow the return-by-rvalue-reference of non-copyable objects.</p>\n"
},
{
"answer_id": 275819,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>I would like to add to Nicola's excellent answer. Yes, you must never return a dangling reference (e.g., reference to a local variable), however, there are three useful ways to improve performance in those cases:</p>\n\n<ol>\n<li><p>Return-value optimisation (RVO): You return by value, but eliminate copying by having only one <code>return</code> statement, which creates the return value on the spot. Here's an example of RVO being used: <a href=\"https://stackoverflow.com/questions/275733/c-string#275747\">How can I tokenize a C++ string?</a></p></li>\n<li><p>Named return-value optimisation (NRVO): You return by value, and declare the return value variable first, at the top of the function. All <code>return</code> statements return that variable. With compilers that support NRVO, that variable is allocated in the return-value slot, and does not get copied upon return. e.g.,</p>\n\n<pre><code>string\nfoobar()\n{\n string result;\n // fill in \"result\"\n return result;\n}\n</code></pre></li>\n<li><p>Use a <code>shared_ptr</code> or the like as the return type; this necessitates creating your object on the heap, rather than the stack. This prevents dangling-reference problems while still not requiring the whole object to be copied, just the smart pointer.</p></li>\n</ol>\n\n<p>By the way, I can't take credit for the information about RVO and NRVO; they come straight out of Scott Meyers's <a href=\"http://www.informit.com/store/product.aspx?isbn=020163371X\" rel=\"noreferrer\">More Effective C++</a>. Since I don't have the book with me at the moment, any errors in my description are my doing, not Scott's. :-)</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
E.g.
What's best out of these:
```
std::string f() {}
```
or
```
const std::string& f() {}
```
|
A function **should never return** a reference to a local object/variable since such objects go out of the scope and get destroyed when the function returns.
Differently, the function can return a const or non const reference to an object whose scope is not limited by the function context. Typical example is a custom `operator<<`:
```
std::ostream & operator<<(std::ostream &out, const object &obj)
{
out << obj.data();
return out;
}
```
Unfortunately, returning-by-value has its performance drawback. As Chris mentioned, returning an object by value involves the copy of a temporary object and its subsequent destruction. The copy takes place by means of either copy constructor or `operator=`. To avoid these inefficiencies, smart compilers may apply the RVO or the NRVO optimizations, but there are cases in which they can't -- multiple returns.
The upcoming C++0x standard, partially available in gnu gcc-4.3, introduces the rvalue reference [&&] that can be used to distinguish a lvalue from a rvalue reference. By means of that, it's possible to implement the **move constructor**, useful to return an object partially avoiding the cost of copy constructor and the destructor of the temporary.
The move constructor is basically what Andrei envisioned some years ago in the article <http://www.ddj.com/database/184403855> suggested by Chris.
A *move constructor* has the following signature:
```
// move constructor
object(object && obj)
{}
```
and it's supposed to take the ownership of the internals of the passed object leaving the latter in a default state. By doing that, copies of internals are avoided and the destruction of the temporary made easy. A typical function factory will then have the following form:
```
object factory()
{
object obj;
return std::move(obj);
}
```
The `std::move()` returns a rvalue reference from an object. Last but not least, move constructors allow the return-by-rvalue-reference of non-copyable objects.
|
275,810 |
<p>Is anyone using Castle MonoRail and ELMAH with success?</p>
<p>We are using a number of Resuces to present users with friendly error messages, but if we do this the exceptions never get as far as ELMAH as the MonoRail rescue intercepts them.</p>
<p>Ideally we want the user to see the rescue, but for the exception to be logged in ELMAH.</p>
<p>Any ideas/pointers?</p>
<p>Cheers,</p>
<p>Jay.</p>
|
[
{
"answer_id": 277626,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 2,
"selected": false,
"text": "<p>After also posting on <a href=\"http://groups.google.com/group/elmah/browse_thread/thread/c81280722a05602f\" rel=\"nofollow noreferrer\">Google Groups</a> it looks like Atif may have pointed me in the right direction.</p>\n\n<blockquote>\n <p>You might want to look into error\n signaling in ELMAH. It is designed for\n scenarios where you want to pass an\n exception through ELMAH's pipeline\n even if it is being handled/swallowed.\n Here are some pointers to get started\n with error signaling:</p>\n \n <ul>\n <li><a href=\"http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signaling\" rel=\"nofollow noreferrer\">http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signa...</a></li>\n <li><a href=\"http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Signaling_errors\" rel=\"nofollow noreferrer\">http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Signaling_e...</a></li>\n </ul>\n \n <p>-Atif</p>\n</blockquote>\n"
},
{
"answer_id": 620066,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 3,
"selected": true,
"text": "<p>After looking at the links Macka posted, I wrote this simple monorail exception handler:</p>\n\n<pre><code>public class ElmahExceptionHandler : AbstractExceptionHandler {\n public override void Process(IRailsEngineContext context) {\n ErrorSignal.FromCurrentContext().Raise(context.LastException);\n }\n}\n</code></pre>\n\n<p>Then I registered it in web.config, monorail section:</p>\n\n<pre><code><monorail>\n <extensions>\n <extension type=\"Castle.MonoRail.Framework.Extensions.ExceptionChaining.ExceptionChainingExtension, Castle.MonoRail.Framework\"/>\n </extensions>\n <exception>\n <exceptionHandler type=\"MyNamespace.ElmahExceptionHandler, MyAssembly\"/>\n </exception>\n...\n</monorail>\n</code></pre>\n\n<p>And that's it.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8542/"
] |
Is anyone using Castle MonoRail and ELMAH with success?
We are using a number of Resuces to present users with friendly error messages, but if we do this the exceptions never get as far as ELMAH as the MonoRail rescue intercepts them.
Ideally we want the user to see the rescue, but for the exception to be logged in ELMAH.
Any ideas/pointers?
Cheers,
Jay.
|
After looking at the links Macka posted, I wrote this simple monorail exception handler:
```
public class ElmahExceptionHandler : AbstractExceptionHandler {
public override void Process(IRailsEngineContext context) {
ErrorSignal.FromCurrentContext().Raise(context.LastException);
}
}
```
Then I registered it in web.config, monorail section:
```
<monorail>
<extensions>
<extension type="Castle.MonoRail.Framework.Extensions.ExceptionChaining.ExceptionChainingExtension, Castle.MonoRail.Framework"/>
</extensions>
<exception>
<exceptionHandler type="MyNamespace.ElmahExceptionHandler, MyAssembly"/>
</exception>
...
</monorail>
```
And that's it.
|
275,824 |
<p>I am getting an 'Access to the path is denied" error message when running in debug mode. I have tried granting permissions to {MACHINENAME}\ASPNET and to NETWORK SERVICE but this hasn't made any difference. I have also tried < impersonate = true /> using an admin account, this also made no difference. So how do I establish exactly which account is being used?</p>
|
[
{
"answer_id": 275830,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": true,
"text": "<p>To find out which NT account your app is running under at any given time, do something like (in VB.NET):</p>\n\n<pre><code> Dim User = System.Security.Principal.WindowsIdentity.GetCurrent.User\n Dim UserName = User.Translate(GetType(System.Security.Principal.NTAccount)).Value\n</code></pre>\n\n<p>When using ASP.NET, this account will match the identity of the application pool, which you configure using IIS Manager. Note that the anonymous IIS user isn't much involved with ASP.NET requests.</p>\n"
},
{
"answer_id": 275843,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "<p>You could use this code:</p>\n\n<p><strong>C#</strong></p>\n\n<pre><code>Response.Write(\"Windows Account which runs ASP.NET is: \" \n + Environment.Username);\n</code></pre>\n\n<p><strong>VB.NET</strong></p>\n\n<pre><code>Response.Write(\"Windows Account which runs ASP.NET is: \" _\n & Environment.Username)\n</code></pre>\n\n<p>If you run your application in Visual Studio on your PC (localhost) you'll get your user name. If you deploy ASP.NET web application on IIS, you will probably get the NETWORK SERVICE account, because that is default user running IIS 6.0 (ASPNET on Windows Server 2000's IIS 5.0).</p>\n\n<p><code>Environment.UserName</code> returns the thread's currently logged-on user. <code>Page.User</code> returns the name that ASP.NET verifies through Authentication and this user in most cases is independent of the Windows logon that is running the current thread. For anonymous requests Page.User is blank, while Environment.User will be NETWORK SERVICE.</p>\n\n<p><em>As <a href=\"https://stackoverflow.com/users/8562/mdb\">mdb</a> correctly points out in a comment to this answer, Environment.Username will simply return the USERNAME environment variable, which is set on process creation and not updated in case of impersonation and such.</em></p>\n"
},
{
"answer_id": 1095515,
"author": "Adam",
"author_id": 33503,
"author_profile": "https://Stackoverflow.com/users/33503",
"pm_score": 4,
"selected": false,
"text": "<p>C# Code for the vb.net answer</p>\n\n<pre><code>var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;\nvar userName = user.Translate(typeof (System.Security.Principal.NTAccount));\n</code></pre>\n"
},
{
"answer_id": 15383216,
"author": "manju",
"author_id": 2165011,
"author_profile": "https://Stackoverflow.com/users/2165011",
"pm_score": -1,
"selected": false,
"text": "<pre><code>strint t=System.Web.Security.Membership.GetUser().UserName.ToString();\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
I am getting an 'Access to the path is denied" error message when running in debug mode. I have tried granting permissions to {MACHINENAME}\ASPNET and to NETWORK SERVICE but this hasn't made any difference. I have also tried < impersonate = true /> using an admin account, this also made no difference. So how do I establish exactly which account is being used?
|
To find out which NT account your app is running under at any given time, do something like (in VB.NET):
```
Dim User = System.Security.Principal.WindowsIdentity.GetCurrent.User
Dim UserName = User.Translate(GetType(System.Security.Principal.NTAccount)).Value
```
When using ASP.NET, this account will match the identity of the application pool, which you configure using IIS Manager. Note that the anonymous IIS user isn't much involved with ASP.NET requests.
|
275,836 |
<p>I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?</p>
|
[
{
"answer_id": 275841,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": -1,
"selected": false,
"text": "<p>There is no native support for this; you will either have to use multiple labels or find a 3rd-party control that will provide this functionality.</p>\n"
},
{
"answer_id": 275845,
"author": "mrtaikandi",
"author_id": 34623,
"author_profile": "https://Stackoverflow.com/users/34623",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think so. You should create one yourself.</p>\n"
},
{
"answer_id": 275846,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 4,
"selected": false,
"text": "<p>You could try using a RichTextBox so that you can get multiple colors for the string and then make it read only and remove the border. Change the background color to the same as the Form it is on and you might get away with it.</p>\n"
},
{
"answer_id": 275847,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "<p>As an alternative, you might do this as rtf or html in a suitable control (such as WebBrowser). It would probably take a bit more resources that you'd ideally like, but it'll work fairly quickly.</p>\n"
},
{
"answer_id": 275870,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "<p>If you are building your Windows app for people with XP and up, you can use WPF. Even if it's a Windows Forms app, you can add a WPF UserControl.</p>\n\n<p>I would then use a Label, and set the \"Foreground\" property to be a gradient of colors.</p>\n\n<p>Or, in Windows Forms (no WPF), you could just use a \"Flow Panel\", and then in a for loop add multiple Labels as segments of your sentense... they will all \"flow\" together as if it was one label.</p>\n"
},
{
"answer_id": 275876,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 7,
"selected": true,
"text": "<p>There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). Normally you would have a custom label control inherit directly from Label, but since you can't get multi-colored text in one label, you would just inherit from UserControl.</p>\n\n<p>For rendering the text, your UserControl could split the text on commas and then dynamically load a differently-colored Label for each chunk. A better way, however, would be to render the text directly onto your UserControl using the DrawString and MeasureString methods in the Graphics namespace.</p>\n\n<p>Writing UserControls in .NET is really not difficult, and this kind of unusual problem is exactly what custom UserControls are for.</p>\n\n<p><strong>Update</strong>: here's a simple method you can use for rendering the multi-colored text on a PictureBox:</p>\n\n<pre><code>public void RenderRainbowText(string Text, PictureBox pb)\n{\n // PictureBox needs an image to draw on\n pb.Image = new Bitmap(pb.Width, pb.Height);\n using (Graphics g = Graphics.FromImage(pb.Image))\n {\n // create all-white background for drawing\n SolidBrush brush = new SolidBrush(Color.White);\n g.FillRectangle(brush, 0, 0,\n pb.Image.Width, pb.Image.Height);\n // draw comma-delimited elements in multiple colors\n string[] chunks = Text.Split(',');\n brush = new SolidBrush(Color.Black);\n SolidBrush[] brushes = new SolidBrush[] { \n new SolidBrush(Color.Red),\n new SolidBrush(Color.Green),\n new SolidBrush(Color.Blue),\n new SolidBrush(Color.Purple) };\n float x = 0;\n for (int i = 0; i < chunks.Length; i++)\n {\n // draw text in whatever color\n g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);\n // measure text and advance x\n x += (g.MeasureString(chunks[i], pb.Font)).Width;\n // draw the comma back in, in black\n if (i < (chunks.Length - 1))\n {\n g.DrawString(\",\", pb.Font, brush, x, 0);\n x += (g.MeasureString(\",\", pb.Font)).Width;\n }\n }\n }\n}\n</code></pre>\n\n<p>Obviously this will break if you have more than 4 comma-delimited elements in your text, but you get the idea. Also, there appears to be a small glitch in MeasureString that makes it return a width that is a couple pixels wider than necessary, so the multi-colored string appears stretched out - you might want to tweak that part.</p>\n\n<p>It should be straightforward to modify this code for a UserControl.</p>\n\n<p><strong>Note</strong>: TextRenderer is a better class to use for drawing and measuring strings, since it uses ints. Graphics.DrawString and .MeasureString use floats, so you'll get off-by-a-pixel errors here and there.</p>\n\n<p><strong>Update</strong>: <em>Forget</em> about using TextRenderer. It is dog slow.</p>\n"
},
{
"answer_id": 420796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>As per your Question your requirement is simple like\n<code>lable.Text = \"This color is Red\"</code>, So it have to display text like this \n\"The color is\" will be in Blue and \"Red\" will be red color ..\nThis can be done like this</p>\n\n<pre><code>lable.Text = \"<span style='Color:Blue'>\" + \" The color is \" +\"</span>\" + \"<span style='Color:Red'>\"Red\"</span>\"\n</code></pre>\n"
},
{
"answer_id": 1102748,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 1,
"selected": false,
"text": "<p>Slightly off topic ... You could check also: </p>\n\n<ul>\n<li><a href=\"http://ysgitdiary.blogspot.com/2009/07/how-to-generate-html-color-table-with.html\" rel=\"nofollow noreferrer\">generate html color table</a> </li>\n<li><a href=\"http://ysgitdiary.blogspot.com/2009/07/how-to-create-html-color-table-in-sql.html\" rel=\"nofollow noreferrer\">model colors in sql</a> </li>\n<li><a href=\"http://ysgitdiary.blogspot.com/2009/07/how-to-create-html-color-table-part-2.html\" rel=\"nofollow noreferrer\">the result</a> </li>\n</ul>\n"
},
{
"answer_id": 6415324,
"author": "Chris Wegener",
"author_id": 407641,
"author_profile": "https://Stackoverflow.com/users/407641",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply use multiple labels. Set the font properties you want and then use the left. top and width properties to display the words you want displayed differently. This is assuming you are using windows forms.</p>\n"
},
{
"answer_id": 33027593,
"author": "harry4516",
"author_id": 3304035,
"author_profile": "https://Stackoverflow.com/users/3304035",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using colored labels quite often to mark keywords in red color etc.\nLike in Phil Wright's answer I use a RichTextBox control, remove the border and set the background color to SystemColors.Control.</p>\n\n<p>To write colored text the control is first cleared and then I use this function to append colored text:</p>\n\n<pre><code>private void rtb_AppendText(Font selfont, Color color, Color bcolor, \n string text, RichTextBox box)\n {\n // append the text to the RichTextBox control\n int start = box.TextLength;\n box.AppendText(text);\n int end = box.TextLength;\n\n // select the new text\n box.Select(start, end - start);\n // set the attributes of the new text\n box.SelectionColor = color;\n box.SelectionFont = selfont;\n box.SelectionBackColor = bcolor;\n // unselect\n box.Select(end, 0);\n\n // only required for multi line text to scroll to the end\n box.ScrollToCaret();\n }\n</code></pre>\n\n<p>If you want to run this function with \"mono\" then add a space before every new colored text, or mono will not set new the color correctly. This is not required with .NET</p>\n\n<p>Usage:</p>\n\n<pre><code>myRtb.Text = \"\";\nrtb_AppendText(new Font(\"Courier New\", (float)10), \n Color.Red, SystemColors.Control, \" my red text\", myRtb);\nrtb_AppendText(new Font(\"Courier New\", (float)10), \n Color.Blue, SystemColors.Control, \" followed by blue\", myRtb);\n</code></pre>\n"
},
{
"answer_id": 48922765,
"author": "Padmaja Vudatha",
"author_id": 6318527,
"author_profile": "https://Stackoverflow.com/users/6318527",
"pm_score": -1,
"selected": false,
"text": "<p>Try this, </p>\n\n<pre><code> labelId.Text = \"Successfully sent to\" + \"<a style='color:Blue'> \" + name + \"</a>\"; \n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207/"
] |
I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?
|
There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). Normally you would have a custom label control inherit directly from Label, but since you can't get multi-colored text in one label, you would just inherit from UserControl.
For rendering the text, your UserControl could split the text on commas and then dynamically load a differently-colored Label for each chunk. A better way, however, would be to render the text directly onto your UserControl using the DrawString and MeasureString methods in the Graphics namespace.
Writing UserControls in .NET is really not difficult, and this kind of unusual problem is exactly what custom UserControls are for.
**Update**: here's a simple method you can use for rendering the multi-colored text on a PictureBox:
```
public void RenderRainbowText(string Text, PictureBox pb)
{
// PictureBox needs an image to draw on
pb.Image = new Bitmap(pb.Width, pb.Height);
using (Graphics g = Graphics.FromImage(pb.Image))
{
// create all-white background for drawing
SolidBrush brush = new SolidBrush(Color.White);
g.FillRectangle(brush, 0, 0,
pb.Image.Width, pb.Image.Height);
// draw comma-delimited elements in multiple colors
string[] chunks = Text.Split(',');
brush = new SolidBrush(Color.Black);
SolidBrush[] brushes = new SolidBrush[] {
new SolidBrush(Color.Red),
new SolidBrush(Color.Green),
new SolidBrush(Color.Blue),
new SolidBrush(Color.Purple) };
float x = 0;
for (int i = 0; i < chunks.Length; i++)
{
// draw text in whatever color
g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);
// measure text and advance x
x += (g.MeasureString(chunks[i], pb.Font)).Width;
// draw the comma back in, in black
if (i < (chunks.Length - 1))
{
g.DrawString(",", pb.Font, brush, x, 0);
x += (g.MeasureString(",", pb.Font)).Width;
}
}
}
}
```
Obviously this will break if you have more than 4 comma-delimited elements in your text, but you get the idea. Also, there appears to be a small glitch in MeasureString that makes it return a width that is a couple pixels wider than necessary, so the multi-colored string appears stretched out - you might want to tweak that part.
It should be straightforward to modify this code for a UserControl.
**Note**: TextRenderer is a better class to use for drawing and measuring strings, since it uses ints. Graphics.DrawString and .MeasureString use floats, so you'll get off-by-a-pixel errors here and there.
**Update**: *Forget* about using TextRenderer. It is dog slow.
|
275,842 |
<p>Frequently, I've dug into apropos and docs looking for something like the following only to give up to get back to the task at hand:</p>
<p>(repeat-last-command)</p>
<p>do the last C- or M- command I just executed (to be rebound to a fn key)</p>
<p>or sometimes the related: </p>
<p>(describe-last-function)</p>
<p>what keystroke did I just mistakenly issue, the effect of which I'd like to add to my bag of tricks. describe-key is close, but requires knowing what I typed. </p>
<p>Am I simply asking too much from my trusty sidekick?</p>
|
[
{
"answer_id": 275861,
"author": "Emerick Rogul",
"author_id": 33837,
"author_profile": "https://Stackoverflow.com/users/33837",
"pm_score": 7,
"selected": false,
"text": "<p>Repeat functionality is provided by the <code>repeat.el</code> Emacs Lisp package, which is included with standard Emacs distributions. From <code>repeat.el</code>'s documentation:</p>\n\n<blockquote>\n <p>This package defines a command that\n repeats the preceding command,\n whatever that was, including its\n arguments, whatever they were. This\n command is connected to the key C-x z.\n To repeat the previous command once,\n type C-x z. To repeat it a second time\n immediately after, type just z. By\n typing z again and again, you can\n repeat the command over and over.</p>\n</blockquote>\n\n<p>To see additional information about the repeat command, type <kbd>C-h F repeat RET</kbd> from within Emacs.</p>\n"
},
{
"answer_id": 275862,
"author": "echox",
"author_id": 35915,
"author_profile": "https://Stackoverflow.com/users/35915",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not really sure, but maybe you are searching for this one?</p>\n\n<blockquote>\n <p>The command <kbd>C-x</kbd><kbd>z</kbd> (<code>repeat</code>) provides another way to repeat an\n Emacs command many times. This command repeats the previous Emacs\n command, whatever that was. Repeating a command uses the same arguments\n that were used before; it does not read new arguments each time.</p>\n</blockquote>\n\n<p>Emacs Manual, 8.11 Repeating a Command</p>\n"
},
{
"answer_id": 275875,
"author": "cms",
"author_id": 28532,
"author_profile": "https://Stackoverflow.com/users/28532",
"pm_score": 7,
"selected": true,
"text": "<p>with regards to '<strong>describe-last-function</strong>':</p>\n\n<p>There's a variable <code>last-command</code> which is set to a symbol representative of the last thing you did. So this elisp snippet - <code>(describe-function last-command)</code> - ought to bring up the documentation for the thing that immediately happened.</p>\n\n<p>So you could make a trivial working <code>describe-last-function</code> like so</p>\n\n<pre><code>(defun describe-last-function() \n (interactive) \n (describe-function last-command))\n</code></pre>\n\n<p>Put that elisp in <code>.emacs</code> or equivalent, and you'll have a <strong>M-x describe-last-function</strong>.</p>\n\n<p>If you've banged on a few keys or done something that modified last-command since the thing you're interested in, the <code>command-history</code> function might be of interest. You can get that by <strong>M-x command-history</strong></p>\n"
},
{
"answer_id": 275903,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "<h2>Repeat last command</h2>\n\n<p><kbd>C-x</kbd><kbd>z</kbd></p>\n\n<p>Once you pressed it, just press only\n<kbd>z</kbd>\nafter that and it will repeat (without having to press <kbd>C-x</kbd> again).</p>\n"
},
{
"answer_id": 276557,
"author": "quodlibetor",
"author_id": 25616,
"author_profile": "https://Stackoverflow.com/users/25616",
"pm_score": 5,
"selected": false,
"text": "<p>Also, <code>M-x view-lossage</code> shows you the last hundred(?) keystrokes you entered. So, you'll be able to see where the command is. It's what i used until i just right now found out about <code>M-x command-history</code> which i think i'll be using with <code>C-h w</code> now.</p>\n"
},
{
"answer_id": 624710,
"author": "ashawley",
"author_id": 73449,
"author_profile": "https://Stackoverflow.com/users/73449",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, there is a <strong>repeat</strong> command. It's called <code>repeat</code>:</p>\n\n<ul>\n<li>You can repeat commands with <kbd>C-x</kbd> <kbd>z</kbd>, and hit <kbd>z</kbd> to keep repeating.</li>\n</ul>\n\n<p>A bit shocking nobody mentioned <code>repeat-complex-command</code>, available from the key binding <kbd>C-x</kbd> <kbd>ESC</kbd> <kbd>ESC</kbd>.</p>\n"
},
{
"answer_id": 1732831,
"author": "Murali VP",
"author_id": 179189,
"author_profile": "https://Stackoverflow.com/users/179189",
"pm_score": 3,
"selected": false,
"text": "<p>May be this would help too...\nFrom emacs Help verbatim:</p>\n\n<pre><code>C-x M-ESC runs the command repeat-complex-command\n which is an interactive compiled Lisp function in `simple.el'.\nIt is bound to <again>, <redo>, C-x M-:, C-x M-ESC.\n(repeat-complex-command ARG)\n\nEdit and re-evaluate last complex command, or ARGth from last.\nA complex command is one which used the minibuffer.\nThe command is placed in the minibuffer as a Lisp form for editing.\nThe result is executed, repeating the command as changed.\nIf the command has been changed or is not the most recent previous command\nit is added to the front of the command history.\nYou can use the minibuffer history commands M-n and M-p\nto get different commands to edit and resubmit.\n</code></pre>\n"
},
{
"answer_id": 8105886,
"author": "sabof",
"author_id": 735243,
"author_profile": "https://Stackoverflow.com/users/735243",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I found Sebastian's idea useful. Here is a working version</p>\n\n<pre><code>(global-set-key \"\\C-r\" #'(lambda () (interactive)\n (eval (car command-history))))\n</code></pre>\n"
},
{
"answer_id": 56363288,
"author": "Doug F",
"author_id": 3830432,
"author_profile": "https://Stackoverflow.com/users/3830432",
"pm_score": 1,
"selected": false,
"text": "<p>This is old, but Google pops post this up first when I was looking to retrieve the last command I typed at the Emacs prompt. None of these answers worked for me so I decided to put in my two cents for those who might stumble upon this later on as I did. I'm using Portacle, but I found what I was looking for in <a href=\"https://www.gnu.org/software/emacs/manual/html_node/emacs/Shell-Ring.html\" rel=\"nofollow noreferrer\">here</a> so I'm hoping it's generic enough to work with different setups. Anyway, what worked for me is using <kbd>C-↑</kbd> and <kbd>C-↓</kbd> to cycle through the history. Using <kbd>M-p</kbd> and <kbd>M-n</kbd> worked as well, but I prefer using the arrows since I use Bash quite a bit.</p>\n"
},
{
"answer_id": 64672746,
"author": "Micah Elliott",
"author_id": 326516,
"author_profile": "https://Stackoverflow.com/users/326516",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://www.emacswiki.org/emacs/dot-mode.el\" rel=\"nofollow noreferrer\">dot-mode</a> is a way to repeat the last command(s).</p>\n<p>From its commentary:</p>\n<blockquote>\n<p>It emulates the vi `redo' command, repeating the\nimmediately preceding sequence of commands. This is done by\nrecording input commands which change the buffer, i.e. not motion\ncommands.</p>\n</blockquote>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35911/"
] |
Frequently, I've dug into apropos and docs looking for something like the following only to give up to get back to the task at hand:
(repeat-last-command)
do the last C- or M- command I just executed (to be rebound to a fn key)
or sometimes the related:
(describe-last-function)
what keystroke did I just mistakenly issue, the effect of which I'd like to add to my bag of tricks. describe-key is close, but requires knowing what I typed.
Am I simply asking too much from my trusty sidekick?
|
with regards to '**describe-last-function**':
There's a variable `last-command` which is set to a symbol representative of the last thing you did. So this elisp snippet - `(describe-function last-command)` - ought to bring up the documentation for the thing that immediately happened.
So you could make a trivial working `describe-last-function` like so
```
(defun describe-last-function()
(interactive)
(describe-function last-command))
```
Put that elisp in `.emacs` or equivalent, and you'll have a **M-x describe-last-function**.
If you've banged on a few keys or done something that modified last-command since the thing you're interested in, the `command-history` function might be of interest. You can get that by **M-x command-history**
|
275,853 |
<p>I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway.)</p>
<p>The majority of the places where this goes wrong is a simple iteration of a std::vector, often this used to be an array in the past and has been changed to a std::vector later. So these loops generally look like this:</p>
<pre><code>for (int i = 0; i < someVector.size(); ++i) { /* do stuff */ }
</code></pre>
<p>Because this pattern is used so often, the amount of compiler warning spam about this comparison between signed and unsigned type tends to hide more useful warnings. Note that we definitely do not have vectors with more then INT_MAX elements, and note that until now we used two ways to fix compiler warning:</p>
<pre><code>for (unsigned i = 0; i < someVector.size(); ++i) { /*do stuff*/ }
</code></pre>
<p>This usually works but might silently break if the loop contains any code like 'if (i-1 >= 0) ...', etc.</p>
<pre><code>for (int i = 0; i < static_cast<int>(someVector.size()); ++i) { /*do stuff*/ }
</code></pre>
<p>This change does not have any side effects, but it does make the loop a lot less readable. (And it's more typing.)</p>
<p>So I came up with the following idea:</p>
<pre><code>template <typename T> struct vector : public std::vector<T>
{
typedef std::vector<T> base;
int size() const { return base::size(); }
int max_size() const { return base::max_size(); }
int capacity() const { return base::capacity(); }
vector() : base() {}
vector(int n) : base(n) {}
vector(int n, const T& t) : base(n, t) {}
vector(const base& other) : base(other) {}
};
template <typename Key, typename Data> struct map : public std::map<Key, Data>
{
typedef std::map<Key, Data> base;
typedef typename base::key_compare key_compare;
int size() const { return base::size(); }
int max_size() const { return base::max_size(); }
int erase(const Key& k) { return base::erase(k); }
int count(const Key& k) { return base::count(k); }
map() : base() {}
map(const key_compare& comp) : base(comp) {}
template <class InputIterator> map(InputIterator f, InputIterator l) : base(f, l) {}
template <class InputIterator> map(InputIterator f, InputIterator l, const key_compare& comp) : base(f, l, comp) {}
map(const base& other) : base(other) {}
};
// TODO: similar code for other container types
</code></pre>
<p>What you see is basically the STL classes with the methods which return size_type overridden to return just 'int'. The constructors are needed because these aren't inherited.</p>
<p><strong>What would you think of this as a developer, if you'd see a solution like this in an existing codebase?</strong></p>
<p>Would you think 'whaa, they're redefining the STL, what a huge WTF!', or would you think this is a nice simple solution to prevent bugs and increase readability. Or maybe you'd rather see we had spent (half) a day or so on changing all these loops to use std::vector<>::iterator?</p>
<p>(In particular if this solution was combined with banning the use of unsigned types for anything but raw data (e.g. unsigned char) and bit masks.)</p>
|
[
{
"answer_id": 275873,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "<h2>I made this community wiki... Please edit it. I don't agree with the advice against \"int\" anymore. I now see it as not bad.</h2>\n\n<p>Yes, i agree with Richard. You should never use <code>'int'</code> as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is little reason to, occasionally this can be useful).</p>\n\n<h2>Forward</h2>\n\n<pre><code>for(std::vector<int>::size_type i = 0; i < someVector.size(); i++) {\n /* ... */\n}\n</code></pre>\n\n<h2>Backward</h2>\n\n<p>You can do this, which is perfectly defined behaivor:</p>\n\n<pre><code>for(std::vector<int>::size_type i = someVector.size() - 1; \n i != (std::vector<int>::size_type) -1; i--) {\n /* ... */\n}\n</code></pre>\n\n<p>Soon, with c++1x (next C++ version) coming along nicely, you can do it like this:</p>\n\n<pre><code>for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) {\n /* ... */\n}\n</code></pre>\n\n<p>Decrementing below 0 will cause i to wrap around, because it is unsigned. </p>\n\n<h2>But unsigned will make bugs slurp in</h2>\n\n<p>That should never be an argument to make it the wrong way (using <code>'int'</code>). </p>\n\n<h2>Why not use std::size_t above?</h2>\n\n<p>The C++ Standard defines in <code>23.1 p5 Container Requirements</code>, that <code>T::size_type</code> , for <code>T</code> being some <code>Container</code>, that this type is some implementation defined unsigned integral type. Now, using <code>std::size_t</code> for <code>i</code> above will let bugs slurp in silently. If <code>T::size_type</code> is less or greater than <code>std::size_t</code>, then it will overflow <code>i</code>, or not even get up to <code>(std::size_t)-1</code> if <code>someVector.size() == 0</code>. Likewise, the condition of the loop would have been broken completely.</p>\n"
},
{
"answer_id": 275889,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": false,
"text": "<p>Don't derive publicly from STL containers. They have nonvirtual destructors which invokes undefined behaviour if anyone deletes one of your objects through a pointer-to base. If you must derive e.g. from a vector, do it privately and expose the parts you need to expose with <code>using</code> declarations.</p>\n\n<p>Here, I'd just use a <code>size_t</code> as the loop variable. It's simple and readable. The poster who commented that using an <code>int</code> index exposes you as a n00b is correct. However, using an iterator to loop over a vector exposes you as a slightly more experienced n00b - one who doesn't realize that the subscript operator for vector is constant time. (<code>vector<T>::size_type</code> is accurate, but needlessly verbose IMO).</p>\n"
},
{
"answer_id": 275897,
"author": "Lodle",
"author_id": 23339,
"author_profile": "https://Stackoverflow.com/users/23339",
"pm_score": 0,
"selected": false,
"text": "<p><code>vector.size()</code> returns a <code>size_t</code> var, so just change <code>int</code> to <code>size_t</code> and it should be fine.</p>\n\n<p>Richard's answer is more correct, except that it's a lot of work for a simple loop.</p>\n"
},
{
"answer_id": 275898,
"author": "Dan Olson",
"author_id": 33346,
"author_profile": "https://Stackoverflow.com/users/33346",
"pm_score": 0,
"selected": false,
"text": "<p>You're overthinking the problem.</p>\n\n<p>Using a size_t variable is preferable, but if you don't trust your programmers to use unsigned correctly, go with the cast and just deal with the ugliness. Get an intern to change them all and don't worry about it after that. Turn on warnings as errors and no new ones will creep in. Your loops may be \"ugly\" now, but you can understand that as the consequences of your religious stance on signed versus unsigned.</p>\n"
},
{
"answer_id": 275951,
"author": "Tim Weiler",
"author_id": 33703,
"author_profile": "https://Stackoverflow.com/users/33703",
"pm_score": 2,
"selected": false,
"text": "<p>Definitely use an iterator. Soon you will be able to use the 'auto' type, for better readability (one of your concerns) like this:</p>\n\n<pre><code>for (auto i = someVector.begin();\n i != someVector.end();\n ++i)\n</code></pre>\n"
},
{
"answer_id": 275955,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 2,
"selected": false,
"text": "<p>While I don't think \"use iterators, otherwise you look n00b\" is a good solution to the problem, deriving from std::vector appears much worse than that.</p>\n\n<p>First, developers do expect vector to be std:.vector, and map to be std::map. Second, your solution does not scale for other containers, or for other classes/libraries that interact with containers.</p>\n\n<p>Yes, iterators are ugly, iterator loops are not very well readable, and typedefs only cover up the mess. But at least, they do scale, and they are the canonical solution.</p>\n\n<p>My solution? an stl-for-each macro. That is not without problems (mainly, it is a macro, yuck), but it gets across the meaning. It is not as advanced as e.g. <a href=\"http://wtw.tw/papers/foreach.html\" rel=\"nofollow noreferrer\">this one</a>, but does the job.</p>\n"
},
{
"answer_id": 18369772,
"author": "Adrian McCarthy",
"author_id": 1386054,
"author_profile": "https://Stackoverflow.com/users/1386054",
"pm_score": 2,
"selected": false,
"text": "<h2>Skip the index</h2>\n\n<p>The easiest approach is to sidestep the problem by using iterators, range-based for loops, or algorithms:</p>\n\n<pre><code>for (auto it = begin(v); it != end(v); ++it) { ... }\nfor (const auto &x : v) { ... }\nstd::for_each(v.begin(), v.end(), ...);\n</code></pre>\n\n<p>This is a nice solution if you don't actually need the index value. It also handles reverse loops easily.</p>\n\n<h2>Use an appropriate unsigned type</h2>\n\n<p>Another approach is to use the container's size type.</p>\n\n<pre><code>for (std::vector<T>::size_type i = 0; i < v.size(); ++i) { ... }\n</code></pre>\n\n<p>You can also use <code>std::size_t</code> (from <cstddef>). There are those who (correctly) point out that <code>std::size_t</code> may not be the same type as <code>std::vector<T>::size_type</code> (though it usually is). You can, however, be assured that the container's <code>size_type</code> will fit in a <code>std::size_t</code>. So everything is fine, unless you use certain styles for reverse loops. My preferred style for a reverse loop is this:</p>\n\n<pre><code>for (std::size_t i = v.size(); i-- > 0; ) { ... }\n</code></pre>\n\n<p>With this style, you can safely use <code>std::size_t</code>, even if it's a larger type than <code>std::vector<T>::size_type</code>. The style of reverse loops shown in some of the other answers require casting a -1 to exactly the right type and thus cannot use the easier-to-type <code>std::size_t</code>.</p>\n\n<h2>Use a signed type (carefully!)</h2>\n\n<p>If you really want to use a signed type (or if your <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Integer_Types#Integer_Types\" rel=\"nofollow\">style guide practically demands one</a>), like <code>int</code>, then you can use this tiny function template that checks the underlying assumption in debug builds and makes the conversion explicit so that you don't get the compiler warning message:</p>\n\n<pre><code>#include <cassert>\n#include <cstddef>\n#include <limits>\n\ntemplate <typename ContainerType>\nconstexpr int size_as_int(const ContainerType &c) {\n const auto size = c.size(); // if no auto, use `typename ContainerType::size_type`\n assert(size <= static_cast<std::size_t>(std::numeric_limits<int>::max()));\n return static_cast<int>(size);\n}\n</code></pre>\n\n<p>Now you can write:</p>\n\n<pre><code>for (int i = 0; i < size_as_int(v); ++i) { ... }\n</code></pre>\n\n<p>Or reverse loops in the traditional manner:</p>\n\n<pre><code>for (int i = size_as_int(v) - 1; i >= 0; --i) { ... }\n</code></pre>\n\n<p>The <code>size_as_int</code> trick is only slightly more typing than the loops with the implicit conversions, you get the underlying assumption checked at runtime, you silence the compiler warning with the explicit cast, you get the same speed as non-debug builds because it will almost certainly be inlined, and the optimized object code shouldn't be any larger because the template doesn't do anything the compiler wasn't already doing implicitly.</p>\n"
},
{
"answer_id": 71972901,
"author": "Jeroen Lammertink",
"author_id": 10159412,
"author_profile": "https://Stackoverflow.com/users/10159412",
"pm_score": 0,
"selected": false,
"text": "<p>I notice that people have very different opinions about this subject. I have also an opinion which does not convince others, so it makes sense to search for support by some guru’s, and I found the CPP core guidelines:</p>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines\" rel=\"nofollow noreferrer\">https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines</a></p>\n<p>maintained by Bjarne Stroustrup and Herb Sutter, and their last update, upon which I base the information below, is of April 10, 2022.</p>\n<p>Please take a look at the following code rules:</p>\n<ul>\n<li>ES.100: Don’t mix signed and unsigned arithmetic</li>\n<li>ES.101: Use unsigned types for bit manipulation</li>\n<li>ES.102: Use signed types for arithmetic</li>\n<li>ES.107: Don’t use unsigned for subscripts, prefer gsl::index</li>\n</ul>\n<p>So, supposing that we want to index in a for loop and for some reason the range based for loop is not the appropriate solution, then using an unsigned type is also <strong>not</strong> the preferred solution. The suggested solution is using gsl::index.</p>\n<p>But in case you don’t have gsl around and you don’t want to introduce it, what then?</p>\n<p>In that case I would suggest to have a utility template function as suggested by Adrian McCarthy: size_as_int</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5422/"
] |
I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway.)
The majority of the places where this goes wrong is a simple iteration of a std::vector, often this used to be an array in the past and has been changed to a std::vector later. So these loops generally look like this:
```
for (int i = 0; i < someVector.size(); ++i) { /* do stuff */ }
```
Because this pattern is used so often, the amount of compiler warning spam about this comparison between signed and unsigned type tends to hide more useful warnings. Note that we definitely do not have vectors with more then INT\_MAX elements, and note that until now we used two ways to fix compiler warning:
```
for (unsigned i = 0; i < someVector.size(); ++i) { /*do stuff*/ }
```
This usually works but might silently break if the loop contains any code like 'if (i-1 >= 0) ...', etc.
```
for (int i = 0; i < static_cast<int>(someVector.size()); ++i) { /*do stuff*/ }
```
This change does not have any side effects, but it does make the loop a lot less readable. (And it's more typing.)
So I came up with the following idea:
```
template <typename T> struct vector : public std::vector<T>
{
typedef std::vector<T> base;
int size() const { return base::size(); }
int max_size() const { return base::max_size(); }
int capacity() const { return base::capacity(); }
vector() : base() {}
vector(int n) : base(n) {}
vector(int n, const T& t) : base(n, t) {}
vector(const base& other) : base(other) {}
};
template <typename Key, typename Data> struct map : public std::map<Key, Data>
{
typedef std::map<Key, Data> base;
typedef typename base::key_compare key_compare;
int size() const { return base::size(); }
int max_size() const { return base::max_size(); }
int erase(const Key& k) { return base::erase(k); }
int count(const Key& k) { return base::count(k); }
map() : base() {}
map(const key_compare& comp) : base(comp) {}
template <class InputIterator> map(InputIterator f, InputIterator l) : base(f, l) {}
template <class InputIterator> map(InputIterator f, InputIterator l, const key_compare& comp) : base(f, l, comp) {}
map(const base& other) : base(other) {}
};
// TODO: similar code for other container types
```
What you see is basically the STL classes with the methods which return size\_type overridden to return just 'int'. The constructors are needed because these aren't inherited.
**What would you think of this as a developer, if you'd see a solution like this in an existing codebase?**
Would you think 'whaa, they're redefining the STL, what a huge WTF!', or would you think this is a nice simple solution to prevent bugs and increase readability. Or maybe you'd rather see we had spent (half) a day or so on changing all these loops to use std::vector<>::iterator?
(In particular if this solution was combined with banning the use of unsigned types for anything but raw data (e.g. unsigned char) and bit masks.)
|
I made this community wiki... Please edit it. I don't agree with the advice against "int" anymore. I now see it as not bad.
---------------------------------------------------------------------------------------------------------------------------
Yes, i agree with Richard. You should never use `'int'` as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is little reason to, occasionally this can be useful).
Forward
-------
```
for(std::vector<int>::size_type i = 0; i < someVector.size(); i++) {
/* ... */
}
```
Backward
--------
You can do this, which is perfectly defined behaivor:
```
for(std::vector<int>::size_type i = someVector.size() - 1;
i != (std::vector<int>::size_type) -1; i--) {
/* ... */
}
```
Soon, with c++1x (next C++ version) coming along nicely, you can do it like this:
```
for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) {
/* ... */
}
```
Decrementing below 0 will cause i to wrap around, because it is unsigned.
But unsigned will make bugs slurp in
------------------------------------
That should never be an argument to make it the wrong way (using `'int'`).
Why not use std::size\_t above?
-------------------------------
The C++ Standard defines in `23.1 p5 Container Requirements`, that `T::size_type` , for `T` being some `Container`, that this type is some implementation defined unsigned integral type. Now, using `std::size_t` for `i` above will let bugs slurp in silently. If `T::size_type` is less or greater than `std::size_t`, then it will overflow `i`, or not even get up to `(std::size_t)-1` if `someVector.size() == 0`. Likewise, the condition of the loop would have been broken completely.
|
275,855 |
<p>I have a custom attribute which can be assigned to a class, <code>[FooAttribute]</code>. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have:</p>
<pre><code>[FooAttribute]
public class Bar
{
}
</code></pre>
<p>In the code for FooAttribute, how can I determine it was Bar class that added me? I'm not specifically looking for the Bar type, I just want to set a friendly name using reflection. e.g.</p>
<pre><code>[FooAttribute(Name="MyFriendlyNameForThisClass")]
public class Bar
{
}
public class FooAttribute()
{
public FooAttribute()
{
// How do I get the target types name? (as a default)
}
}
</code></pre>
|
[
{
"answer_id": 275887,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "<p>From your sentence \"I just want to set a friendly name using reflection\" I think you want to set the \"MyFriendlyNameForThisClass\" name to the attribute at runtime. if so, I don't think that's possible. Please see <a href=\"https://stackoverflow.com/questions/51269/change-attributes-parameter-at-runtime\">this thread</a>.</p>\n"
},
{
"answer_id": 275899,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 2,
"selected": false,
"text": "<p>To elaborat. A attribute, built in or custom, is just meta data for a class, or class member, and the attribute itself nas no notation that it's being associated with something.</p>\n\n<ul>\n<li>The type knows of it's own metadata</li>\n<li>The meta data (in this case, the attribute) does not know to whom it belongs</li>\n</ul>\n"
},
{
"answer_id": 275921,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>First off, you might consider the existing <code>[DisplayName]</code> for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type <em>into</em> the attribute - i.e.</p>\n\n<pre><code>[Foo(\"Some name\", typeof(Bar)]\n</code></pre>\n\n<p>What exactly is it you want to do? There may be other options...</p>\n\n<p>Note that for i18n, resx, etc; you can subclass <code>DisplayNameAttribute</code> and provide lookup from keys by overriding the <code>DisplayName</code> getter.</p>\n"
},
{
"answer_id": 467538,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>It is clumsy but you could iterate over all classes in the assembly, testing each for the custom attribute that \"is\" this instance.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
I have a custom attribute which can be assigned to a class, `[FooAttribute]`. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have:
```
[FooAttribute]
public class Bar
{
}
```
In the code for FooAttribute, how can I determine it was Bar class that added me? I'm not specifically looking for the Bar type, I just want to set a friendly name using reflection. e.g.
```
[FooAttribute(Name="MyFriendlyNameForThisClass")]
public class Bar
{
}
public class FooAttribute()
{
public FooAttribute()
{
// How do I get the target types name? (as a default)
}
}
```
|
First off, you might consider the existing `[DisplayName]` for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type *into* the attribute - i.e.
```
[Foo("Some name", typeof(Bar)]
```
What exactly is it you want to do? There may be other options...
Note that for i18n, resx, etc; you can subclass `DisplayNameAttribute` and provide lookup from keys by overriding the `DisplayName` getter.
|
275,868 |
<p>How would I go about having a CMake buildsystem, which scans for source files now using <a href="http://www.cmake.org/cmake/help/cmake2.6docs.html#command:aux_source_directory" rel="noreferrer">AUX_SOURCE_DIRECTORY</a>, scan for header files too in the same directory, preferably using a similar command?</p>
<p>I didn't find an easy way to do this in the documentation yet, so I now have a crappy bash script to post-process my (CodeBlocks) project file...</p>
|
[
{
"answer_id": 293202,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": -1,
"selected": false,
"text": "<p>The documentation to AUX_SOURCE_DIRECTORY suggests that it was not intended to be used that way, so I'd rather doubt that what you're asking is possible. If you want an authoritative answer, you can reach the CMake developers at [email protected] (they're actually very nice to deal with).</p>\n\n<p>I'd recommend strongly against using wildcards to specify what is included in the build. The build files should specify the exact contents of the libraries, and not depend on what happens to exist in the directory. It may be cumbersome at first (if you're used to wildcards, or IDE's which works the same way), but when you get used to it, you don't want to have it any other way.</p>\n"
},
{
"answer_id": 309455,
"author": "David",
"author_id": 28275,
"author_profile": "https://Stackoverflow.com/users/28275",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the file(GLOB ... ) command. For example:</p>\n\n<pre><code>set(dir my_search_dir)\nfile (GLOB headers \"${dir}/*.h\")\nmessage(\"My headers: \" ${headers})\n</code></pre>\n\n<p>This command can also recurse, and list your files relative to a given path. See the <a href=\"http://www.cmake.org/cmake/help/cmake2.6docs.html#command:file\" rel=\"noreferrer\">\"file\" command entry </a> in the cmake doc.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5422/"
] |
How would I go about having a CMake buildsystem, which scans for source files now using [AUX\_SOURCE\_DIRECTORY](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:aux_source_directory), scan for header files too in the same directory, preferably using a similar command?
I didn't find an easy way to do this in the documentation yet, so I now have a crappy bash script to post-process my (CodeBlocks) project file...
|
You can use the file(GLOB ... ) command. For example:
```
set(dir my_search_dir)
file (GLOB headers "${dir}/*.h")
message("My headers: " ${headers})
```
This command can also recurse, and list your files relative to a given path. See the ["file" command entry](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:file) in the cmake doc.
|
275,871 |
<p>Suppose I have code like this:</p>
<pre><code>template<class T, T initial_t> class Bar {
// something
}
</code></pre>
<p>And then try to use it like this:</p>
<pre><code>Bar<Foo*, NULL> foo_and_bar_whatever_it_means_;
</code></pre>
<p>GCC bails out with error (on the above line):</p>
<blockquote>
<p>could not convert template argument
'0' to 'Foo*'</p>
</blockquote>
<p>I found this thread: <a href="http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html" rel="nofollow noreferrer">http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html</a>, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.</p>
|
[
{
"answer_id": 275884,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code>Bar<Foo*, (Foo*)NULL> foo_and_bar_whatever_it_means_;\n</code></pre>\n\n<p>? </p>\n\n<p>or reinterpret_cast(0)?</p>\n"
},
{
"answer_id": 275886,
"author": "Dan Olson",
"author_id": 33346,
"author_profile": "https://Stackoverflow.com/users/33346",
"pm_score": 3,
"selected": true,
"text": "<p>Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed.</p>\n"
},
{
"answer_id": 275908,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 2,
"selected": false,
"text": "<p>It seems to be the same problem as passing a <em>string literal</em> as non-type template parameter: it's not allowed. A pointer to an object is allowed as template parameter if the object has <strong>external linkage</strong>: this to guarantee the uniqueness of the type.</p>\n"
},
{
"answer_id": 275959,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 0,
"selected": false,
"text": "<p>@Dan Olson: there seems to be quite easy workaround.</p>\n\n<p>Create a parent class with only one template parameter. Add a virtual function returning T. For base class it should be hardcoded to be NULL. For deriving class it would return the second template parameter.</p>\n"
},
{
"answer_id": 277934,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>To accept <code>Bar<Foo, NULL></code>, you need</p>\n\n<pre><code>template <typename T, int dummy> class Bar; /* Declared but not defined */\ntemplate <typename T> class Bar <T,NULL> { /* Specialization */ };\n</code></pre>\n\n<p>since typeof(NULL)==int.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
Suppose I have code like this:
```
template<class T, T initial_t> class Bar {
// something
}
```
And then try to use it like this:
```
Bar<Foo*, NULL> foo_and_bar_whatever_it_means_;
```
GCC bails out with error (on the above line):
>
> could not convert template argument
> '0' to 'Foo\*'
>
>
>
I found this thread: <http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html>, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.
|
Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed.
|
275,878 |
<p>My client gets a <code>sec_error_unknown_issuer</code> error message when visiting <a href="https://mediant.ipmail.nl" rel="noreferrer">https://mediant.ipmail.nl</a> with Firefox.
I can't reproduce the error myself. I installed FF on a Vista and a XP machine and had no problems. FF on Ubuntu also works fine.</p>
<p>Does anyone get the same error and does anyone have some clues for me so I can tell my ISP to change some settings?
The certificate is a so called wild-card SSL certificate that works for all subdomains (*.ipmail.nl). Was I wrong to pick the cheapest one?</p>
|
[
{
"answer_id": 275882,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>Which version of Firefox on which platform is your client using?</p>\n\n<p>The are people having the same problem as documented <a href=\"http://support.mozilla.com/tiki-view_forum_thread.php?forumId=1&comments_parentId=64923\" rel=\"nofollow noreferrer\">here in the Support Forum for Firefox</a>. I hope you can find a solution there. Good luck!</p>\n\n<p><em>Update:</em></p>\n\n<p>Let your client check the settings in Firefox: On \"Advanced\" - \"Encryption\" there is a button \"View Certificates\". <strong>Look for \"Comodo CA Limited\"</strong> in the list. I saw that Comodo is the issuer of the certificate of that domain name/server. On two of my machines (FF 3.0.3 on Vista and Mac) the entry is in the list (by default/Mozilla).</p>\n\n<p><a href=\"https://i.stack.imgur.com/b1Cd9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b1Cd9.png\" alt=\"alt text\"></a></p>\n"
},
{
"answer_id": 1026287,
"author": "user126810",
"author_id": 126810,
"author_profile": "https://Stackoverflow.com/users/126810",
"pm_score": 5,
"selected": false,
"text": "<p>Just had the same problem with a Comodo Wildcard SSL cert. After reading the docs the solution is to ensure you include the certificate chain file they send you in your config i.e.</p>\n\n<pre><code>SSLCertificateChainFile /etc/ssl/crt/yourSERVERNAME.ca-bundle\n</code></pre>\n\n<p>Full details on <a href=\"https://support.comodo.com/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=264&nav=0,1\" rel=\"noreferrer\">Comodo site</a></p>\n"
},
{
"answer_id": 1639022,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 4,
"selected": false,
"text": "<p>We had this problem and it was very much Firefox specific -- could only repro in that browser, Safari, IE8, Chrome, etc were all fine.</p>\n\n<p>Fixing it required <strong>getting an updated cert from Comodo</strong> and installing it.</p>\n\n<p>No idea what magic they changed, but it was definitely something in the cert that Firefox did NOT like.</p>\n"
},
{
"answer_id": 1842759,
"author": "toddb",
"author_id": 13074,
"author_profile": "https://Stackoverflow.com/users/13074",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem with Firefox and my server. I contacted GoDaddy customer support, and they had me install the intermediate server certificate:</p>\n\n<p><a href=\"http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate\" rel=\"nofollow noreferrer\">http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate</a></p>\n\n<p>After a re-start of the World Wide Web Publishing Service, everything worked perfectly.</p>\n\n<p>If you do not have full access to your server, your ISP will have to do this for you.</p>\n"
},
{
"answer_id": 1892457,
"author": "Jason Clark",
"author_id": 230150,
"author_profile": "https://Stackoverflow.com/users/230150",
"pm_score": 3,
"selected": false,
"text": "<p>Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.</p>\n\n<p>while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.</p>\n"
},
{
"answer_id": 14721055,
"author": "vadipp",
"author_id": 501399,
"author_profile": "https://Stackoverflow.com/users/501399",
"pm_score": 1,
"selected": false,
"text": "<p>As @user126810 said, the problem can be fixed with a proper <code>SSLCertificateChainFile</code> directive in the config file.</p>\n\n<p>But after fixing the config and restarting the webserver, I also had to <strong>restart Firefox</strong>. Without that, Firefox continued to complain about bad certificate (looks like it used a cached one).</p>\n"
},
{
"answer_id": 20267134,
"author": "Cc65",
"author_id": 2497291,
"author_profile": "https://Stackoverflow.com/users/2497291",
"pm_score": 3,
"selected": false,
"text": "<p>For nginx do this \nGenerate a chained crt file using</p>\n\n<pre><code>$ cat www.example.com.crt bundle.crt > www.example.com.chained.crt\n</code></pre>\n\n<p>The resulting file should be used in the ssl_certificate directive:</p>\n\n<pre><code>server {\n listen 443 ssl;\n server_name www.example.com;\n ssl_certificate www.example.com.chained.crt;\n ssl_certificate_key www.example.com.key;\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 23670019,
"author": "Steven Lizarazo",
"author_id": 589132,
"author_profile": "https://Stackoverflow.com/users/589132",
"pm_score": 1,
"selected": false,
"text": "<p>If you got your cert from COMODO your need to add\nthis line, the file is on the zip file you received.</p>\n\n<pre><code>SSLCertificateChainFile /path/COMODORSADomainValidationSecureServerCA.crt\n</code></pre>\n"
},
{
"answer_id": 24218240,
"author": "leancode",
"author_id": 1343743,
"author_profile": "https://Stackoverflow.com/users/1343743",
"pm_score": 2,
"selected": false,
"text": "<p>I know this thread is a little old but we ran into this too and will archive our eventual solution here for others.</p>\n\n<p>We had the same problem with a Comodo wildcard \"positive ssl\" cert.\nWe are running our website using a squid-reverse SSL proxy and Firefox would keep complaining \"sec_error_unknown_issuer\" as you stated, yet every other browser was OK.</p>\n\n<p>I found that this is a problem of the certificate chain being incomplete. Firefox apparently does not have one of the intermediary certificates build in, though Firefox does trust the root CA. Therefore you have to provide the whole chain of certificates to Firefox. Comodo's support states:</p>\n\n<blockquote>\n <p>An intermediate certificate is the\n certificate, or certificates, that go between your site (server)\n certificate and a root certificate. The intermediate certificate, or\n certificates, completes the chain to a root certificate trusted by the\n browser.</p>\n \n <p>Using an intermediate certificate means that you must complete an\n additional step in the installation process to enable your site\n certificate to be chained to the trusted root, and not show errors in\n the browser when someone visits your web site.</p>\n</blockquote>\n\n<p>This was already touched on earlier in this thread but it did not resove how you do this.</p>\n\n<p>First you have to make a chained certificate bundle and you do that by using your favorite text editor and just paste them in, in the correct (reverse) order i.e.</p>\n\n<ul>\n<li>Intermediate CA Certificate 2 - IntermediateCA2.crt - on top of the\nfile </li>\n<li>Intermediate CA Certificate 1 - IntermediateCA1.crt</li>\n<li>Root CA Certificate - root.crt - at the end of the file</li>\n</ul>\n\n<p>The exact order you can get from your ssl provider if its not obvious from the names.</p>\n\n<p>Then save the file as whatever name you like. E.g. yourdomain-chain-bundle.crt</p>\n\n<p>In this example I have not included the actual domain certificate and as long as your server can be configured to take a separate chained certificate bundle this is what you use.</p>\n\n<p>More data can be found here:</p>\n\n<p><a href=\"https://support.comodo.com/index.php?/Knowledgebase/Article/View/643/0/how-do-i-make-my-own-bundle-file-from-crt-files\" rel=\"nofollow\">https://support.comodo.com/index.php?/Knowledgebase/Article/View/643/0/how-do-i-make-my-own-bundle-file-from-crt-files</a></p>\n\n<p>If for some reason you can't configure your server to use a separate chained bundle, then you just paste your server certificate in the beginning (on the top) of the bundle and use the resulting file as your server cert. This is what needs to be done in the E.g Squid case. See below from the squid mailing list on this subject.</p>\n\n<p><a href=\"http://www.squid-cache.org/mail-archive/squid-users/201109/0037.html\" rel=\"nofollow\">http://www.squid-cache.org/mail-archive/squid-users/201109/0037.html</a></p>\n\n<p>This resolved it for us.</p>\n"
},
{
"answer_id": 24231709,
"author": "lito",
"author_id": 999525,
"author_profile": "https://Stackoverflow.com/users/999525",
"pm_score": 1,
"selected": false,
"text": "<p>June 2014:</p>\n\n<p>This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)</p>\n\n<pre><code>var privateKey = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');\nvar certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');\n\nfiles = [\"COMODORSADomainValidationSecureServerCA.crt\",\n \"COMODORSAAddTrustCA.crt\",\n \"AddTrustExternalCARoot.crt\"\n ];\n\nca = (function() {\n var _i, _len, _results;\n\n _results = [];\n for (_i = 0, _len = files.length; _i < _len; _i++) {\n file = files[_i];\n _results.push(fs.readFileSync(\"helpers/sslcert/\" + file));\n }\n return _results;\n})();\n\nvar credentials = {ca:ca, key: privateKey, cert: certificate};\n\n// process.env.PORT : Heroku Config environment\nvar port = process.env.PORT || 4000;\n\nvar app = express();\nvar server = http.createServer(app).listen(port, function() {\n console.log('Express HTTP server listening on port ' + server.address().port);\n});\nhttps.createServer(credentials, app).listen(3000, function() {\n console.log('Express HTTPS server listening on port ' + server.address().port);\n});\n\n// redirect all http requests to https\napp.use(function(req, res, next) {\n if(!req.secure) {\n return res.redirect(['https://mydomain.com', req.url].join(''));\n }\n next();\n});\n</code></pre>\n\n<p>Then I redirected the 80 and 443 ports:</p>\n\n<pre><code>sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000\nsudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000\n</code></pre>\n\n<p>As you can see after checking my certifications I have 4 [0,1,2,3]:</p>\n\n<blockquote>\n <p>openssl s_client -connect mydomain.com:443 -showcerts | grep \"^ \"</p>\n</blockquote>\n\n<pre><code>ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep \"^ \"\ndepth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root\nverify error:num=19:self signed certificate in certificate chain\nverify return:0\n 0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com\n i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA\n 1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA\n i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority\n 2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority\n i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n 3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n Protocol : TLSv1.1\n Cipher : AES256-SHA\n Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD\n Session-ID-ctx:\n Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94\n Key-Arg : None\n PSK identity: None\n PSK identity hint: None\n SRP username: None\n TLS session ticket lifetime hint: 300 (seconds)\n TLS session ticket:\n 0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac |.6..MLG....p...\n 0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9 ..J&..........S.\n 0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79 .I.HD&.......s.y\n 0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32 .yj........R...2\n 0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce ........(.......\n 0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c .+.s...........L\n 0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e P\"`.....B.V..{..\n 0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f ..J......4...{./\n 0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da .3..H...i....R..\n 0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e .....=......N...\n Start Time: 140...549\n Timeout : 300 (sec)\n Verify return code: 19 (self signed certificate in certificate chain)\n</code></pre>\n\n<p>Good luck!\nPD: if u want more answers please check: <a href=\"http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/\" rel=\"nofollow\">http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/</a></p>\n"
},
{
"answer_id": 28257078,
"author": "chmoder",
"author_id": 3064462,
"author_profile": "https://Stackoverflow.com/users/3064462",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone else is experiencing this issue with an Ubuntu LAMP and \"COMODO Positive SSL\" try to build your own bundle from the certs in the compressed file.</p>\n\n<p><code>cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt > YOURDOMAIN.ca-bundle</code></p>\n"
},
{
"answer_id": 34758683,
"author": "Rob",
"author_id": 491950,
"author_profile": "https://Stackoverflow.com/users/491950",
"pm_score": 0,
"selected": false,
"text": "<p>I've being going round in circles with Firefox 43, El Capitan and WHM/cPanel SSL installation continually getting the Untrusted site error - I didn't buy the certificate it was handed over to me to install as the last guy walked out the door. Turns out I was installing under the wrong domain because I missed off the www - but the certificate still installed against the domain, when I installed the certificate in WHM using www.domain.com.au it installed now worries and the FF error has gone - the certificate works fine for both www and non-www.</p>\n"
},
{
"answer_id": 50683724,
"author": "Pierz",
"author_id": 436794,
"author_profile": "https://Stackoverflow.com/users/436794",
"pm_score": 0,
"selected": false,
"text": "<p>To answer the non-reproducability aspect of the question - Firefox automatically imports intermediate certificates into its certificate store. So if you've previously visited a site which has used the same Intermediate Certificate using a correctly configured certificate chain then Firefox will store that Certificate so you will not see the problem when you visit a site that has an incorrectly configured chain using the same Intermediate certificate.</p>\n\n<p>You can check this in Firefox's Certificate Manager (Options->Privacy&Security->View Certificates...) where you can see all stored certificates. Under the 'Security Device' Column you can check where a certificate has come from - automatically/manually imported certificates will appear as from 'Software Security Device' as opposed to the 'Builtin Object Token', which are the default set installed with Firefox. You can delete/Distrust any specific certificates and test again.</p>\n"
},
{
"answer_id": 57954298,
"author": "Meloman",
"author_id": 2282880,
"author_profile": "https://Stackoverflow.com/users/2282880",
"pm_score": 0,
"selected": false,
"text": "<p>Had same issue this end of week, only Firefox will not accept certificate... The solution for me has been to add, in the apache configuration of the website, the intermediate certificate with the following line :</p>\n\n<pre><code>SSLCACertificateFile /your/path/to/ssl_ca_certs.pem\n</code></pre>\n\n<p><em>Find more infomration on <a href=\"https://httpd.apache.org/docs/2.4/fr/mod/mod_ssl.html\" rel=\"nofollow noreferrer\">https://httpd.apache.org/docs/2.4/fr/mod/mod_ssl.html</a></em></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
My client gets a `sec_error_unknown_issuer` error message when visiting <https://mediant.ipmail.nl> with Firefox.
I can't reproduce the error myself. I installed FF on a Vista and a XP machine and had no problems. FF on Ubuntu also works fine.
Does anyone get the same error and does anyone have some clues for me so I can tell my ISP to change some settings?
The certificate is a so called wild-card SSL certificate that works for all subdomains (\*.ipmail.nl). Was I wrong to pick the cheapest one?
|
Just had the same problem with a Comodo Wildcard SSL cert. After reading the docs the solution is to ensure you include the certificate chain file they send you in your config i.e.
```
SSLCertificateChainFile /etc/ssl/crt/yourSERVERNAME.ca-bundle
```
Full details on [Comodo site](https://support.comodo.com/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=264&nav=0,1)
|
275,880 |
<p>I'm working with JSTL in Eclipse, using the WTP. I have jstl and standard.jar in my WEB-INF/lib directory, and everything works. Eclipse is giving me this warning in my JSP:</p>
<p>The TagExtraInfo class for c:forEach (org.apache.taglibs.standard.tei.ForEachTEI) was not found on the build path.</p>
<p>I have JSTL included:</p>
<pre><code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
</code></pre>
<p>The warning is on a line that uses a c:forEach. How can I get rid of it?
My project is targeting Tomcat v6.</p>
|
[
{
"answer_id": 282338,
"author": "nitind",
"author_id": 27905,
"author_profile": "https://Stackoverflow.com/users/27905",
"pm_score": 1,
"selected": false,
"text": "<p>Are the jars actually on the build path? If so, you might try closing and reopening the project. Otherwise that message is controllable from the Web/JSP Files/Validation preference page.</p>\n"
},
{
"answer_id": 354244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Add the standard.jar from the web-inf directory to your build path jars.</p>\n"
},
{
"answer_id": 1414843,
"author": "TimK",
"author_id": 2348,
"author_profile": "https://Stackoverflow.com/users/2348",
"pm_score": 1,
"selected": true,
"text": "<p>Eventually, I accidentally double-clicked the warning, and it took me to the source, which was editable. Then I fixed the problem myself.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2348/"
] |
I'm working with JSTL in Eclipse, using the WTP. I have jstl and standard.jar in my WEB-INF/lib directory, and everything works. Eclipse is giving me this warning in my JSP:
The TagExtraInfo class for c:forEach (org.apache.taglibs.standard.tei.ForEachTEI) was not found on the build path.
I have JSTL included:
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
```
The warning is on a line that uses a c:forEach. How can I get rid of it?
My project is targeting Tomcat v6.
|
Eventually, I accidentally double-clicked the warning, and it took me to the source, which was editable. Then I fixed the problem myself.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.