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
|
---|---|---|---|---|---|---|
275,888 |
<p>Use HttpWebRequest to download web pages without key sensitive issues</p>
|
[
{
"answer_id": 275905,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>[update: I don't know why, but both examples below now work fine! Originally I was also seeing a 403 on the page2 example. Maybe it was a server issue?]</p>\n\n<p>First, <code>WebClient</code> is easier. Actually, <a href=\"http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1393cb0a3c6728a7/258fd33c5fc96c2f\" rel=\"nofollow noreferrer\">I've seen this before</a>. It turned out to be case sensitivity in the url when accessing wikipedia; try ensuring that you have used the same case in your request to wikipedia.</p>\n\n<p>[updated] As Bruno Conde and gimel observe, using %27 should help make it consistent (the intermittent behaviour suggest that maybe some wikipedia servers are configured differently to others)</p>\n\n<p>I've just checked, and in this case the case issue doesn't seem to be the problem... however, <em>if</em> it worked (it does<strike>n't</strike>), this would be the easiest way to request the page:</p>\n\n<pre><code> using (WebClient wc = new WebClient())\n {\n string page1 = wc.DownloadString(\"http://en.wikipedia.org/wiki/Algeria\");\n\n string page2 = wc.DownloadString(\"http://en.wikipedia.org/wiki/%27Abadilah\");\n }\n</code></pre>\n\n<p><strike>I'm afraid I can't think what to do about the leading apostrophe that is breaking things...</strike></p>\n"
},
{
"answer_id": 275935,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "<p>I also got strange results ... First, the</p>\n\n<blockquote>\n <p><a href=\"http://en.wikipedia.org/wiki/\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/</a>'Abadilah</p>\n</blockquote>\n\n<p>didn't work and after some failed tries it started working.</p>\n\n<p>The second url,</p>\n\n<blockquote>\n <p><a href=\"http://en.wikipedia.org/wiki/\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/</a>'t_Zand_(Alphen-Chaam)</p>\n</blockquote>\n\n<p>always failed for me...</p>\n\n<p>The apostrophe seems to be the responsible for these problems. If you replace it with</p>\n\n<blockquote>\n <p><strong>%27</strong></p>\n</blockquote>\n\n<p>all urls work fine.</p>\n"
},
{
"answer_id": 275938,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "<p>Try escaping the special characters using <a href=\"http://www.ietf.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">Percent Encoding (paragraph 2.1)</a>. For example, a single quote is represented by <code>%27</code> in the URL (<a href=\"http://www.w3.org/International/articles/idn-and-iri/\" rel=\"nofollow noreferrer\">IRI</a>).</p>\n"
},
{
"answer_id": 1964299,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 1,
"selected": false,
"text": "<p>I'm sure the OP has this sorted by now but I've just run across the same kind of problem - intermittent 403's when downloading from wikipedia via a web client. Setting a user agent header sorts it out:</p>\n\n<pre><code>client.Headers.Add(\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35917/"
] |
Use HttpWebRequest to download web pages without key sensitive issues
|
[update: I don't know why, but both examples below now work fine! Originally I was also seeing a 403 on the page2 example. Maybe it was a server issue?]
First, `WebClient` is easier. Actually, [I've seen this before](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1393cb0a3c6728a7/258fd33c5fc96c2f). It turned out to be case sensitivity in the url when accessing wikipedia; try ensuring that you have used the same case in your request to wikipedia.
[updated] As Bruno Conde and gimel observe, using %27 should help make it consistent (the intermittent behaviour suggest that maybe some wikipedia servers are configured differently to others)
I've just checked, and in this case the case issue doesn't seem to be the problem... however, *if* it worked (it doesn't), this would be the easiest way to request the page:
```
using (WebClient wc = new WebClient())
{
string page1 = wc.DownloadString("http://en.wikipedia.org/wiki/Algeria");
string page2 = wc.DownloadString("http://en.wikipedia.org/wiki/%27Abadilah");
}
```
I'm afraid I can't think what to do about the leading apostrophe that is breaking things...
|
275,891 |
<p>I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:</p>
<pre><code><div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
}
</code></pre>
<p>Javascript:</p>
<pre><code>$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
</code></pre>
<p><strong>EDIT:</strong> I forgot to say that I had reasons not to want to use the css way.</p>
<p>And I indeed forgot to check if the DOM was loaded.</p>
|
[
{
"answer_id": 275912,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 7,
"selected": true,
"text": "<p>Your code looks fine to me.</p>\n\n<p>Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:</p>\n\n<pre><code>$(function() {\n $('.menuItem').hover( function(){\n $(this).css('background-color', '#F00');\n },\n function(){\n $(this).css('background-color', '#000');\n });\n});\n</code></pre>\n"
},
{
"answer_id": 275919,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 3,
"selected": false,
"text": "<p>This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <code><div></code>s in IE6)</p>\n\n<p>HTML:</p>\n\n<pre><code><div id=\"menu\">\n <a class=\"menuItem\" href=#>Bla</a>\n <a class=\"menuItem\" href=#>Bla</a>\n <a class=\"menuItem\" href=#>Bla</a>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.menuItem{\n height:30px;\n width:100px;\n background-color:#000;\n}\n.menuItem:hover {\n background-color:#F00;\n}\n</code></pre>\n"
},
{
"answer_id": 275932,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 3,
"selected": false,
"text": "<p><strong>test.html</strong></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!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\" xml:lang=\"en\">\n <head>\n <title>jQuery Test</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\" src=\"test.js\"></script>\n </head>\n <body>\n <div id=\"menu\">\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n </div>\n </body>\n</html>\n</code></pre>\n\n<p><strong>test.css</strong></p>\n\n<pre><code>.menuItem\n{\n\n display: inline;\n height: 30px;\n width: 100px;\n background-color: #000;\n\n}\n</code></pre>\n\n<p><strong>test.js</strong></p>\n\n<pre><code>$( function(){\n\n $('.menuItem').hover( function(){\n\n $(this).css('background-color', '#F00');\n\n },\n function(){\n\n $(this).css('background-color', '#000');\n\n });\n\n});\n</code></pre>\n\n<p><strong>Works :-)</strong></p>\n"
},
{
"answer_id": 275936,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 5,
"selected": false,
"text": "<p>I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.</p>\n\n<p>You can use the \":hover\" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an \"a\" element.</p>\n\n<pre><code>.menuItem\n{\n display: inline;\n background-color: #000;\n\n /* width and height should not work on inline elements */\n /* if this works, your browser is doing the rendering */\n /* in quirks mode which will not be compatible with */\n /* other browsers - but this will not work on touch mobile devices like android */\n\n}\n.menuItem a:hover \n{\n background-color:#F00;\n}\n</code></pre>\n"
},
{
"answer_id": 275947,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.</p>\n\n<p>Don't forget to add <code>display: block ;</code> in <code>.menuItem</code>, so height and width are taken into account.</p>\n\n<p>edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use <code>$(...).addClass(\"myclass\")</code> and <code>$(...).removeClass(\"myclass\")</code></p>\n"
},
{
"answer_id": 276025,
"author": "Justin Lucente",
"author_id": 35773,
"author_profile": "https://Stackoverflow.com/users/35773",
"pm_score": 3,
"selected": false,
"text": "<p>Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:</p>\n\n<p>HTML:</p>\n\n<pre><code> <ul id=\"menu\">\n <li><a href=\"#\">Bla</a></li>\n <li><a href=\"#\">Bla</a></li>\n <li><a href=\"#\">Bla</a></li>\n </ul>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#menu {\n margin: 0;\n}\n#menu li {\n float: left;\n list-style: none;\n margin: 0;\n}\n#menu li a {\n display: block;\n line-height:30px;\n width:100px;\n background-color:#000;\n}\n#menu li a:hover {\n background-color:#F00;\n}\n</code></pre>\n"
},
{
"answer_id": 276521,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 2,
"selected": false,
"text": "<p>On a side note this is more efficient:</p>\n\n<pre><code>$(\".menuItem\").hover(function(){\n this.style.backgroundColor = \"#F00\";\n}, function() {\n this.style.backgroundColor = \"#000\";\n});\n</code></pre>\n"
},
{
"answer_id": 633316,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery</p>\n\n<p><a href=\"http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/\" rel=\"nofollow noreferrer\">http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/</a></p>\n"
},
{
"answer_id": 2016242,
"author": "Joberror",
"author_id": 245030,
"author_profile": "https://Stackoverflow.com/users/245030",
"pm_score": 0,
"selected": false,
"text": "<p>Always keep things easy and simple by creating a class</p>\n\n<p>.bcolor{ background:#F00; }</p>\n\n<p>THEN USE THE addClass() & removeClass() to finish it up</p>\n"
},
{
"answer_id": 5018641,
"author": "Greg",
"author_id": 619965,
"author_profile": "https://Stackoverflow.com/users/619965",
"pm_score": 1,
"selected": false,
"text": "<p>If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:</p>\n\n<p>I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...</p>\n\n<pre><code>function changeAttr(attrName,changeThis,toThis){\n var mysheet=document.styleSheets[1], targetrule;\n var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;\n\n for (i=0; i<myrules.length; i++){\n if(myrules[i].selectorText.toLowerCase()==\".daymark:hover\"){ //find \"a:hover\" rule\n targetrule=myrules[i];\n break;\n }\n }\n switch(changeThis)\n {\n case \"height\":\n targetrule.style.height=toThis+\"px\";\n break;\n case \"width\":\n targetrule.style.width=toThis+\"px\";\n break;\n }\n\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35197/"
] |
I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:
```
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
```
CSS:
```
.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
}
```
Javascript:
```
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
```
**EDIT:** I forgot to say that I had reasons not to want to use the css way.
And I indeed forgot to check if the DOM was loaded.
|
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
```
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
```
|
275,920 |
<p>I have been trying to set up my Beta 1 MVC app on IIS 6 and cannot get it to run correctly. I have added a Wildcard mapping to the .net isapi DLL as suggested in other blog posts but get the following error when I access the root of the website:</p>
<pre><code>The incoming request does not match any route.
..
[HttpException (0x80004005): The incoming request does not match any route.]
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +147
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +36
System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4
HCD.Intranet.Web.Default.Page_Load(Object sender, EventArgs e) +81
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
</code></pre>
<p>I am using the Default.aspx page supplied in the MVC template application that rewrites access to the root of the website properly.</p>
<pre><code>public partial class Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
HttpContext.Current.RewritePath(Request.ApplicationPath);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
}
</code></pre>
<p>If I try and access a route within the application, such as /Project, I get the standard IIS 404 error page, not the .net error page.</p>
<p>I tried adding the following line to my Web.config httpHandlers section:</p>
<pre><code><add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</code></pre>
<p>This gave me a different error - the .net 404 error page.</p>
<p>I added the following to my Global.asax, which did nothing:</p>
<pre><code>protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Context.Request.FilePath.Equals("/"))
Context.RewritePath("Default.aspx");
}
</code></pre>
<p>I am using the following route configuration (uses the restful routing supplied by the MvcContrib project):</p>
<pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
SimplyRestfulRouteHandler.BuildRoutes(routes);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
</code></pre>
<p>Any suggestions would be grealy received as I've exhausted all options for the time I have right now.</p>
<p>Many thanks.</p>
|
[
{
"answer_id": 275928,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunatly IIS 6 needs a file extension to map the request to the right handler which means you will have to use the .mvc suffix on your controller names, such as <em>/{controller}.mvc/{action}</em></p>\n\n<pre><code>routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\nSimplyRestfulRouteHandler.BuildRoutes(routes);\n\nroutes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{id}\",\n new { controller = \"Home\", action = \"Index\", id = \"\" }\n);\n</code></pre>\n\n<p>However, the are ways around this depending on your level of control on the IIS 6 server. Please refer to the following pages for more information</p>\n\n<ul>\n<li><a href=\"http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/\" rel=\"nofollow noreferrer\">http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/</a></li>\n<li><a href=\"http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx\" rel=\"nofollow noreferrer\">http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx</a></li>\n</ul>\n"
},
{
"answer_id": 279386,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 4,
"selected": false,
"text": "<p>Here's what I did to get extensionless URLs working with IIS 6 and ASP.NET MVC Beta 1.</p>\n\n<ul>\n<li>Create a default ASP.NET MVC Beta\nproject and compile it.</li>\n<li>Create a new IIS website pointing to\nthe application directory.</li>\n<li>In the IIS properties for the\nwebsite, click the HomeDirectory\ntab.</li>\n<li>Click the \"Configuration...\" button.\nIn the \"Mappings\" tab, click\n\"Insert...\"</li>\n<li>Next to the \"Wildcard application\nmaps\" label In the textbox, type in\n\"c:\\windows\\microsoft.net\\framework\\v2.0.50727\\aspnet_isapi.dll\"</li>\n<li>Uncheck the box labelled \"Verify\nthat file exists\" Click OK</li>\n<li>Navigate to /home It worked!</li>\n</ul>\n\n<p>You shouldn't need to change web.config at all. You just need to map all requests to IIS to the ASP.NET Isapi dll otherwise ASP.NET will never get those requests.</p>\n"
},
{
"answer_id": 283840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>OK, got it working.</p>\n\n<p>The problem was that I was using msbuild automation to package up the files that I needed to deploy, and I was missing global.asax.</p>\n\n<p>So it looks like if global.asax is not deployed to the site then none of the routes get hooked up. This means that hitting the website root correctly results in the error 'The incoming request does not match any route.', and any other requests no longer get routed through to your controller classes, so result in a 404.</p>\n\n<p>HTH.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31412/"
] |
I have been trying to set up my Beta 1 MVC app on IIS 6 and cannot get it to run correctly. I have added a Wildcard mapping to the .net isapi DLL as suggested in other blog posts but get the following error when I access the root of the website:
```
The incoming request does not match any route.
..
[HttpException (0x80004005): The incoming request does not match any route.]
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +147
System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +36
System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4
HCD.Intranet.Web.Default.Page_Load(Object sender, EventArgs e) +81
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
```
I am using the Default.aspx page supplied in the MVC template application that rewrites access to the root of the website properly.
```
public partial class Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
HttpContext.Current.RewritePath(Request.ApplicationPath);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
}
```
If I try and access a route within the application, such as /Project, I get the standard IIS 404 error page, not the .net error page.
I tried adding the following line to my Web.config httpHandlers section:
```
<add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
```
This gave me a different error - the .net 404 error page.
I added the following to my Global.asax, which did nothing:
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Context.Request.FilePath.Equals("/"))
Context.RewritePath("Default.aspx");
}
```
I am using the following route configuration (uses the restful routing supplied by the MvcContrib project):
```
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
SimplyRestfulRouteHandler.BuildRoutes(routes);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
```
Any suggestions would be grealy received as I've exhausted all options for the time I have right now.
Many thanks.
|
OK, got it working.
The problem was that I was using msbuild automation to package up the files that I needed to deploy, and I was missing global.asax.
So it looks like if global.asax is not deployed to the site then none of the routes get hooked up. This means that hitting the website root correctly results in the error 'The incoming request does not match any route.', and any other requests no longer get routed through to your controller classes, so result in a 404.
HTH.
|
275,927 |
<p>I have a form that tries to modify a JComponent's graphics context. I use, for example,</p>
<pre><code>((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5));
</code></pre>
<p>Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?</p>
<p>Thanks,</p>
<p>Vlad</p>
|
[
{
"answer_id": 276388,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": 3,
"selected": true,
"text": "<p>There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.</p>\n\n<p>What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:</p>\n\n<p><a href=\"http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html\" rel=\"nofollow noreferrer\"><a href=\"http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html\" rel=\"nofollow noreferrer\">http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html</a></a></p>\n"
},
{
"answer_id": 276522,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Nobody to answer? I have let some time to see if there is any good answer before mine: I am not a specialist of such question...</p>\n\n<p>First, I don't fully understand your question: you change a setting then close the form?</p>\n\n<p>Anyway, I am not too sure, but somewhere in the process, the graphics context might be recomputed or taken from default. Perhaps if you do this operation in the paint() method, you can get some result, although I am not sure.</p>\n\n<p>For a number of changes, you usually use a decorator. I explored a bit this topic when answering a question on SO: <a href=\"https://stackoverflow.com/questions/138793/how-do-i-add-a-separator-to-a-jcombobox-in-java#139366\" title=\"How do I add a separator to a JComboBox in Java?\">How do I add a separator to a JComboBox in Java?</a>. I had to paint my own border there (asymmetrical), but often you just take an existing one, so it is quite simple.</p>\n\n<p>I hope I provided some information, if it didn't helped, perhaps you should give more details on what you want to do (and perhaps a simple, minimal program illustrating your problem).</p>\n"
},
{
"answer_id": 277769,
"author": "Vlad Dogaru",
"author_id": 1155998,
"author_profile": "https://Stackoverflow.com/users/1155998",
"pm_score": 0,
"selected": false,
"text": "<p>OK, I've worked around the problem like this: The custom JComponent now holds a Stroke object, which is set by the \"Choose stroke\" form when the user clicks OK. Then, in the paint method of the JComponent, I set the stroke of the graphics context passed as parameter to paint to the one contained in the object. </p>\n\n<p>I have experimented and found out that, for some reason, JComponent.getGraphics().set* doesn't work.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1155998/"
] |
I have a form that tries to modify a JComponent's graphics context. I use, for example,
```
((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5));
```
Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?
Thanks,
Vlad
|
There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.
What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:
[<http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html>](http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html)
|
275,931 |
<p>I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element — ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?</p>
|
[
{
"answer_id": 275942,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>Would a <del><a href=\"http://enhance.qd-creative.co.uk/demos/pulse/\" rel=\"nofollow noreferrer\">pulse effect</a></del>(offline) JQuery plugin be appropriate for what you are looking for ?</p>\n\n<p>You can add a duration for limiting the pulse effect in time.</p>\n\n<hr>\n\n<p>As mentioned by <strong><a href=\"https://stackoverflow.com/users/21677/j-p\">J-P</a></strong> in the comments, there is now <em>his</em> <a href=\"http://james.padolsey.com/javascript/simple-pulse-plugin-for-jquery/\" rel=\"nofollow noreferrer\">updated pulse plugin</a>.<br>\nSee his <a href=\"https://github.com/padolsey/jQuery-Plugins/tree/master/pulse\" rel=\"nofollow noreferrer\">GitHub repo</a>. And here is <a href=\"http://jsfiddle.net/9sWRT/207/\" rel=\"nofollow noreferrer\">a demo</a>.</p>\n"
},
{
"answer_id": 275943,
"author": "Michiel Overeem",
"author_id": 5043,
"author_profile": "https://Stackoverflow.com/users/5043",
"pm_score": 6,
"selected": false,
"text": "<p>You could use the <a href=\"http://docs.jquery.com/UI/Effects/Highlight\" rel=\"noreferrer\">highlight effect</a> in jQuery UI to achieve the same, I guess.</p>\n"
},
{
"answer_id": 275953,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 4,
"selected": false,
"text": "<p>You could use this plugin (put it in a js file and use it via script-tag)</p>\n\n<p><a href=\"http://plugins.jquery.com/project/color\" rel=\"noreferrer\">http://plugins.jquery.com/project/color</a></p>\n\n<p>And then use something like this:</p>\n\n<pre><code>jQuery.fn.flash = function( color, duration )\n{\n\n var current = this.css( 'color' );\n\n this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );\n this.animate( { color: current }, duration / 2 );\n\n}\n</code></pre>\n\n<p>This adds a 'flash' method to all jQuery objects:</p>\n\n<pre><code>$( '#importantElement' ).flash( '255,0,0', 1000 );\n</code></pre>\n"
},
{
"answer_id": 1145719,
"author": "curthipster",
"author_id": 139262,
"author_profile": "https://Stackoverflow.com/users/139262",
"pm_score": 7,
"selected": false,
"text": "<p>You can use the <a href=\"https://github.com/jquery/jquery-color\" rel=\"noreferrer\" title=\"jQuery Color on GitHub\">jQuery Color plugin</a>.</p>\n\n<p>For example, to draw attention to all the divs on your page, you could use the following code:</p>\n\n<pre><code>$(\"div\").stop().css(\"background-color\", \"#FFFF9C\")\n .animate({ backgroundColor: \"#FFFFFF\"}, 1500);\n</code></pre>\n\n<p><strong>Edit - New and improved</strong></p>\n\n<p>The following uses the same technique as above, but it has the added benefits of:</p>\n\n<ul>\n<li>parameterized highlight color and duration</li>\n<li>retaining original background color, instead of assuming that it is white</li>\n<li>being an extension of jQuery, so you can use it on any object</li>\n</ul>\n\n<p>Extend the jQuery Object:</p>\n\n<pre><code>var notLocked = true;\n$.fn.animateHighlight = function(highlightColor, duration) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n var originalBg = this.css(\"backgroundColor\");\n if (notLocked) {\n notLocked = false;\n this.stop().css(\"background-color\", highlightBg)\n .animate({backgroundColor: originalBg}, animateMs);\n setTimeout( function() { notLocked = true; }, animateMs);\n }\n};\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>$(\"div\").animateHighlight(\"#dd0000\", 1000);\n</code></pre>\n"
},
{
"answer_id": 4672402,
"author": "SooDesuNe",
"author_id": 64709,
"author_profile": "https://Stackoverflow.com/users/64709",
"pm_score": 6,
"selected": false,
"text": "<p>If you're using jQueryUI, there is <code>pulsate</code> function in <code>UI/Effects</code></p>\n\n<pre><code>$(\"div\").click(function () {\n $(this).effect(\"pulsate\", { times:3 }, 2000);\n});\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/UI/Effects/Pulsate\" rel=\"noreferrer\">http://docs.jquery.com/UI/Effects/Pulsate</a></p>\n"
},
{
"answer_id": 6602513,
"author": "danlee",
"author_id": 529733,
"author_profile": "https://Stackoverflow.com/users/529733",
"pm_score": 2,
"selected": false,
"text": "<p>There is a workaround for the animate background bug. This gist includes an example of a simple highlight method and its use.</p>\n\n<pre><code>/* BEGIN jquery color */\n (function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(!fx.colorInit){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);fx.colorInit=true;}\n fx.elem.style[attr]=\"rgb(\"+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(\",\")+\")\";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)\n return color;if(result=/rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(color))\n return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(color))\n return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))\n return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))\n return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\\(0, 0, 0, 0\\)/.exec(color))\n return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()];}\n function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,\"body\"))\n break;attr=\"backgroundColor\";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};})(jQuery);\n /* END jquery color */\n\n\n /* BEGIN highlight */\n jQuery(function() {\n $.fn.highlight = function(options) {\n options = (options) ? options : {start_color:\"#ff0\",end_color:\"#fff\",delay:1500};\n $(this).each(function() {\n $(this).stop().css({\"background-color\":options.start_color}).animate({\"background-color\":options.end_color},options.delay);\n });\n }\n });\n /* END highlight */\n\n /* BEGIN highlight example */\n $(\".some-elements\").highlight();\n /* END highlight example */\n</code></pre>\n\n<p><a href=\"https://gist.github.com/1068231\" rel=\"nofollow\">https://gist.github.com/1068231</a></p>\n"
},
{
"answer_id": 7501372,
"author": "RicardO",
"author_id": 482526,
"author_profile": "https://Stackoverflow.com/users/482526",
"pm_score": 0,
"selected": false,
"text": "<p>I am using this one. though not yet tested on all browser. \njust modify this in the way you like,</p>\n\n<p>usage: <code>hlight($(\"#mydiv\"));</code></p>\n\n<pre><code>function hlight(elementid){\n var hlight= \"#fe1414\"; //set the hightlight color\n var aspeed= 2000; //set animation speed\n var orig= \"#ffffff\"; // set default background color\n elementid.stop().css(\"background-color\", hlight).animate({backgroundColor: orig}, aspeed);\n}\n</code></pre>\n\n<p>NOTE: you need a jquery UI added to your header.</p>\n"
},
{
"answer_id": 7549125,
"author": "bthemonarch",
"author_id": 964126,
"author_profile": "https://Stackoverflow.com/users/964126",
"pm_score": 3,
"selected": false,
"text": "<p>I can't believe this isn't on this question yet. All you gotta do: </p>\n\n<pre><code>(\"#someElement\").show('highlight',{color: '#C8FB5E'},'fast');\n</code></pre>\n\n<p>This does exactly what you want it to do, is super easy, works for both <code>show()</code> and <code>hide()</code> methods. </p>\n"
},
{
"answer_id": 8621313,
"author": "th3byrdm4n",
"author_id": 362716,
"author_profile": "https://Stackoverflow.com/users/362716",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a slightly improved version of colbeerhey's solution. I added a return statement so that, in true jQuery form, we chain events after calling the animation. I've also added the arguments to clear the queue and jump to the end of an animation. </p>\n\n<pre><code>// Adds a highlight effect\n$.fn.animateHighlight = function(highlightColor, duration) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n this.stop(true,true);\n var originalBg = this.css(\"backgroundColor\");\n return this.css(\"background-color\", highlightBg).animate({backgroundColor: originalBg}, animateMs);\n};\n</code></pre>\n"
},
{
"answer_id": 9097349,
"author": "etlds",
"author_id": 801790,
"author_profile": "https://Stackoverflow.com/users/801790",
"pm_score": 9,
"selected": false,
"text": "<p>My way is .fadein, .fadeout .fadein, .fadeout ......</p>\n\n<pre><code>$(\"#someElement\").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function go1() { $(\"#demo1\").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}\r\n\r\nfunction go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#demo1,\r\n#demo2 {\r\n text-align: center;\r\n font-family: Helvetica;\r\n background: IndianRed;\r\n height: 50px;\r\n line-height: 50px;\r\n width: 150px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\r\n<button onclick=\"go1()\">Click Me</button>\r\n<div id='demo1'>My Element</div>\r\n<br>\r\n<button onclick=\"go2()\">Click Me</button> (from comment)\r\n<div id='demo2'>My Element</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 11054415,
"author": "Rob Evans",
"author_id": 599020,
"author_profile": "https://Stackoverflow.com/users/599020",
"pm_score": 4,
"selected": false,
"text": "<p>You can extend Desheng Li's method further by allowing an iterations count to do multiple flashes like so:</p>\n\n<pre><code>// Extend jquery with flashing for elements\n$.fn.flash = function(duration, iterations) {\n duration = duration || 1000; // Default to 1 second\n iterations = iterations || 1; // Default to 1 iteration\n var iterationDuration = Math.floor(duration / iterations);\n\n for (var i = 0; i < iterations; i++) {\n this.fadeOut(iterationDuration).fadeIn(iterationDuration);\n }\n return this;\n}\n</code></pre>\n\n<p>Then you can call the method with a time and number of flashes:</p>\n\n<pre><code>$(\"#someElementId\").flash(1000, 4); // Flash 4 times over a period of 1 second\n</code></pre>\n"
},
{
"answer_id": 11174405,
"author": "Gene Kelly",
"author_id": 1477540,
"author_profile": "https://Stackoverflow.com/users/1477540",
"pm_score": 2,
"selected": false,
"text": "<p>If including a library is overkill here is a solution that is guaranteed to work.</p>\n<pre><code>$('div').click(function() {\n $(this).css('background-color','#FFFFCC');\n setTimeout(function() { $(this).fadeOut('slow').fadeIn('slow'); } , 1000); \n setTimeout(function() { $(this).css('background-color','#FFFFFF'); } , 1000); \n});\n</code></pre>\n<ol>\n<li><p>Setup event trigger</p>\n</li>\n<li><p>Set the background color of block element</p>\n</li>\n<li><p>Inside setTimeout use fadeOut and fadeIn to create a little animation effect.</p>\n</li>\n<li><p>Inside second setTimeout reset default background color</p>\n<p>Tested in a few browsers and it works nicely.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 11915453,
"author": "vinay",
"author_id": 428302,
"author_profile": "https://Stackoverflow.com/users/428302",
"pm_score": 7,
"selected": false,
"text": "<p>You can use css3 animations to flash an element </p>\n\n<pre><code>.flash {\n -moz-animation: flash 1s ease-out;\n -moz-animation-iteration-count: 1;\n\n -webkit-animation: flash 1s ease-out;\n -webkit-animation-iteration-count: 1;\n\n -ms-animation: flash 1s ease-out;\n -ms-animation-iteration-count: 1;\n}\n\n@keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-webkit-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-moz-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-ms-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n</code></pre>\n\n<p>And you jQuery to add the class</p>\n\n<pre><code>jQuery(selector).addClass(\"flash\");\n</code></pre>\n"
},
{
"answer_id": 12808148,
"author": "sporkit",
"author_id": 1732979,
"author_profile": "https://Stackoverflow.com/users/1732979",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$('#district').css({opacity: 0});\n$('#district').animate({opacity: 1}, 700 );\n</code></pre>\n"
},
{
"answer_id": 13132816,
"author": "Sankglory",
"author_id": 1784582,
"author_profile": "https://Stackoverflow.com/users/1784582",
"pm_score": 2,
"selected": false,
"text": "<p>The following codes work for me. Define two fade-in and fade-out functions and put them in each other's callback.</p>\n\n<pre><code>var fIn = function() { $(this).fadeIn(300, fOut); };\nvar fOut = function() { $(this).fadeOut(300, fIn); };\n$('#element').fadeOut(300, fIn);\n</code></pre>\n\n<p>The following controls the times of flashes:</p>\n\n<pre><code>var count = 3;\nvar fIn = function() { $(this).fadeIn(300, fOut); };\nvar fOut = function() { if (--count > 0) $(this).fadeOut(300, fIn); };\n$('#element').fadeOut(300, fIn);\n</code></pre>\n"
},
{
"answer_id": 14820860,
"author": "rcd",
"author_id": 642093,
"author_profile": "https://Stackoverflow.com/users/642093",
"pm_score": 3,
"selected": false,
"text": "<p>This may be a more up-to-date answer, and is shorter, as things have been consolidated somewhat since this post. Requires <strong>jquery-ui-effect-highlight</strong>.</p>\n\n<pre><code>$(\"div\").click(function () {\n $(this).effect(\"highlight\", {}, 3000);\n});\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/UI/Effects/Highlight\">http://docs.jquery.com/UI/Effects/Highlight</a></p>\n"
},
{
"answer_id": 17780161,
"author": "phillyd",
"author_id": 2605557,
"author_profile": "https://Stackoverflow.com/users/2605557",
"pm_score": 3,
"selected": false,
"text": "<p>Found this many moons later but if anyone cares, it seems like this is a nice way to get something to flash permanently:</p>\n\n<pre><code>$( \"#someDiv\" ).hide();\n\nsetInterval(function(){\n $( \"#someDiv\" ).fadeIn(1000).fadeOut(1000);\n},0)\n</code></pre>\n"
},
{
"answer_id": 18383287,
"author": "Cauêh Q.",
"author_id": 2707793,
"author_profile": "https://Stackoverflow.com/users/2707793",
"pm_score": 0,
"selected": false,
"text": "<p>This function makes it blink.\nIt must use cssHooks, because of the rgb default return of <strong>background-color</strong> function.</p>\n\n<p>Hope it helps!</p>\n\n<pre><code>$.cssHooks.backgroundColor = {\nget: function(elem) {\n if (elem.currentStyle)\n var bg = elem.currentStyle[\"backgroundColor\"];\n else if (window.getComputedStyle)\n var bg = document.defaultView.getComputedStyle(elem,\n null).getPropertyValue(\"background-color\");\n if (bg.search(\"rgb\") == -1)\n return bg;\n else {\n bg = bg.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/);\n function hex(x) {\n return (\"0\" + parseInt(x).toString(16)).slice(-2);\n }\n return \"#\" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);\n }\n}\n}\nfunction blink(element,blinkTimes,color,originalColor){\n var changeToColor;\n if(blinkTimes === null || blinkTimes === undefined)\n blinkTimes = 1;\n if(!originalColor || originalColor === null || originalColor === undefined)\n originalColor = $(element).css(\"backgroundColor\");\n if(!color || color === null || color === undefined)\n color = \"#ffffdf\";\n if($(element).css(\"backgroundColor\") == color){\n changeToColor = originalColor;\n }else{\n changeToColor = color;\n --blinkTimes;\n }\n if(blinkTimes >= 0){\n $(element).animate({\n \"background-color\": changeToColor,\n }, {\n duration: 500,\n complete: function() {\n blink(element, blinkTimes, color, originalColor);\n return true;\n }\n });\n }else{\n $(element).removeAttr(\"style\");\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 19083993,
"author": "SoEzPz",
"author_id": 2063096,
"author_profile": "https://Stackoverflow.com/users/2063096",
"pm_score": 3,
"selected": false,
"text": "<p>I was looking for a solution to this problem but without relying on jQuery UI. </p>\n\n<p>This is what I came up with and it works for me (no plugins, just Javascript and jQuery);\n-- Heres the working fiddle -- <a href=\"http://jsfiddle.net/CriddleCraddle/yYcaY/2/\" rel=\"noreferrer\">http://jsfiddle.net/CriddleCraddle/yYcaY/2/</a> </p>\n\n<p>Set the current CSS parameter in your CSS file as normal css, and create a new class that just handles the parameter to change i.e. background-color, and set it to '!important' to override the default behavior. like this...</p>\n\n<pre><code>.button_flash {\nbackground-color: #8DABFF !important;\n}//This is the color to change to. \n</code></pre>\n\n<p>Then just use the function below and pass in the DOM element as a string, an integer for the number of times you would want the flash to occur, the class you want to change to, and an integer for delay.</p>\n\n<p>Note: If you pass in an even number for the 'times' variable, you will end up with the class you started with, and if you pass an odd number you will end up with the toggled class. Both are useful for different things. I use the 'i' to change the delay time, or they would all fire at the same time and the effect would be lost. </p>\n\n<pre><code>function flashIt(element, times, klass, delay){\n for (var i=0; i < times; i++){\n setTimeout(function(){\n $(element).toggleClass(klass);\n }, delay + (300 * i));\n };\n};\n\n//Then run the following code with either another delay to delay the original start, or\n// without another delay. I have provided both options below.\n\n//without a start delay just call\nflashIt('.info_status button', 10, 'button_flash', 500)\n\n//with a start delay just call\nsetTimeout(function(){\n flashIt('.info_status button', 10, 'button_flash', 500)\n}, 4700);\n// Just change the 4700 above to your liking for the start delay. In this case, \n//I need about five seconds before the flash started. \n</code></pre>\n"
},
{
"answer_id": 21761423,
"author": "TonyP",
"author_id": 3307168,
"author_profile": "https://Stackoverflow.com/users/3307168",
"pm_score": 3,
"selected": false,
"text": "<p>How about a really simple answer?</p>\n\n<p><code>$('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1)</code></p>\n\n<p>Blinks twice...that's all folks!</p>\n"
},
{
"answer_id": 22949247,
"author": "Brad",
"author_id": 1316159,
"author_profile": "https://Stackoverflow.com/users/1316159",
"pm_score": 1,
"selected": false,
"text": "<p>This one will pulsate an element's background color until a mouseover event is triggered</p>\n\n<pre><code>$.fn.pulseNotify = function(color, duration) {\n\nvar This = $(this);\nconsole.log(This);\n\nvar pulseColor = color || \"#337\";\nvar pulseTime = duration || 3000;\nvar origBg = This.css(\"background-color\");\nvar stop = false;\n\nThis.bind('mouseover.flashPulse', function() {\n stop = true;\n This.stop();\n This.unbind('mouseover.flashPulse');\n This.css('background-color', origBg);\n})\n\nfunction loop() {\n console.log(This);\n if( !stop ) {\n This.animate({backgroundColor: pulseColor}, pulseTime/3, function(){\n This.animate({backgroundColor: origBg}, (pulseTime/3)*2, 'easeInCirc', loop);\n });\n }\n}\n\nloop();\n\nreturn This;\n}\n</code></pre>\n"
},
{
"answer_id": 23030299,
"author": "Majal",
"author_id": 2756066,
"author_profile": "https://Stackoverflow.com/users/2756066",
"pm_score": 6,
"selected": false,
"text": "<h3>After 5 years... (And no additional plugin needed)</h3>\n\n<p>This one \"pulses\" it to the color you want (e.g. white) by <strong>putting a div background</strong> color behind it, and then <strong>fading the object</strong> out and in again.</p>\n\n<p><strong>HTML</strong> object (e.g. button):</p>\n\n<pre><code><div style=\"background: #fff;\">\n <input type=\"submit\" class=\"element\" value=\"Whatever\" />\n</div>\n</code></pre>\n\n<p><strong>jQuery</strong> (vanilla, no other plugins):</p>\n\n<pre><code>$('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });\n</code></pre>\n\n<p><strong>element</strong> - class name</p>\n\n<p><strong>first number</strong> in <code>fadeTo()</code> - milliseconds for the transition</p>\n\n<p><strong>second number</strong> in <code>fadeTo()</code> - opacity of the object after fade/unfade</p>\n\n<p>You may check this out in the lower right corner of this webpage: <a href=\"https://single.majlovesreg.one/v1/\" rel=\"noreferrer\">https://single.majlovesreg.one/v1/</a></p>\n\n<p><strong>Edit</strong> (willsteel) no duplicated selector by using $(this) and tweaked values to acutally perform a flash (as the OP requested).</p>\n"
},
{
"answer_id": 23601338,
"author": "Chloe",
"author_id": 148844,
"author_profile": "https://Stackoverflow.com/users/148844",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately the top answer requires JQuery UI. <a href=\"http://api.jquery.com/animate/\" rel=\"nofollow\">http://api.jquery.com/animate/</a></p>\n\n<h1>Here is a vanilla JQuery solution</h1>\n\n<p><a href=\"http://jsfiddle.net/EfKBg/\" rel=\"nofollow\">http://jsfiddle.net/EfKBg/</a></p>\n\n<h3>JS</h3>\n\n<pre><code>var flash = \"<div class='flash'></div>\";\n$(\".hello\").prepend(flash);\n$('.flash').show().fadeOut('slow');\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>.flash {\n background-color: yellow;\n display: none;\n position: absolute;\n width: 100%;\n height: 100%;\n}\n</code></pre>\n\n<h3>HTML</h3>\n\n<pre><code><div class=\"hello\">Hello World!</div>\n</code></pre>\n"
},
{
"answer_id": 24655804,
"author": "Duncan",
"author_id": 3751876,
"author_profile": "https://Stackoverflow.com/users/3751876",
"pm_score": 1,
"selected": false,
"text": "<p>Put this together from all of the above - an easy solution for flashing an element and return to the original bgcolour...</p>\n\n<pre><code>$.fn.flash = function (highlightColor, duration, iterations) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n var originalBg = this.css('backgroundColor');\n var flashString = 'this';\n for (var i = 0; i < iterations; i++) {\n flashString = flashString + '.animate({ backgroundColor: highlightBg }, animateMs).animate({ backgroundColor: originalBg }, animateMs)';\n }\n eval(flashString);\n}\n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>$('<some element>').flash('#ffffc0', 1000, 3);\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 26268217,
"author": "Xanarus",
"author_id": 2525112,
"author_profile": "https://Stackoverflow.com/users/2525112",
"pm_score": 0,
"selected": false,
"text": "<p>Simple as the best is to do in this way :</p>\n\n<pre><code><script>\n\nsetInterval(function(){\n\n $(\".flash-it\").toggleClass(\"hide\");\n\n},700)\n</script>\n</code></pre>\n"
},
{
"answer_id": 27772902,
"author": "sffc",
"author_id": 1407170,
"author_profile": "https://Stackoverflow.com/users/1407170",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a solution that uses a mix of jQuery and CSS3 animations.</p>\n\n<p><a href=\"http://jsfiddle.net/padfv0u9/2/\" rel=\"nofollow\">http://jsfiddle.net/padfv0u9/2/</a></p>\n\n<p>Essentially you start by changing the color to your \"flash\" color, and then use a CSS3 animation to let the color fade out. You need to change the transition duration in order for the initial \"flash\" to be faster than the fade.</p>\n\n<pre><code>$(element).removeClass(\"transition-duration-medium\");\n$(element).addClass(\"transition-duration-instant\");\n$(element).addClass(\"ko-flash\");\nsetTimeout(function () {\n $(element).removeClass(\"transition-duration-instant\");\n $(element).addClass(\"transition-duration-medium\");\n $(element).removeClass(\"ko-flash\");\n}, 500);\n</code></pre>\n\n<p>Where the CSS classes are as follows.</p>\n\n<pre><code>.ko-flash {\n background-color: yellow;\n}\n.transition-duration-instant {\n -webkit-transition-duration: 0s;\n -moz-transition-duration: 0s;\n -o-transition-duration: 0s;\n transition-duration: 0s;\n}\n.transition-duration-medium {\n -webkit-transition-duration: 1s;\n -moz-transition-duration: 1s;\n -o-transition-duration: 1s;\n transition-duration: 1s;\n}\n</code></pre>\n"
},
{
"answer_id": 28297754,
"author": "shanehoban",
"author_id": 1173155,
"author_profile": "https://Stackoverflow.com/users/1173155",
"pm_score": 0,
"selected": false,
"text": "<p>Working with jQuery 1.10.2, this pulses a dropdown twice and changes the text to an error. It also stores the values for the changed attributes to reinstate them.</p>\n\n<pre><code>// shows the user an error has occurred\n$(\"#myDropdown\").fadeOut(700, function(){\n var text = $(this).find(\"option:selected\").text();\n var background = $(this).css( \"background\" );\n\n $(this).css('background', 'red');\n $(this).find(\"option:selected\").text(\"Error Occurred\");\n\n $(this).fadeIn(700, function(){\n $(this).fadeOut(700, function(){\n $(this).fadeIn(700, function(){\n $(this).fadeOut(700, function(){\n\n $(this).find(\"option:selected\").text(text);\n $(this).css(\"background\", background);\n $(this).fadeIn(700);\n })\n })\n })\n })\n});\n</code></pre>\n\n<p>Done via callbacks - to ensure no animations are missed.</p>\n"
},
{
"answer_id": 28361724,
"author": "ibsenv",
"author_id": 1952713,
"author_profile": "https://Stackoverflow.com/users/1952713",
"pm_score": 1,
"selected": false,
"text": "<p>just give elem.fadeOut(10).fadeIn(10);</p>\n"
},
{
"answer_id": 28374194,
"author": "maudulus",
"author_id": 3216297,
"author_profile": "https://Stackoverflow.com/users/3216297",
"pm_score": 0,
"selected": false,
"text": "<p>Create two classes, giving each a background color: </p>\n\n<pre><code>.flash{\n background: yellow;\n}\n\n.noflash{\n background: white;\n}\n</code></pre>\n\n<p>Create a div with one of these classes:</p>\n\n<pre><code><div class=\"noflash\"></div>\n</code></pre>\n\n<p>The following function will toggle the classes and make it appear to be flashing:</p>\n\n<pre><code>var i = 0, howManyTimes = 7;\nfunction flashingDiv() {\n $('.flash').toggleClass(\"noFlash\")\n i++;\n if( i <= howManyTimes ){\n setTimeout( f, 200 );\n }\n}\nf();\n</code></pre>\n"
},
{
"answer_id": 28527876,
"author": "Nizar B.",
"author_id": 1106312,
"author_profile": "https://Stackoverflow.com/users/1106312",
"pm_score": -1,
"selected": false,
"text": "<p>You can use this cool library to make any kind of animated effect on your element: <a href=\"http://daneden.github.io/animate.css/\" rel=\"nofollow\">http://daneden.github.io/animate.css/</a></p>\n"
},
{
"answer_id": 28658753,
"author": "NateS",
"author_id": 187883,
"author_profile": "https://Stackoverflow.com/users/187883",
"pm_score": 1,
"selected": false,
"text": "<p>This is generic enough that you can write whatever code you like to animate. You can even decrease the delay from 300ms to 33ms and fade colors, etc.</p>\n\n<pre><code>// Flash linked to hash.\nvar hash = location.hash.substr(1);\nif (hash) {\n hash = $(\"#\" + hash);\n var color = hash.css(\"color\"), count = 1;\n function hashFade () {\n if (++count < 7) setTimeout(hashFade, 300);\n hash.css(\"color\", count % 2 ? color : \"red\");\n }\n hashFade();\n}\n</code></pre>\n"
},
{
"answer_id": 28980225,
"author": "hakunin",
"author_id": 517529,
"author_profile": "https://Stackoverflow.com/users/517529",
"pm_score": 4,
"selected": false,
"text": "<h3>Pure jQuery solution.</h3>\n\n<p>(no jquery-ui/animate/color needed.)</p>\n\n<p>If all you want is that yellow \"flash\" effect without loading jquery color:</p>\n\n<pre><code>var flash = function(elements) {\n var opacity = 100;\n var color = \"255, 255, 20\" // has to be in this format since we use rgba\n var interval = setInterval(function() {\n opacity -= 3;\n if (opacity <= 0) clearInterval(interval);\n $(elements).css({background: \"rgba(\"+color+\", \"+opacity/100+\")\"});\n }, 30)\n};\n</code></pre>\n\n<p>Above script simply does 1s yellow fadeout, perfect for letting the user know the element was was updated or something similar.</p>\n\n<p>Usage:</p>\n\n<pre><code>flash($('#your-element'))\n</code></pre>\n"
},
{
"answer_id": 37345060,
"author": "Roman Losev",
"author_id": 1602375,
"author_profile": "https://Stackoverflow.com/users/1602375",
"pm_score": 2,
"selected": false,
"text": "<p>Like fadein / fadeout you could use animate css / delay</p>\n\n<pre><code>$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);\n</code></pre>\n\n<p>Simple and flexible</p>\n"
},
{
"answer_id": 38136251,
"author": "yPhil",
"author_id": 1729094,
"author_profile": "https://Stackoverflow.com/users/1729094",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function pulse() {\n $('.blink').fadeIn(300).fadeOut(500);\n}\nsetInterval(pulse, 1000);\n</code></pre>\n"
},
{
"answer_id": 39690011,
"author": "Combine",
"author_id": 2979938,
"author_profile": "https://Stackoverflow.com/users/2979938",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(\"#someElement\").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); \n</code></pre>\n\n<p>3000 is 3 seconds</p>\n\n<p>From opacity 1 it is faded to 0.3, then to 1 and so on.</p>\n\n<p>You can stack more of these. </p>\n\n<p>Only jQuery is needed. :)</p>\n"
},
{
"answer_id": 41674441,
"author": "Iman",
"author_id": 184572,
"author_profile": "https://Stackoverflow.com/users/184572",
"pm_score": 1,
"selected": false,
"text": "<p>you can use jquery Pulsate plugin to force to focus the attention on any html element with control over speed and repeatation and color.</p>\n\n<p><a href=\"https://kilianvalkhof.com/jquerypulsate\" rel=\"nofollow noreferrer\">JQuery.pulsate()</a> <sup><em>* with Demos</em></sup></p>\n\n<p>sample initializer:</p>\n\n<ul>\n<li>$(\".pulse4\").pulsate({speed:2500}) </li>\n<li>$(\".CommandBox button:visible\").pulsate({ color: \"#f00\", speed: 200, reach: 85, repeat: 15 })</li>\n</ul>\n"
},
{
"answer_id": 58101220,
"author": "Chris",
"author_id": 5786478,
"author_profile": "https://Stackoverflow.com/users/5786478",
"pm_score": 0,
"selected": false,
"text": "<p>Straight jquery, no plugins. It blinks the specified number of times, changes the background color while blinking and then changes it back.</p>\n\n<pre><code>function blink(target, count, blinkspeed, bc) {\n let promises=[];\n const b=target.css(`background-color`);\n target.css(`background-color`, bc||b);\n for (i=1; i<count; i++) {\n const blink = target.fadeTo(blinkspeed||100, .3).fadeTo(blinkspeed||100, 1.0);\n promises.push(blink);\n }\n // wait for all the blinking to finish before changing the background color back\n $.when.apply(null, promises).done(function() {\n target.css(`background-color`, b);\n });\n promises=undefined;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>blink($(`.alert-danger`), 5, 200, `yellow`);\n</code></pre>\n"
},
{
"answer_id": 59550553,
"author": "R.Akhlaghi",
"author_id": 2830315,
"author_profile": "https://Stackoverflow.com/users/2830315",
"pm_score": 0,
"selected": false,
"text": "<p>you can use this code :)\nchange mili value for change animation speed</p>\n\n<pre><code>var mili = 300\nfor (var i = 2; i < 8; i++) {\n if (i % 2 == 0) {\n $(\"#lblTransferCount\").fadeOut(mili)\n } else {\n $(\"#lblTransferCount\").fadeIn(mili)\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73336149,
"author": "teknopaul",
"author_id": 870207,
"author_profile": "https://Stackoverflow.com/users/870207",
"pm_score": 0,
"selected": false,
"text": "<p>CSS supports flashing in all major browsers</p>\n<pre><code>.flash {\n animation: flash 0.5s ease-out;\n animation-iteration-count: 10;\n}\n@keyframes flash {\n 0% { opacity: 0.5; }\n 50% { opacity: 1.0; }\n 100% { opacity: 0.5; }\n}\n</code></pre>\n<p>add this class to the element you want to flash</p>\n<pre><code>$(elem).addClass("flash");\n</code></pre>\n<p>iteration-count: 10 is how many times you want it to flash, no need to remove the class, it will stop flashing on its own.</p>\n<p>by using opacity: this works for elements of any colour as long as its not already transparent.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7961/"
] |
I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element — ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?
|
My way is .fadein, .fadeout .fadein, .fadeout ......
```
$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
```
```js
function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}
function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }
```
```css
#demo1,
#demo2 {
text-align: center;
font-family: Helvetica;
background: IndianRed;
height: 50px;
line-height: 50px;
width: 150px;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="go1()">Click Me</button>
<div id='demo1'>My Element</div>
<br>
<button onclick="go2()">Click Me</button> (from comment)
<div id='demo2'>My Element</div>
```
|
275,944 |
<p>I have the string </p>
<pre><code>a.b.c.d
</code></pre>
<p>I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.</p>
<p>(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).</p>
|
[
{
"answer_id": 275969,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": false,
"text": "<p>Sooner or later, <em>something</em> has to loop. It's far simpler for you to write the (very simple) loop than to use something like <code>split</code> which is much more powerful than you need.</p>\n\n<p>By all means encapsulate the loop in a separate method, e.g.</p>\n\n<pre><code>public static int countOccurrences(String haystack, char needle)\n{\n int count = 0;\n for (int i=0; i < haystack.length(); i++)\n {\n if (haystack.charAt(i) == needle)\n {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n\n<p>Then you don't need have the loop in your main code - but the loop has to be there somewhere.</p>\n"
},
{
"answer_id": 275975,
"author": "Yonatan Maman",
"author_id": 20065,
"author_profile": "https://Stackoverflow.com/users/20065",
"pm_score": 4,
"selected": false,
"text": "<p>here is a solution without a loop:</p>\n\n<pre><code>public static int countOccurrences(String haystack, char needle, int i){\n return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}\n\n\nSystem.out.println(\"num of dots is \"+countOccurrences(\"a.b.c.d\",'.',0));\n</code></pre>\n\n<p>well, there is a loop, but it is <strong>invisible</strong> :-)</p>\n\n<p>-- Yonatan</p>\n"
},
{
"answer_id": 275979,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 5,
"selected": false,
"text": "<pre><code>String s = \"a.b.c.d\";\nint charCount = s.length() - s.replaceAll(\"\\\\.\", \"\").length();\n</code></pre>\n\n<p>ReplaceAll(\".\") would replace all characters.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string#276062\">PhiLho's solution</a> uses ReplaceAll(\"[^.]\",\"\"), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.</p>\n"
},
{
"answer_id": 276062,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": false,
"text": "<p>I had an idea similar to Mladen, but the opposite...</p>\n\n<pre><code>String s = \"a.b.c.d\";\nint charCount = s.replaceAll(\"[^.]\", \"\").length();\nprintln(charCount);\n</code></pre>\n"
},
{
"answer_id": 276218,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Okay, inspired by Yonatan's solution, here's one which is <em>purely</em> recursive - the only library methods used are <code>length()</code> and <code>charAt()</code>, neither of which do any looping:</p>\n\n<pre><code>public static int countOccurrences(String haystack, char needle)\n{\n return countOccurrences(haystack, needle, 0);\n}\n\nprivate static int countOccurrences(String haystack, char needle, int index)\n{\n if (index >= haystack.length())\n {\n return 0;\n }\n\n int contribution = haystack.charAt(index) == needle ? 1 : 0;\n return contribution + countOccurrences(haystack, needle, index+1);\n}\n</code></pre>\n\n<p>Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.</p>\n\n<p>I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.</p>\n"
},
{
"answer_id": 276246,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 2,
"selected": false,
"text": "<p>While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char[] for performance reasons though.</p>\n\n<pre><code>public static int count( final String s, final char c ) {\n final char[] chars = s.toCharArray();\n int count = 0;\n for(int i=0; i<chars.length; i++) {\n if (chars[i] == c) {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n\n<p>Using replaceAll (that is RE) does not sound like the best way to go.</p>\n"
},
{
"answer_id": 280995,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "<p>Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.</p>\n\n<pre><code>public static int countOccurrences(CharSequeunce haystack, char needle) {\n return countOccurrences(haystack, needle, 0, haystack.length);\n}\n\n// Alternatively String.substring/subsequence use to be relatively efficient\n// on most Java library implementations, but isn't any more [2013].\nprivate static int countOccurrences(\n CharSequence haystack, char needle, int start, int end\n) {\n if (start == end) {\n return 0;\n } else if (start+1 == end) {\n return haystack.charAt(start) == needle ? 1 : 0;\n } else {\n int mid = (end+start)>>>1; // Watch for integer overflow...\n return\n countOccurrences(haystack, needle, start, mid) +\n countOccurrences(haystack, needle, mid, end);\n }\n}\n</code></pre>\n\n<p>(Disclaimer: Not tested, not compiled, not sensible.)</p>\n\n<p>Perhaps the best (single-threaded, no surrogate-pair support) way to write it:</p>\n\n<pre><code>public static int countOccurrences(String haystack, char needle) {\n int count = 0;\n for (char c : haystack.toCharArray()) {\n if (c == needle) {\n ++count;\n }\n }\n return count;\n}\n</code></pre>\n"
},
{
"answer_id": 281044,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "<p>Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:</p>\n\n<pre><code>int numDots = 0;\nif (s.charAt(0) == '.') {\n numDots++;\n}\n\nif (s.charAt(1) == '.') {\n numDots++;\n}\n\n\nif (s.charAt(2) == '.') {\n numDots++;\n}\n</code></pre>\n\n<p>...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:</p>\n\n<pre><code>create a project\nposition = 0\nwhile (not end of string) {\n write check for character at position \"position\" (see above)\n}\nwrite code to output variable \"numDots\"\ncompile program\nhand in homework\ndo not think of the loop that your \"if\"s may have been optimized and compiled to\n</code></pre>\n"
},
{
"answer_id": 665744,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a slightly different style recursion solution:</p>\n\n<pre><code>public static int countOccurrences(String haystack, char needle)\n{\n return countOccurrences(haystack, needle, 0);\n}\n\nprivate static int countOccurrences(String haystack, char needle, int accumulator)\n{\n if (haystack.length() == 0) return accumulator;\n return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);\n}\n</code></pre>\n"
},
{
"answer_id": 1815572,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 5,
"selected": false,
"text": "<p>A shorter example is</p>\n\n<pre><code>String text = \"a.b.c.d\";\nint count = text.split(\"\\\\.\",-1).length-1;\n</code></pre>\n"
},
{
"answer_id": 1816989,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 11,
"selected": true,
"text": "<p>My 'idiomatic one-liner' for this is:</p>\n\n<pre><code>int count = StringUtils.countMatches(\"a.b.c.d\", \".\");\n</code></pre>\n\n<p>Why write it yourself when it's already in <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">commons lang</a>?</p>\n\n<p>Spring Framework's oneliner for this is:</p>\n\n<pre><code>int occurance = StringUtils.countOccurrencesOf(\"a.b.c.d\", \".\");\n</code></pre>\n"
},
{
"answer_id": 3408400,
"author": "BeeCreative",
"author_id": 411112,
"author_profile": "https://Stackoverflow.com/users/411112",
"pm_score": 0,
"selected": false,
"text": "<p>Try this method:</p>\n\n<pre><code>StringTokenizer stOR = new StringTokenizer(someExpression, \"||\");\nint orCount = stOR.countTokens()-1;\n</code></pre>\n"
},
{
"answer_id": 5103934,
"author": "user496208",
"author_id": 496208,
"author_profile": "https://Stackoverflow.com/users/496208",
"pm_score": 3,
"selected": false,
"text": "<p>In case you're using Spring framework, you might also use \"StringUtils\" class.\nThe method would be \"countOccurrencesOf\".</p>\n"
},
{
"answer_id": 5813808,
"author": "Darryl Price",
"author_id": 728568,
"author_profile": "https://Stackoverflow.com/users/728568",
"pm_score": 2,
"selected": false,
"text": "<p>Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?</p>\n"
},
{
"answer_id": 6267655,
"author": "Hardest",
"author_id": 696834,
"author_profile": "https://Stackoverflow.com/users/696834",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static int countOccurrences(String container, String content){\n int lastIndex, currIndex = 0, occurrences = 0;\n while(true) {\n lastIndex = container.indexOf(content, currIndex);\n if(lastIndex == -1) {\n break;\n }\n currIndex = lastIndex + content.length();\n occurrences++;\n }\n return occurrences;\n}\n</code></pre>\n"
},
{
"answer_id": 8910767,
"author": "Andreas Wederbrand",
"author_id": 296452,
"author_profile": "https://Stackoverflow.com/users/296452",
"pm_score": 10,
"selected": false,
"text": "<p>How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.</p>\n\n<pre><code>int count = line.length() - line.replace(\".\", \"\").length();\n</code></pre>\n"
},
{
"answer_id": 9548397,
"author": "Benny Neugebauer",
"author_id": 451634,
"author_profile": "https://Stackoverflow.com/users/451634",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Complete sample:</strong></p>\n\n<pre><code>public class CharacterCounter\n{\n\n public static int countOccurrences(String find, String string)\n {\n int count = 0;\n int indexOf = 0;\n\n while (indexOf > -1)\n {\n indexOf = string.indexOf(find, indexOf + 1);\n if (indexOf > -1)\n count++;\n }\n\n return count;\n }\n}\n</code></pre>\n\n<p><strong>Call:</strong></p>\n\n<pre><code>int occurrences = CharacterCounter.countOccurrences(\"l\", \"Hello World.\");\nSystem.out.println(occurrences); // 3\n</code></pre>\n"
},
{
"answer_id": 13389003,
"author": "kassim",
"author_id": 1825248,
"author_profile": "https://Stackoverflow.com/users/1825248",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import java.util.Scanner;\n\nclass apples {\n\n public static void main(String args[]) { \n Scanner bucky = new Scanner(System.in);\n String hello = bucky.nextLine();\n int charCount = hello.length() - hello.replaceAll(\"e\", \"\").length();\n System.out.println(charCount);\n }\n}// COUNTS NUMBER OF \"e\" CHAR´s within any string input\n</code></pre>\n"
},
{
"answer_id": 14280103,
"author": "KannedFarU",
"author_id": 1096126,
"author_profile": "https://Stackoverflow.com/users/1096126",
"pm_score": 4,
"selected": false,
"text": "<p>Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:</p>\n\n<pre><code>public static int numberOf(String target, String content)\n{\n return (content.split(target).length - 1);\n}\n</code></pre>\n"
},
{
"answer_id": 16033843,
"author": "0xCAFEBABE",
"author_id": 494501,
"author_profile": "https://Stackoverflow.com/users/494501",
"pm_score": 4,
"selected": false,
"text": "<p>I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.</p>\n\n<pre><code>for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))\n</code></pre>\n\n<p>does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.</p>\n"
},
{
"answer_id": 16336288,
"author": "Shubham",
"author_id": 2170138,
"author_profile": "https://Stackoverflow.com/users/2170138",
"pm_score": 2,
"selected": false,
"text": "<p>The following source code will give you no.of occurrences of a given string in a word entered by user :- </p>\n\n<pre><code>import java.util.Scanner;\n\npublic class CountingOccurences {\n\n public static void main(String[] args) {\n\n Scanner inp= new Scanner(System.in);\n String str;\n char ch;\n int count=0;\n\n System.out.println(\"Enter the string:\");\n str=inp.nextLine();\n\n while(str.length()>0)\n {\n ch=str.charAt(0);\n int i=0;\n\n while(str.charAt(i)==ch)\n {\n count =count+i;\n i++;\n }\n\n str.substring(count);\n System.out.println(ch);\n System.out.println(count);\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17566410,
"author": "Adrian",
"author_id": 2169691,
"author_profile": "https://Stackoverflow.com/users/2169691",
"pm_score": 1,
"selected": false,
"text": "<pre><code> public static int countSubstring(String subStr, String str) {\n\n int count = 0;\n for (int i = 0; i < str.length(); i++) {\n if (str.substring(i).startsWith(subStr)) {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n"
},
{
"answer_id": 18641094,
"author": "Sergio",
"author_id": 2751435,
"author_profile": "https://Stackoverflow.com/users/2751435",
"pm_score": 1,
"selected": false,
"text": "<p>Why are you trying to avoid the loop? I mean you can't count the \"numberOf\" dots without checking every single character of the string, and if you call any function, somehow it will loop. This is, String.replace should do a loop verifying if the string appears so it can replace every single occurrence.</p>\n\n<p>If you're trying to reduce resource usage, you won't do it like that because you're creating a new String just for counting the dots.</p>\n\n<p>Now if we talk about the recursive \"enter code here\" method, someone said that it will fail due to an OutOfMemmoryException, I think he forgot StackOverflowException.</p>\n\n<p>So my method would be like this (I know it is like the others but, this problem requires the loop):</p>\n\n<pre><code>public static int numberOf(String str,int c) {\n int res=0;\n if(str==null)\n return res;\n for(int i=0;i<str.length();i++)\n if(c==str.charAt(i))\n res++;\n return res;\n}\n</code></pre>\n"
},
{
"answer_id": 19315079,
"author": "fubo",
"author_id": 1315444,
"author_profile": "https://Stackoverflow.com/users/1315444",
"pm_score": 5,
"selected": false,
"text": "<pre><code>String s = \"a.b.c.d\";\nlong result = s.chars().filter(ch -> ch == '.').count();\n</code></pre>\n"
},
{
"answer_id": 19962695,
"author": "mlchen850622",
"author_id": 2808744,
"author_profile": "https://Stackoverflow.com/users/2808744",
"pm_score": 5,
"selected": false,
"text": "<p>My 'idiomatic one-liner' solution:</p>\n\n<pre><code>int count = \"a.b.c.d\".length() - \"a.b.c.d\".replace(\".\", \"\").length();\n</code></pre>\n\n<p>Have no idea why a solution that uses StringUtils is accepted. </p>\n"
},
{
"answer_id": 23517296,
"author": "Shaban",
"author_id": 3285421,
"author_profile": "https://Stackoverflow.com/users/3285421",
"pm_score": 2,
"selected": false,
"text": "<pre><code>int count = (line.length() - line.replace(\"str\", \"\").length())/\"str\".length();\n</code></pre>\n"
},
{
"answer_id": 23874504,
"author": "Alexis C.",
"author_id": 1587046,
"author_profile": "https://Stackoverflow.com/users/1587046",
"pm_score": 4,
"selected": false,
"text": "<p>With <a href=\"/questions/tagged/java-8\" class=\"post-tag\" title=\"show questions tagged 'java-8'\" rel=\"tag\">java-8</a> you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!</p>\n\n<pre><code>public static long countOccurences(String s, char c){\n return s.chars().filter(ch -> ch == c).count();\n}\n\ncountOccurences(\"a.b.c.d\", '.'); //3\ncountOccurences(\"hello world\", 'l'); //3\n</code></pre>\n"
},
{
"answer_id": 23962604,
"author": "Arnab sen",
"author_id": 3692714,
"author_profile": "https://Stackoverflow.com/users/3692714",
"pm_score": 0,
"selected": false,
"text": "<p>What about below recursive algo.Which is also linear time.</p>\n\n<p></p>\n\n<pre><code>import java.lang.*;\nimport java.util.*;\n\nclass longestSubstr{\n\npublic static void main(String[] args){\n String s=\"ABDEFGABEF\";\n\n\n int ans=calc(s);\n\n System.out.println(\"Max nonrepeating seq= \"+ans);\n\n}\n\npublic static int calc(String s)\n{//s.s\n int n=s.length();\n int max=1;\n if(n==1)\n return 1;\n if(n==2)\n {\n if(s.charAt(0)==s.charAt(1)) return 1;\n else return 2;\n\n\n }\n String s1=s;\n String a=s.charAt(n-1)+\"\";\n s1=s1.replace(a,\"\");\n // System.out.println(s+\" \"+(n-2)+\" \"+s.substring(0,n-1));\n max=Math.max(calc(s.substring(0,n-1)),(calc(s1)+1));\n\n\nreturn max;\n}\n\n\n}\n\n\n</i>\n</code></pre>\n"
},
{
"answer_id": 25584803,
"author": "Maarten Bodewes",
"author_id": 589259,
"author_profile": "https://Stackoverflow.com/users/589259",
"pm_score": 1,
"selected": false,
"text": "<p>I see a lot of tricks and such being used. Now I'm not against beautiful tricks but personally I like to simply call the methods that are <em>meant</em> to do the work, so I've created yet another answer.</p>\n\n<p>Note that if performance is any issue, use <a href=\"https://stackoverflow.com/a/275969/589259\">Jon Skeet's answer</a> instead. This one is a bit more generalized and therefore slightly more readable in my opinion (and of course, reusable for strings and patterns).</p>\n\n<pre><code>public static int countOccurances(char c, String input) {\n return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);\n}\n\npublic static int countOccurances(String s, String input) {\n return countOccurancesOfPattern(Pattern.quote(s), input);\n}\n\npublic static int countOccurancesOfPattern(String pattern, String input) {\n Matcher m = Pattern.compile(pattern).matcher(input);\n int count = 0;\n while (m.find()) {\n count++;\n }\n return count;\n}\n</code></pre>\n"
},
{
"answer_id": 27059883,
"author": "Narendra",
"author_id": 4278285,
"author_profile": "https://Stackoverflow.com/users/4278285",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public class OccurencesInString { public static void main(String[] args) { String str = \"NARENDRA AMILINENI\"; HashMap occur = new HashMap(); int count =0; String key = null; for(int i=0;i<str.length()-1;i++){ key = String.valueOf(str.charAt(i)); if(occur.containsKey(key)){ count = (Integer)occur.get(key); occur.put(key,++count); }else{ occur.put(key,1); } } System.out.println(occur); } }\n</code></pre>\n"
},
{
"answer_id": 29150794,
"author": "The_Fresher",
"author_id": 3357185,
"author_profile": "https://Stackoverflow.com/users/3357185",
"pm_score": -1,
"selected": false,
"text": "<p>I tried to work out your question with a switch statement but I still required a for loop to parse the string . feel free to comment if I can improve the code</p>\n\n<pre><code>public class CharacterCount {\npublic static void main(String args[])\n{\n String message=\"hello how are you\";\n char[] array=message.toCharArray();\n int a=0;\n int b=0;\n int c=0;\n int d=0;\n int e=0;\n int f=0;\n int g=0;\n int h=0;\n int i=0;\n int space=0;\n int j=0;\n int k=0;\n int l=0;\n int m=0;\n int n=0;\n int o=0;\n int p=0;\n int q=0;\n int r=0;\n int s=0;\n int t=0;\n int u=0;\n int v=0;\n int w=0;\n int x=0;\n int y=0;\n int z=0;\n\n\n for(char element:array)\n {\n switch(element)\n {\n case 'a':\n a++;\n break;\n case 'b':\n b++;\n break;\n case 'c':c++;\n break;\n\n case 'd':d++;\n break;\n case 'e':e++;\n break;\n case 'f':f++;\n break;\n\n case 'g':g++;\n break;\n case 'h':\n h++;\n break;\n case 'i':i++;\n break;\n case 'j':j++;\n break;\n case 'k':k++;\n break;\n case 'l':l++;\n break;\n case 'm':m++;\n break;\n case 'n':m++;\n break;\n case 'o':o++;\n break;\n case 'p':p++;\n break;\n case 'q':q++;\n break;\n case 'r':r++;\n break;\n case 's':s++;\n break;\n case 't':t++;\n break;\n case 'u':u++;\n break;\n case 'v':v++;\n break;\n case 'w':w++;\n break;\n case 'x':x++;\n break;\n case 'y':y++;\n break;\n case 'z':z++;\n break;\n case ' ':space++;\n break;\n default :break;\n }\n }\n System.out.println(\"A \"+a+\" B \"+ b +\" C \"+c+\" D \"+d+\" E \"+e+\" F \"+f+\" G \"+g+\" H \"+h);\n System.out.println(\"I \"+i+\" J \"+j+\" K \"+k+\" L \"+l+\" M \"+m+\" N \"+n+\" O \"+o+\" P \"+p);\n System.out.println(\"Q \"+q+\" R \"+r+\" S \"+s+\" T \"+t+\" U \"+u+\" V \"+v+\" W \"+w+\" X \"+x+\" Y \"+y+\" Z \"+z);\n System.out.println(\"SPACE \"+space);\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 32294112,
"author": "Bismaya Kumar Biswal",
"author_id": 4793394,
"author_profile": "https://Stackoverflow.com/users/4793394",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code:</p>\n\n<pre><code>package com.java.test;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class TestCuntstring {\n\n public static void main(String[] args) {\n\n String name = \"Bissssmmayaa\";\n char[] ar = new char[name.length()];\n for (int i = 0; i < name.length(); i++) {\n ar[i] = name.charAt(i);\n }\n Map<Character, String> map=new HashMap<Character, String>();\n for (int i = 0; i < ar.length; i++) {\n int count=0;\n for (int j = 0; j < ar.length; j++) {\n if(ar[i]==ar[j]){\n count++;\n }\n }\n map.put(ar[i], count+\" no of times\");\n }\n System.out.println(map);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 34801971,
"author": "Christoph Zabinski",
"author_id": 1787945,
"author_profile": "https://Stackoverflow.com/users/1787945",
"pm_score": 2,
"selected": false,
"text": "<p>Well, with a quite similar task I stumbled upon this Thread. \nI did not see any programming language restriction and since groovy runs on a java vm: \nHere is how I was able to solve my Problem using Groovy.</p>\n\n<pre><code>\"a.b.c.\".count(\".\")\n</code></pre>\n\n<p>done. </p>\n"
},
{
"answer_id": 35242882,
"author": "Slava Vedenin",
"author_id": 4318868,
"author_profile": "https://Stackoverflow.com/users/4318868",
"pm_score": 8,
"selected": false,
"text": "<p>Summarize other answer and what I know all ways to do this using a one-liner:</p>\n\n<pre><code> String testString = \"a.b.c.d\";\n</code></pre>\n\n<p>1) Using <strong>Apache Commons</strong></p>\n\n<pre><code>int apache = StringUtils.countMatches(testString, \".\");\nSystem.out.println(\"apache = \" + apache);\n</code></pre>\n\n<p>2) Using <strong>Spring Framework's</strong></p>\n\n<pre><code>int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, \".\");\nSystem.out.println(\"spring = \" + spring);\n</code></pre>\n\n<p>3) Using <strong>replace</strong></p>\n\n<pre><code>int replace = testString.length() - testString.replace(\".\", \"\").length();\nSystem.out.println(\"replace = \" + replace);\n</code></pre>\n\n<p>4) Using <strong>replaceAll</strong> (case 1)</p>\n\n<pre><code>int replaceAll = testString.replaceAll(\"[^.]\", \"\").length();\nSystem.out.println(\"replaceAll = \" + replaceAll);\n</code></pre>\n\n<p>5) Using <strong>replaceAll</strong> (case 2)</p>\n\n<pre><code>int replaceAllCase2 = testString.length() - testString.replaceAll(\"\\\\.\", \"\").length();\nSystem.out.println(\"replaceAll (second case) = \" + replaceAllCase2);\n</code></pre>\n\n<p>6) Using <strong>split</strong></p>\n\n<pre><code>int split = testString.split(\"\\\\.\",-1).length-1;\nSystem.out.println(\"split = \" + split);\n</code></pre>\n\n<p>7) Using <strong>Java8</strong> (case 1)</p>\n\n<pre><code>long java8 = testString.chars().filter(ch -> ch =='.').count();\nSystem.out.println(\"java8 = \" + java8);\n</code></pre>\n\n<p>8) Using <strong>Java8</strong> (case 2), may be better for unicode than case 1</p>\n\n<pre><code>long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();\nSystem.out.println(\"java8 (second case) = \" + java8Case2);\n</code></pre>\n\n<p>9) Using <strong>StringTokenizer</strong></p>\n\n<pre><code>int stringTokenizer = new StringTokenizer(\" \" +testString + \" \", \".\").countTokens()-1;\nSystem.out.println(\"stringTokenizer = \" + stringTokenizer);\n</code></pre>\n\n<p><strong>From comment</strong>: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once</p>\n\n<p>More info in <a href=\"https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/FindCountOfOccurrencesBenchmark.java\">github</a></p>\n\n<p><a href=\"https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/FindCountOfOccurrencesBenchmark.java\">Perfomance test</a> (using <a href=\"http://openjdk.java.net/projects/code-tools/jmh/\">JMH</a>, mode = AverageTime, score <code>0.010</code> better then <code>0.351</code>): </p>\n\n<pre><code>Benchmark Mode Cnt Score Error Units\n1. countMatches avgt 5 0.010 ± 0.001 us/op\n2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op\n3. stringTokenizer avgt 5 0.028 ± 0.002 us/op\n4. java8_1 avgt 5 0.077 ± 0.005 us/op\n5. java8_2 avgt 5 0.078 ± 0.003 us/op\n6. split avgt 5 0.137 ± 0.009 us/op\n7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op\n8. replace avgt 5 0.303 ± 0.034 us/op\n9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op\n</code></pre>\n"
},
{
"answer_id": 37317254,
"author": "user3322553",
"author_id": 3322553,
"author_profile": "https://Stackoverflow.com/users/3322553",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the <code>split()</code> function in just one line code </p>\n\n<pre><code>int noOccurence=string.split(\"#\",-1).length-1;\n</code></pre>\n"
},
{
"answer_id": 43627604,
"author": "Ashish Jaiswal",
"author_id": 7316914,
"author_profile": "https://Stackoverflow.com/users/7316914",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to count the no. of same character in a string 'SELENIUM' or you want to print the unique characters of the string 'SELENIUM'.</p>\n\n<pre><code>public class Count_Characters_In_String{\n\n public static void main(String []args){\n\n String s = \"SELENIUM\";\n System.out.println(s);\n int counter;\n\n String g = \"\";\n\n for( int i=0; i<s.length(); i++ ) { \n\n if(g.indexOf(s.charAt(i)) == - 1){\n g=g+s.charAt(i); \n }\n\n }\n System.out.println(g + \" \");\n\n\n\n for( int i=0; i<g.length(); i++ ) { \n System.out.print(\",\");\n\n System.out.print(s.charAt(i)+ \" : \");\n counter=0; \n for( int j=0; j<s.length(); j++ ) { \n\n if( g.charAt(i) == s.charAt(j) ) {\n counter=counter+1;\n\n } \n\n }\n System.out.print(counter); \n }\n }\n}\n</code></pre>\n\n<p>/******************** OUTPUT **********************/</p>\n\n<p>SELENIUM</p>\n\n<p>SELNIUM </p>\n\n<p>S : 1,E : 2,L : 1,E : 1,N : 1,I : 1,U : 1</p>\n"
},
{
"answer_id": 44020468,
"author": "Amar Magar",
"author_id": 5667861,
"author_profile": "https://Stackoverflow.com/users/5667861",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way to get the answer is as follow:</p>\n\n<pre><code>public static void main(String[] args) {\n String string = \"a.b.c.d\";\n String []splitArray = string.split(\"\\\\.\",-1);\n System.out.println(\"No of . chars is : \" + (splitArray.length-1));\n}\n</code></pre>\n"
},
{
"answer_id": 44160784,
"author": "gil.fernandes",
"author_id": 2735286,
"author_profile": "https://Stackoverflow.com/users/2735286",
"pm_score": 3,
"selected": false,
"text": "<p>Also possible to use reduce in Java 8 to solve this problem:</p>\n\n<pre><code>int res = \"abdsd3$asda$asasdd$sadas\".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));\nSystem.out.println(res);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>3\n</code></pre>\n"
},
{
"answer_id": 44713830,
"author": "Donald Raab",
"author_id": 1570415,
"author_profile": "https://Stackoverflow.com/users/1570415",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a></p>\n\n<pre><code>int count = Strings.asChars(\"a.b.c.d\").count(c -> c == '.');\n</code></pre>\n\n<p>If you have more than one character to count, you can use a <code>CharBag</code> as follows:</p>\n\n<pre><code>CharBag bag = Strings.asChars(\"a.b.c.d\").toBag();\nint count = bag.occurrencesOf('.');\n</code></pre>\n\n<p>Note: I am a committer for Eclipse Collections.</p>\n"
},
{
"answer_id": 45393057,
"author": "Perry Anderson",
"author_id": 8387219,
"author_profile": "https://Stackoverflow.com/users/8387219",
"pm_score": 0,
"selected": false,
"text": "<pre><code>String[] parts = text.split(\".\");\nint occurances = parts.length - 1;\n\n\" It's a great day at O.S.G. Dallas! \"\n -- Famous Last Words\n</code></pre>\n\n<p>Well, it's a case of knowing your Java, especially your basic foundational understanding of the collection classes already available in Java. If you look throughout the entire posting here, there is just about everything short of Stephen Hawking's explanation of the Origin of the Universe, Darwin's paperback on Evolution and Gene Roddenberry's Star Trek cast selection as to why they went with William Shatner short of how to do this quickly and easily...</p>\n\n<p>... need I say anymore?</p>\n"
},
{
"answer_id": 51640872,
"author": "Baibhav Ghimire",
"author_id": 4941710,
"author_profile": "https://Stackoverflow.com/users/4941710",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static void getCharacter(String str){\n\n int count[]= new int[256];\n\n for(int i=0;i<str.length(); i++){\n\n\n count[str.charAt(i)]++;\n\n }\n System.out.println(\"The ascii values are:\"+ Arrays.toString(count));\n\n //Now display wht character is repeated how many times\n\n for (int i = 0; i < count.length; i++) {\n if (count[i] > 0)\n System.out.println(\"Number of \" + (char) i + \": \" + count[i]);\n }\n\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 57606966,
"author": "Niklas Lyszio",
"author_id": 11860105,
"author_profile": "https://Stackoverflow.com/users/11860105",
"pm_score": 0,
"selected": false,
"text": "<p>Using Java 8 and a HashMap without any library for counting all the different chars:</p>\n\n<pre><code>private static void countChars(String string) {\n HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));\n hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + \":\" + i));\n}\n</code></pre>\n"
},
{
"answer_id": 58210549,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 0,
"selected": false,
"text": "<p><em>use a lambda function which removes all characters to count</em><br />\nthe count is the difference of the before-length and after-length</p>\n\n<pre><code>String s = \"a.b.c.d\";\nint count = s.length() - deleteChars.apply( s, \".\" ).length(); // 3\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/4576352/remove-all-occurrences-of-char-from-string/56916146#56916146\">find deleteChars here</a></p>\n\n<p><br /><em>if you have to count the occurrences of more than one character it can be done in one swoop:</em><br />\neg. for <code>b</code> <code>c</code> and <code>.</code>:</p>\n\n<pre><code>int count = s.length() - deleteChars.apply( s, \"bc.\" ).length(); // 5\n</code></pre>\n"
},
{
"answer_id": 59332508,
"author": "Saharcasm",
"author_id": 5559138,
"author_profile": "https://Stackoverflow.com/users/5559138",
"pm_score": 3,
"selected": false,
"text": "<p>A much easier solution would be to just the split the string based on the character you're matching it with.</p>\n\n<p>For instance,</p>\n\n<p><code>int getOccurences(String characters, String string) {\n String[] words = string.split(characters);\n return words.length - 1;\n}</code></p>\n\n<p>This will return 4 in the case of:\n<code>getOccurences(\"o\", \"something about a quick brown fox\");</code></p>\n"
},
{
"answer_id": 62514326,
"author": "IonKat",
"author_id": 12480986,
"author_profile": "https://Stackoverflow.com/users/12480986",
"pm_score": 2,
"selected": false,
"text": "<p>This is what I use to count the occurrences of a string.</p>\n<p>Hope someone finds it helpful.</p>\n<pre><code> private long countOccurrences(String occurrences, char findChar){\n return occurrences.chars().filter( x -> {\n return x == findChar;\n }).count();\n }\n</code></pre>\n"
},
{
"answer_id": 65026287,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 0,
"selected": false,
"text": "<p><em>a lambda one-liner</em><br />\nw/o the need of an external library.<br />\nCreates a map with the count of each character:<br /></p>\n<pre><code>Map<Character,Long> counts = "a.b.c.d".codePoints().boxed().collect(\n groupingBy( t -> (char)(int)t, counting() ) );\n</code></pre>\n<p>gets: <code>{a=1, b=1, c=1, d=1, .=3}</code><br />\nthe count of a certain character eg. <code>'.'</code> is given over:<br />\n<code>counts.get( '.' )</code></p>\n<p><em>(I also write a lambda solution out of morbid curiosity to find out how slow my solution is, preferably from the man with the 10-line solution.)</em></p>\n"
},
{
"answer_id": 67026485,
"author": "Murali",
"author_id": 1759028,
"author_profile": "https://Stackoverflow.com/users/1759028",
"pm_score": 0,
"selected": false,
"text": "<p>Here is most simple and easy to understand without using arrays, just by using Hashmap. Also it will calculate whitespaces, number of capital chars and small chars, special characters etc.</p>\n<pre><code>import java.util.HashMap;\n //The code by muralidharan \n public class FindChars {\n \n public static void main(String[] args) {\n \n findchars("rererereerererererererere");\n }\n \n public static void findchars(String s){\n \n HashMap<Character,Integer> k=new HashMap<Character,Integer>();\n for(int i=0;i<s.length();i++){\n if(k.containsKey(s.charAt(i))){\n Integer v =k.get(s.charAt(i));\n k.put(s.charAt(i), v+1);\n }else{\n k.put(s.charAt(i), 1);\n }\n \n }\n System.out.println(k);\n \n }\n \n }\n</code></pre>\n<p><strong>O/P:\n<strong>{r=12, e=13}</strong></strong></p>\n<p>second input:</p>\n<pre><code>findchars("The world is beautiful and $#$%%%%%%@@@@ is worst");\n</code></pre>\n<p><strong>O/P:\n<strong>{ =7, @=4, a=2, b=1, #=1, d=2, $=2, e=2, %=6, f=1, h=1, i=3, l=2, n=1, o=2, r=2, s=3, T=1, t=2, u=2, w=2}</strong></strong></p>\n"
},
{
"answer_id": 68966764,
"author": "hadialaoui",
"author_id": 8709853,
"author_profile": "https://Stackoverflow.com/users/8709853",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public static String encodeMap(String plainText){\n \n Map<Character,Integer> mapResult=new LinkedHashMap<Character,Integer>();\n String result = "";\n for(int i=0;i<plainText.length();i++){\n if(mapResult.containsKey(plainText.charAt(i))){\n Integer v =mapResult.get(plainText.charAt(i));\n mapResult.put(plainText.charAt(i), v+1);\n }else{\n mapResult.put(plainText.charAt(i), 1);\n }\n }\n \n for(Map.Entry<Character, Integer> t : mapResult.entrySet()) {\n result += String.valueOf(t.getKey())+t.getValue();\n }\n \n return result;\n \n }\n\n public static void main(String args[]) {\n String plainText = "aaavvfff";\n System.out.println(encodeMap(plainText)); //a3v2f3 \n }\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343/"
] |
I have the string
```
a.b.c.d
```
I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.
(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).
|
My 'idiomatic one-liner' for this is:
```
int count = StringUtils.countMatches("a.b.c.d", ".");
```
Why write it yourself when it's already in [commons lang](http://commons.apache.org/lang/)?
Spring Framework's oneliner for this is:
```
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
```
|
275,958 |
<p>I have a list of say 100 unsorted items. Each item belongs to a group. The group the item belongs to is simply a member of the item class.</p>
<p>Using C/C++ I'm looking for the most efficient way of scanning through the list of items, checking which group they are in and printing the item to the screen. Here's the catch though. Once an item from a group has been printed to the screen, I don't want to print any more items belonging to that group.</p>
<p>I'm using a pre STL compiler and the size of the executable is critical so I don't want to start defining my own Hash classes.</p>
|
[
{
"answer_id": 275961,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a dictionary/hashmap of groups and for each group store a bool saying if a item of that group was printed or not.</p>\n\n<p>Sample code:</p>\n\n<pre><code>#include <unordered_map>\n#include <string>\n#include <iostream>\n\nstd::string getGroupForNumber( int num )\n{\n//\n}\n\nint main()\n{\n typedef std::tr1::unordered_map< std::string, bool > hashmap;\n hashmap groupsPrinted;\n\n for( int i = 0 ; i < 100 ; ++i ) {\n if ( groupsPrinted[ getGroupForNumber( i ) ] == false ) {\n groupsPrinted[ getGroupForNumber( i ) ] = true;\n std::cout << i << std::endl;\n }\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 275973,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<p>Sort the items according the group value (if it's a <em>pointer</em>, then you can use its address, otherwise <em>lexicographical</em> sort the <em>string</em>). Then loop through that sorted list, taking the first item of each group always. </p>\n\n<p>\nThis takes approximately <pre>n + n * log(n)</pre>\n</p>\n\n<p>I think this is a reasonable alternative between the size of your executable and speed.</p>\n"
},
{
"answer_id": 276004,
"author": "Drakosha",
"author_id": 19868,
"author_profile": "https://Stackoverflow.com/users/19868",
"pm_score": 0,
"selected": false,
"text": "<p>If you can number the groups 0..99 then you'll need an array of booleans, or bitset if you want to optimize.\nInit all the array to 'false'.\nSet arr[groupId] = 'true' after you print it, and check the value next time before printing. No STL required.</p>\n"
},
{
"answer_id": 276006,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 0,
"selected": false,
"text": "<p>Keep a std::set of the group names that items of which should no longer be printed.</p>\n"
},
{
"answer_id": 276018,
"author": "Tamir Shomer",
"author_id": 35898,
"author_profile": "https://Stackoverflow.com/users/35898",
"pm_score": 1,
"selected": false,
"text": "<p>You did write c/c++ in the question, so here's some c code.\nA couple of questions are in order. \nDoes a group become printable sometime in the future?\nIs the item list static?\nDoes it matter which item from a specific group you print?</p>\n\n<p>I would suggest the following construct (with my limited understanding of the problem):</p>\n\n<p>An array of lists.</p>\n\n<pre><code> typedef struct node{\n void *item; /* this is your item */\n node *next; \n } node_t;\n\n typedef struct {\n node_t *my_group;\n int used;\n } group_t;\n\n static group_t my_items[NUM_OF_GROUPS]; /* this is your ordered by groups list.*/\n</code></pre>\n\n<p>Better yet, use a list of lists. group_t will be:</p>\n\n<pre><code>typedef struct group{\n node_t *my_group;\n group *next_free;\n} group_t;\n</code></pre>\n"
},
{
"answer_id": 276047,
"author": "KJF",
"author_id": 7129,
"author_profile": "https://Stackoverflow.com/users/7129",
"pm_score": 0,
"selected": false,
"text": "<p>To answer some more questions.</p>\n\n<blockquote>\n <p>Is the item list static?</p>\n</blockquote>\n\n<p>No, it can shrink or grow at any time.</p>\n\n<blockquote>\n <p>Does it matter which item from a\n specific group you print?</p>\n</blockquote>\n\n<p>Not for the time being, no. Maybe in the future, but at the moment it should be sufficient to print the first item found belonging to a unique group.</p>\n"
},
{
"answer_id": 276170,
"author": "Tamir Shomer",
"author_id": 35898,
"author_profile": "https://Stackoverflow.com/users/35898",
"pm_score": 0,
"selected": false,
"text": "<p>What about groups? can you get a new group? And can a group become relevant after you print one of its members?</p>\n"
},
{
"answer_id": 276603,
"author": "Jed",
"author_id": 33208,
"author_profile": "https://Stackoverflow.com/users/33208",
"pm_score": 0,
"selected": false,
"text": "<p>The cost to print to the screen is several orders of magnitude more than anything else you can do with the objects. If you had an array of 10 million objects in only a few groups, then sorting is not a reasonable option. If the groups can be identified by a static index (i.e. an integer in a given range), just use a mask array to indicate whether it's been seen. If the groups are more complicated, you can store the groups that have been seen in any set data structure (hash, tree, etc).</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7129/"
] |
I have a list of say 100 unsorted items. Each item belongs to a group. The group the item belongs to is simply a member of the item class.
Using C/C++ I'm looking for the most efficient way of scanning through the list of items, checking which group they are in and printing the item to the screen. Here's the catch though. Once an item from a group has been printed to the screen, I don't want to print any more items belonging to that group.
I'm using a pre STL compiler and the size of the executable is critical so I don't want to start defining my own Hash classes.
|
Sort the items according the group value (if it's a *pointer*, then you can use its address, otherwise *lexicographical* sort the *string*). Then loop through that sorted list, taking the first item of each group always.
This takes approximately
```
n + n * log(n)
```
I think this is a reasonable alternative between the size of your executable and speed.
|
275,965 |
<p>when i create an aspx page, the header includes something like this:-</p>
<pre><code><%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
AutoEventWireup="true"
CodeBehind="Create.aspx.cs"
Inherits="My.Mvc.Views.Blah" %>
</code></pre>
<p>With ASP.NET MVC apps, do we:</p>
<ul>
<li>need to include this AutoEventWireUp attribute?</li>
<li>What happens if we set this to false?</li>
<li>what does this attribute really do? is it valid for ASP.NET MVC?</li>
</ul>
<p>thanks heaps folks!</p>
|
[
{
"answer_id": 275982,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 2,
"selected": false,
"text": "<p>You can get rid of this attribute, or set it to false (which is the default). </p>\n\n<p>AutoEventWireup means ASP.NET will use reflection at runtime to look for methods on your web form class in the form of Page_EventName (like Page_Load, Page_Init, etc), and automatically wire the methods to the corresponding page lifecycle events. I have some more details here: <a href=\"http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx\" rel=\"nofollow noreferrer\">http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx</a></p>\n\n<p>In MVC you should, as a general rule, avoid wiring up event handlers for the page lifecycle and code-behind in general. </p>\n"
},
{
"answer_id": 276385,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 3,
"selected": true,
"text": "<p>Sorry - the default is true in ASP.NET, so you should explicitly set AutoEventWireup to false in the @ Page directive, or remove it and set it to false in pages section of web.config for MVC. </p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
when i create an aspx page, the header includes something like this:-
```
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
AutoEventWireup="true"
CodeBehind="Create.aspx.cs"
Inherits="My.Mvc.Views.Blah" %>
```
With ASP.NET MVC apps, do we:
* need to include this AutoEventWireUp attribute?
* What happens if we set this to false?
* what does this attribute really do? is it valid for ASP.NET MVC?
thanks heaps folks!
|
Sorry - the default is true in ASP.NET, so you should explicitly set AutoEventWireup to false in the @ Page directive, or remove it and set it to false in pages section of web.config for MVC.
|
275,971 |
<p>I'm pretty new to HQL (well, nHibernate in general) and am currently building a simple app to learn more about it.</p>
<p>I've run into problems trying to express the following SQL as HQL though, and would be very grateful for any ideas.</p>
<p>Here's the query:</p>
<pre><code>select * from parent p
where p.id in (select p.parentid from child c where c.createdby = 2)
and
(select top 1 createdby
from child where parentid = p.id order by createdon desc) != 2
</code></pre>
|
[
{
"answer_id": 275982,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 2,
"selected": false,
"text": "<p>You can get rid of this attribute, or set it to false (which is the default). </p>\n\n<p>AutoEventWireup means ASP.NET will use reflection at runtime to look for methods on your web form class in the form of Page_EventName (like Page_Load, Page_Init, etc), and automatically wire the methods to the corresponding page lifecycle events. I have some more details here: <a href=\"http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx\" rel=\"nofollow noreferrer\">http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx</a></p>\n\n<p>In MVC you should, as a general rule, avoid wiring up event handlers for the page lifecycle and code-behind in general. </p>\n"
},
{
"answer_id": 276385,
"author": "OdeToCode",
"author_id": 17210,
"author_profile": "https://Stackoverflow.com/users/17210",
"pm_score": 3,
"selected": true,
"text": "<p>Sorry - the default is true in ASP.NET, so you should explicitly set AutoEventWireup to false in the @ Page directive, or remove it and set it to false in pages section of web.config for MVC. </p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm pretty new to HQL (well, nHibernate in general) and am currently building a simple app to learn more about it.
I've run into problems trying to express the following SQL as HQL though, and would be very grateful for any ideas.
Here's the query:
```
select * from parent p
where p.id in (select p.parentid from child c where c.createdby = 2)
and
(select top 1 createdby
from child where parentid = p.id order by createdon desc) != 2
```
|
Sorry - the default is true in ASP.NET, so you should explicitly set AutoEventWireup to false in the @ Page directive, or remove it and set it to false in pages section of web.config for MVC.
|
275,980 |
<p>I tried to import mechanize module to my python script like this,</p>
<pre><code>from mechanize import Browser
</code></pre>
<p>But, Google appengine throws HTTP 500 when accessing my script.</p>
<p>To make things more clear, Let me give you the snapshot of my package structure,</p>
<pre><code>root
....mechanize(where all the mechanize related files there)
....main.py
....app.yaml
....image
....script
</code></pre>
<p>Can anyone help me out to resolve this issue?</p>
<p>Thanks,
Ponmalar</p>
|
[
{
"answer_id": 276350,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>When GAE throws a 500, you can see the actual error in the logs on your admin console. If that doesn't help, paste it here and we'll help further.</p>\n\n<p>Also, does it work on the dev_appserver?</p>\n"
},
{
"answer_id": 276640,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 2,
"selected": false,
"text": "<p>The mechanize main page says:</p>\n\n<blockquote>\n <p>mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector</p>\n</blockquote>\n\n<p>My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I tried to import mechanize module to my python script like this,
```
from mechanize import Browser
```
But, Google appengine throws HTTP 500 when accessing my script.
To make things more clear, Let me give you the snapshot of my package structure,
```
root
....mechanize(where all the mechanize related files there)
....main.py
....app.yaml
....image
....script
```
Can anyone help me out to resolve this issue?
Thanks,
Ponmalar
|
The mechanize main page says:
>
> mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector
>
>
>
My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.
|
275,994 |
<p>I need to move backwards through an array, so I have code like this:</p>
<pre><code>for (int i = myArray.Length - 1; i >= 0; i--)
{
// Do something
myArray[i] = 42;
}
</code></pre>
<p>Is there a better way of doing this?</p>
<p>Update: I was hoping that maybe C# had some built-in mechanism for this like:</p>
<pre><code>foreachbackwards (int i in myArray)
{
// so easy
}
</code></pre>
|
[
{
"answer_id": 275996,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "<p>That's definitely the best way for any array whose length is a signed integral type. For arrays whose lengths are an unsigned integral type (e.g. an <code>std::vector</code> in C++), then you need to modify the end condition slightly:</p>\n\n<pre><code>for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)\n // blah\n</code></pre>\n\n<p>If you just said <code>i >= 0</code>, this is always true for an unsigned integer, so the loop will be an infinite loop.</p>\n"
},
{
"answer_id": 276001,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Looks good to me. If the indexer was unsigned (uint etc), you might have to take that into account. Call me lazy, but in that (unsigned) case, I might just use a counter-variable:</p>\n\n<pre><code>uint pos = arr.Length;\nfor(uint i = 0; i < arr.Length ; i++)\n{\n arr[--pos] = 42;\n}\n</code></pre>\n\n<p>(actually, even here you'd need to be careful of cases like arr.Length = uint.MaxValue... maybe a != somewhere... of course, that is a very unlikely case!)</p>\n"
},
{
"answer_id": 276003,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going to try answering my own question here, but I don't really like this, either:</p>\n\n<pre><code>for (int i = 0; i < myArray.Length; i++)\n{\n int iBackwards = myArray.Length - 1 - i; // ugh\n myArray[iBackwards] = 666;\n}\n</code></pre>\n"
},
{
"answer_id": 276044,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 4,
"selected": false,
"text": "<p>In <strong>C#</strong> using <strong>Linq</strong>:</p>\n\n<pre><code>foreach(var item in myArray.Reverse())\n{\n // do something\n}\n</code></pre>\n"
},
{
"answer_id": 276053,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "\n<p>In C++ you basicially have the choice between iterating using iterators, or indices.\nDepending on whether you have a plain array, or a <code>std::vector</code>, you use different techniques.</p>\n<h2>Using std::vector</h2>\n<h3>Using iterators</h3>\nC++ allows you to do this using <code>std::reverse_iterator:</code>\n<pre class=\"lang-c++ prettyprint-override\"><code>for(std::vector<T>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it) {\n /* std::cout << *it; ... */\n}\n</code></pre>\n<h3>Using indices</h3>\nThe unsigned integral type returned by `std::vector::size` is *not* always `std::size_t`. It can be greater or less. This is crucial for the loop to work. \n<pre class=\"lang-c++ prettyprint-override\"><code>for(std::vector<int>::size_type i = someVector.size() - 1; \n i != (std::vector<int>::size_type) -1; i--) {\n /* std::cout << someVector[i]; ... */\n}\n</code></pre>\n<p>It works, since unsigned integral types values are defined by means of modulo their count of bits. Thus, if you are setting <code>-N</code>, you end up at <code>(2 ^ BIT_SIZE) -N</code></p>\n<h2>Using Arrays</h2>\n<h3>Using iterators</h3>\nWe are using `std::reverse_iterator` to do the iterating.\n<pre class=\"lang-c++ prettyprint-override\"><code>for(std::reverse_iterator<element_type*> it(a + sizeof a / sizeof *a), itb(a); \n it != itb; \n ++it) {\n /* std::cout << *it; .... */\n}\n</code></pre>\n<h3>Using indices</h3>\nWe can safely use `std::size_t` here, as opposed to above, since `sizeof` always returns `std::size_t` by definition.\n<pre class=\"lang-c++ prettyprint-override\"><code>for(std::size_t i = (sizeof a / sizeof *a) - 1; i != (std::size_t) -1; i--) {\n /* std::cout << a[i]; ... */\n}\n</code></pre>\n<h2>Avoiding pitfalls with sizeof applied to pointers</h2>\nActually the above way of determining the size of an array sucks. If a is actually a pointer instead of an array (which happens quite often, and beginners will confuse it), it will silently fail. A better way is to use the following, which will fail at compile time, if given a pointer:\n<pre class=\"lang-c++ prettyprint-override\"><code>template<typename T, std::size_t N> char (& array_size(T(&)[N]) )[N];\n</code></pre>\n<p>It works by getting the size of the passed array first, and then declaring to return a reference to an array of type char of the same size. <code>char</code> is defined to have <code>sizeof</code> of: 1. So the returned array will have a <code>sizeof</code> of: N * 1, which is what we are looking for, with only compile time evaluation and zero runtime overhead.</p>\n<p>Instead of doing</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>(sizeof a / sizeof *a)\n</code></pre>\n<p>Change your code so that it now does</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>(sizeof array_size(a))\n</code></pre>\n"
},
{
"answer_id": 276056,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": "<p>While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is</p>\n\n<pre><code>for (int i = myArray.Length; i --> 0; )\n{\n //do something\n}\n</code></pre>\n"
},
{
"answer_id": 276084,
"author": "domain.dot.net team",
"author_id": 31626,
"author_profile": "https://Stackoverflow.com/users/31626",
"pm_score": -1,
"selected": false,
"text": "<p>NOTE: This post ended up being far more detailed and therefore off topic, I apologize.</p>\n\n<p>That being said my peers read it and believe it is valuable 'somewhere'. This thread is not the place. I would appreciate your feedback on where this should go (I am new to the site).</p>\n\n<hr>\n\n<p>Anyway this is the C# version in .NET 3.5 which is amazing in that it works on any collection type using the defined semantics. This is a default measure (reuse!) not performance or CPU cycle minimization in most common dev scenario although that never seems to be what happens in the real world (premature optimization).</p>\n\n<p>*** Extension method working over any collection type and taking an action delegate expecting a single value of the type, all executed over each item in reverse **</p>\n\n<p>Requres 3.5:</p>\n\n<pre><code>public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)\n {\n foreach (var contextItem in sequenceToReverse.Reverse())\n doForEachReversed(contextItem);\n }\n</code></pre>\n\n<p>Older .NET versions or do you want to understand Linq internals better? Read on.. Or not..</p>\n\n<p>ASSUMPTION: In the .NET type system the Array type inherits from the IEnumerable interface (not the generic IEnumerable only IEnumerable).</p>\n\n<p>This is all you need to iterate from beginning to end, however you want to move in the opposite direction. As IEnumerable works on Array of type 'object' any type is valid, </p>\n\n<p>CRITICAL MEASURE: We assume if you can process any sequence in reverse order that is 'better' then only being able to do it on integers. </p>\n\n<p>Solution a for .NET CLR 2.0-3.0:</p>\n\n<p>Description: We will accept any IEnumerable implementing instance with the mandate that each instance it contains is of the same type. So if we recieve an array the entire array contains instances of type X. If any other instances are of a type !=X an exception is thrown:</p>\n\n<p>A singleton service:</p>\n\n<p>public class ReverserService\n {\n private ReverserService() { }</p>\n\n<pre><code> /// <summary>\n /// Most importantly uses yield command for efficiency\n /// </summary>\n /// <param name=\"enumerableInstance\"></param>\n /// <returns></returns>\n public static IEnumerable ToReveresed(IEnumerable enumerableInstance)\n {\n if (enumerableInstance == null)\n {\n throw new ArgumentNullException(\"enumerableInstance\");\n }\n\n // First we need to move forwarad and create a temp\n // copy of a type that allows us to move backwards\n // We can use ArrayList for this as the concrete\n // type\n\n IList reversedEnumerable = new ArrayList();\n IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();\n\n while (tempEnumerator.MoveNext())\n {\n reversedEnumerable.Add(tempEnumerator.Current);\n }\n\n // Now we do the standard reverse over this using yield to return\n // the result\n // NOTE: This is an immutable result by design. That is \n // a design goal for this simple question as well as most other set related \n // requirements, which is why Linq results are immutable for example\n // In fact this is foundational code to understand Linq\n\n for (var i = reversedEnumerable.Count - 1; i >= 0; i--)\n {\n yield return reversedEnumerable[i];\n }\n }\n}\n\n\n\npublic static class ExtensionMethods\n{\n\n public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)\n {\n return ReverserService.ToReveresed(enumerableInstance);\n }\n }\n</code></pre>\n\n<p>[TestFixture]\n public class Testing123\n {</p>\n\n<pre><code> /// <summary>\n /// .NET 1.1 CLR\n /// </summary>\n [Test]\n public void Tester_fornet_1_dot_1()\n {\n const int initialSize = 1000;\n\n // Create the baseline data\n int[] myArray = new int[initialSize];\n\n for (var i = 0; i < initialSize; i++)\n {\n myArray[i] = i + 1;\n }\n\n IEnumerable _revered = ReverserService.ToReveresed(myArray);\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n }\n\n [Test]\n public void tester_why_this_is_good()\n {\n\n ArrayList names = new ArrayList();\n names.Add(\"Jim\");\n names.Add(\"Bob\");\n names.Add(\"Eric\");\n names.Add(\"Sam\");\n\n IEnumerable _revered = ReverserService.ToReveresed(names);\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(\"Sam\"));\n\n\n }\n\n [Test]\n public void tester_extension_method()\n {\n\n // Extension Methods No Linq (Linq does this for you as I will show)\n var enumerableOfInt = Enumerable.Range(1, 1000);\n\n // Use Extension Method - which simply wraps older clr code\n IEnumerable _revered = enumerableOfInt.ToReveresed();\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n\n\n }\n\n\n [Test]\n public void tester_linq_3_dot_5_clr()\n {\n\n // Extension Methods No Linq (Linq does this for you as I will show)\n IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);\n\n // Reverse is Linq (which is are extension methods off IEnumerable<T>\n // Note you must case IEnumerable (non generic) using OfType or Cast\n IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n\n\n }\n\n\n\n [Test]\n public void tester_final_and_recommended_colution()\n {\n\n var enumerableOfInt = Enumerable.Range(1, 1000);\n enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));\n\n }\n\n\n\n private static object TestAndGetResult(IEnumerable enumerableIn)\n {\n // IEnumerable x = ReverserService.ToReveresed(names);\n\n Assert.IsTrue(enumerableIn != null);\n IEnumerator _test = enumerableIn.GetEnumerator();\n\n // Move to first\n Assert.IsTrue(_test.MoveNext());\n return _test.Current;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 276097,
"author": "xyz",
"author_id": 82,
"author_profile": "https://Stackoverflow.com/users/82",
"pm_score": 0,
"selected": false,
"text": "<p>I'd use the code in the original question, but if you really wanted to use foreach and have an integer index in C#:</p>\n\n<pre><code>foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())\n{\n myArray[i] = 42; \n}\n</code></pre>\n"
},
{
"answer_id": 276146,
"author": "Twotymz",
"author_id": 2224,
"author_profile": "https://Stackoverflow.com/users/2224",
"pm_score": 2,
"selected": false,
"text": "<p>In C I like to do this:</p>\n\n<pre>\n<code>\nint i = myArray.Length;\nwhile (i--) {\n myArray[i] = 42;\n}\n</code>\n</pre>\n\n<p>C# example added by MusiGenesis:</p>\n\n<pre><code>{int i = myArray.Length; while (i-- > 0)\n{\n myArray[i] = 42;\n}}\n</code></pre>\n"
},
{
"answer_id": 276176,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": false,
"text": "<p><strong>In C#</strong>, using Visual Studio 2005 or later, <strong>type 'forr' and hit [TAB] [TAB]</strong>. This will expand to a <code>for</code> loop that goes backwards through a collection.</p>\n\n<p>It's so easy to get wrong (at least for me), that I thought putting this snippet in would be a good idea.</p>\n\n<p>That said, I like <code>Array.Reverse()</code> / <code>Enumerable.Reverse()</code> and then iterate <em>forwards</em> better - they more clearly state intent.</p>\n"
},
{
"answer_id": 276793,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The best way to do that in C++ is probably to use iterator (or better, range) adaptors, which will lazily transform the sequence as it is being traversed.</p>\n\n<p>Basically,</p>\n\n<pre><code>vector<value_type> range;\nforeach(value_type v, range | reversed)\n cout << v;\n</code></pre>\n\n<p>Displays the range \"range\" (here, it's empty, but i'm fairly sure you can add elements yourself) in reverse order.\nOf course simply iterating the range is not much use, but passing that new range to algorithms and stuff is pretty cool.</p>\n\n<p>This mechanism can also be used for much more powerful uses:</p>\n\n<pre><code>range | transformed(f) | filtered(p) | reversed\n</code></pre>\n\n<p>Will lazily compute the range \"range\", where function \"f\" is applied to all elements, elements for which \"p\" is not true are removed, and finally the resulting range is reversed.</p>\n\n<p>Pipe syntax is the most readable IMO, given it's infix.\nThe Boost.Range library update pending review implements this, but it's pretty simple to do it yourself also. It's even more cool with a lambda DSEL to generate the function f and the predicate p in-line.</p>\n"
},
{
"answer_id": 369137,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// this is how I always do it\nfor (i = n; --i >= 0;){\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 14136931,
"author": "Jack Griffin",
"author_id": 1362643,
"author_profile": "https://Stackoverflow.com/users/1362643",
"pm_score": 6,
"selected": false,
"text": "<p>I would <strong>always</strong> prefer clear code against '<em>typographically pleasing</em>' code.\nThus, I would always use : </p>\n\n<pre><code>for (int i = myArray.Length - 1; i >= 0; i--) \n{ \n // Do something ... \n} \n</code></pre>\n\n<p>You can consider it as the standard way to loop backwards.<br>\nJust my two cents...</p>\n"
},
{
"answer_id": 40234452,
"author": "Petko Petkov",
"author_id": 2240383,
"author_profile": "https://Stackoverflow.com/users/2240383",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer a while loop. It's more clear to me than decrementing <code>i</code> in the condition of a for loop</p>\n\n<pre><code>int i = arrayLength;\nwhile(i)\n{\n i--;\n //do something with array[i]\n}\n</code></pre>\n"
},
{
"answer_id": 65542588,
"author": "nspo",
"author_id": 997151,
"author_profile": "https://Stackoverflow.com/users/997151",
"pm_score": 0,
"selected": false,
"text": "<p><strong>For C++:</strong></p>\n<p>As mentioned by others, when possible (i.e. when you only want each element at a time) it is strongly preferable to use iterators to both be explicit and avoid common pitfalls. Modern C++ has a more concise syntax for that with <code>auto</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.rend(); ++it) {\n std::cout<<*it<<" ";\n}\n</code></pre>\n<p>prints <code>4 3 2 1 </code>.</p>\n<p>You can also modify the value during the loop:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.rend(); ++it) {\n *it = *it + 10;\n std::cout<<*it<<" ";\n}\n</code></pre>\n<p>leading to <code>14 13 12 11 </code> being printed and <code>{11, 12, 13, 14}</code> being in the <code>std::vector</code> afterwards.</p>\n<p>If you don't plan on modifying the value during the loop, you should make sure that you get an error when you try to do that by accident, similarly to how one might write <code>for(const auto& element : vec)</code>. This is possible like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.crbegin(); it != vec.crend(); ++it) { // used crbegin()/crend() here...\n *it = *it + 10; // ... so that this is a compile-time error\n std::cout<<*it<<" ";\n}\n</code></pre>\n<p>The compiler error in this case for me is:</p>\n<pre><code>/tmp/main.cpp:20:9: error: assignment of read-only location ‘it.std::reverse_iterator<__gnu_cxx::__normal_iterator<const int*, std::vector<int> > >::operator*()’\n 20 | *it = *it + 10;\n | ~~~~^~~~~~~~~~\n</code></pre>\n<p>Also note that you should make sure not to use different iterator types together:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.end(); ++it) { // mixed rbegin() and end()\n std::cout<<*it<<" ";\n}\n</code></pre>\n<p>leads to the verbose error:</p>\n<pre><code>/tmp/main.cpp: In function ‘int main()’:\n/tmp/main.cpp:19:33: error: no match for ‘operator!=’ (operand types are ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >’ and ‘std::vector<int>::iterator’ {aka ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’})\n 19 | for (auto it = vec.rbegin(); it != vec.end(); ++it) {\n | ~~ ^~ ~~~~~~~~~\n | | |\n | | std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}\n | std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >\n</code></pre>\n<p>If you have C-style arrays on the stack, you can do things like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int vec[] = {1,2,3,4};\nfor (auto it = std::crbegin(vec); it != std::crend(vec); ++it) {\n std::cout<<*it<<" ";\n}\n</code></pre>\n<p>If you really need the index, consider the following options:</p>\n<ul>\n<li>check the range, then work with signed values, e.g.:</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>void loop_reverse(std::vector<int>& vec) {\n if (vec.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {\n throw std::invalid_argument("Input too large");\n }\n const int sz = static_cast<int>(vec.size());\n for(int i=sz-1; i >= 0; --i) {\n // do something with i\n }\n}\n</code></pre>\n<ul>\n<li>Work with unsigned values, be careful, and add comments, e.g.:</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>void loop_reverse2(std::vector<int>& vec) {\n for(size_t i=vec.size(); i-- > 0;) { // reverse indices from N-1 to 0\n // do something with i\n }\n}\n</code></pre>\n<ul>\n<li>calculate the actual index separately, e.g.:</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>void loop_reverse3(std::vector<int>& vec) {\n for(size_t offset=0; offset < vec.size(); ++offset) {\n const size_t i = vec.size()-1-offset; // reverse indices from N-1 to 0\n // do something with i\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69274027,
"author": "Ibrahim Ozdemir",
"author_id": 4950783,
"author_profile": "https://Stackoverflow.com/users/4950783",
"pm_score": 1,
"selected": false,
"text": "<p>i do this</p>\n<pre><code>if (list.Count > 0)\n for (size_t i = list.Count - 1; ; i--)\n {\n //do your thing\n \n if (i == 0) //for preventing unsigned wrap\n break;\n }\n</code></pre>\n<p>but for some reason visual studio 2019 gets angry and warns me "ill-defined loop" or something.. it doesnt trust me</p>\n<hr />\n<p>edit: you can remove "i >= 0" from "for (size_t i = list.Count - 1; i >= 0; i--)" .. its unnecessary</p>\n"
},
{
"answer_id": 74102748,
"author": "RecursiveDude",
"author_id": 20266692,
"author_profile": "https://Stackoverflow.com/users/20266692",
"pm_score": -1,
"selected": false,
"text": "<p>Not that it matters after 13+ years but just for educational purposes and a bit of trivial learning;</p>\n<p>The original code was;</p>\n<pre><code>for (int i = myArray.Length - 1; i >= 0; i--)\n{\n // Do something\n myArray[i] = 42;\n}\n</code></pre>\n<p>You don't really need to test 'i' again being greater or equal to zero since you simply need to only produce a 'false' result to terminate the loop. Therefore, you can simple do this where you are only testing 'i' itself if it is true or false since it will be (implicitly) false when it hits zero.;</p>\n<pre><code>for (int i = myArray.Length - 1; i; i--)\n{\n // Do something\n myArray[i] = 42;\n}\n</code></pre>\n<p>Like I stated, it doesn't really matter, but it is just interesting to understand the mechanics of what is going on inside the for() loop.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/275994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
I need to move backwards through an array, so I have code like this:
```
for (int i = myArray.Length - 1; i >= 0; i--)
{
// Do something
myArray[i] = 42;
}
```
Is there a better way of doing this?
Update: I was hoping that maybe C# had some built-in mechanism for this like:
```
foreachbackwards (int i in myArray)
{
// so easy
}
```
|
While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is
```
for (int i = myArray.Length; i --> 0; )
{
//do something
}
```
|
276,029 |
<p>I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.</p>
<p>Example:</p>
<pre><code> i'm living <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>, i love Paris.
</code></pre>
<p>would become </p>
<pre><code> i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.
</code></pre>
|
[
{
"answer_id": 276073,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Regular expression:</strong></p>\n\n<pre><code>!(<a.*</a>.*)*Paris!isU\n</code></pre>\n\n<p><strong>Replacement:</strong></p>\n\n<pre><code>$1<a href=\"Paris\">Paris</a>\n</code></pre>\n\n<p>$1 referes to the first sub-pattern (at least in PHP). Depending on the language you use it could be slightly different.</p>\n\n<p>This should replace all occurencies of \"Paris\" with the link in the replacement. It just checks whether all opening a-Tags were closed before \"Paris\".</p>\n\n<p>PHP example:</p>\n\n<pre><code><?php\n$s = 'i\\'m living <a href=\"Paris\" atl=\"Paris link\">in Paris</a>, near Paris <a href=\"gare\">Gare du Nord</a>, i love Paris.'; \n$regex = '!(<a.*</a>.*)*Paris!isU'; \n$replace = '$1<a href=\"Paris\">Paris</a>'; \n$result = preg_replace( $regex, $replace, $s); \n?>\n</code></pre>\n\n<p>Addition:</p>\n\n<p>This is not the best solution. One situation where this regex won't work is when you have a img-Tag, which is not within an a-Element. When you set the title-Attribute of that image to \"Paris\", this \"Paris\" will be replaced, too. And that's not what you want.\nNevertheless I see no way to solve your problem completely with a simple regular expression.</p>\n"
},
{
"answer_id": 276078,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>Traditional answer for such question: use a real HTML parser. Because REs aren't really good at operating in a context. And HTML is complex, a 'a' tag can have attributes or not, in any order, can have HTML in the link or not, etc.</p>\n"
},
{
"answer_id": 276109,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>This is hard to do in one step. Writing a single regex that does that is virtually impossible.</p>\n\n<p>Try a two-step approach.</p>\n\n<ol>\n<li>Put a link around every \"Paris\" there is, regardless if there already is another link present.</li>\n<li>Find all incorrectly nested links (<code><a href=\"...\"><a href=\"...\">Paris</a></a></code>), and eliminate the inner link.</li>\n</ol>\n\n<p>Regex for step one is dead-simple:</p>\n\n<pre><code>\\bParis\\b\n</code></pre>\n\n<p>Regex for step two is slightly more complex:</p>\n\n<pre><code>(<a[^>]+>.*?(?!:</a>))<a[^>]+>(Paris)</a>\n</code></pre>\n\n<p>Use that one on the whole string and replace it with the content of match groups 1 and 2, effectively removing the surplus inner link.</p>\n\n<p>Explanation of regex #2 in plain words:</p>\n\n<ul>\n<li>Find every link (<code><a[^>]+></code>), optionally followed by anything that is not itself followed by a closing link (<code>.*?(?!:</a>)</code>). Save it into match group 1.</li>\n<li>Now look for the next link (<code><a[^>]+></code>). Make sure it is there, but do not save it.</li>\n<li>Now look for the word Paris. Save it into match group 2.</li>\n<li>Look for a closing link (<code></a></code>). Make sure it is there, but don't save it.</li>\n<li>Replace everything with the content of groups 1 and 2, thereby losing everything you did not save.</li>\n</ul>\n\n<p>The approach assumes these side conditions:</p>\n\n<ul>\n<li>Your input HTML is not horribly broken.</li>\n<li>Your regex flavor supports non-greedy quantifiers (.*?) and zero-width negative look-ahead assertions (<code>(?!:...)</code>).</li>\n<li>You wrap the word \"Paris\" only in a link in step 1, no additional characters. Every \"<code>Paris</code>\" becomes \"<code><a href\"...\">Paris</a></code>\", or step two will fail (until you change the second regex).</li>\n<li><p>BTW: regex #2 explicitly allows for constructs like this:</p>\n\n<p><code><a href=\"\">in the <b>capital of France</b>, <a href=\"\">Paris</a></a></code></p>\n\n<p>The surplus link comes from step one, replacement result of step 2 will be:</p>\n\n<p><code><a href=\"\">in the <b>capital of France</b>, Paris</a></code></p></li>\n</ul>\n"
},
{
"answer_id": 276634,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 0,
"selected": false,
"text": "<p>If you weren't limited to using Regular expressions in this case, XSLT is a good choice for a language in which you can define this replacement, because it 'understands' XML. </p>\n\n<p>You define two templates:\nOne template finds links and removes those links that don't have \"Paris\" as the body text. Another template finds everything else, splits it into words and adds tags.</p>\n"
},
{
"answer_id": 276800,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": -1,
"selected": false,
"text": "<p>Regexes don't replace. Languages do.</p>\n\n<p>Languages and libraries would also read from the database or file that holds the list of words you care about, and associate a URL with their name. Here's the easiest substitution I can imagine possible my a single regex (perl is used for the <em>replacement</em> syntax.) </p>\n\n<pre><code>s/([a-z-']+)/<a href=\"http:\\/\\/en.wikipedia.org\\/wiki\\/$1\">$1<\\/a>/i\n</code></pre>\n\n<p>Proper names might work better:</p>\n\n<pre><code>s/([A-Z][a-z-']+)/<a href=\"http:\\/\\/en.wikipedia.org\\/wiki\\/$1\">$1<\\/a>/gi;\n</code></pre>\n\n<p>Of course \"Baton Rouge\" would become two links for:</p>\n\n<pre><code><a href=\"http://en.wikipedia.org/wiki/Baton\">Baton</a> \n<a href=\"http://en.wikipedia.org/wiki/Rouge\">Rouge</a>\n</code></pre>\n\n<p>In <em>Perl</em>, you can do this:</p>\n\n<pre><code>my $barred_list_of_cities \n = join( '|'\n , sort { ( length $a <=> $b ) || ( $a cmp $b ) } keys %url_for_city_of\n );\ns/($barred_list_of_cities)/<a href=\"$url_for_city_of{$1}\">$1<\\/a>/g;\n</code></pre>\n\n<p>But again, it's a <em>language</em> that implements a set of operations for regexes, regexes don't do a thing. (In reality, it's such a common application, that I'd be surprised if there isn't a <a href=\"http://cpan.org/\" rel=\"nofollow noreferrer\">CPAN</a> module out there somewhere that does this, and you just need to load the hash. </p>\n"
},
{
"answer_id": 280398,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 3,
"selected": true,
"text": "<p>You could search for this regular expression:</p>\n\n<pre><code>(<a[^>]*>.*?</a>)|Paris\n</code></pre>\n\n<p>This regex matches a link, which it captures into the first (and only) capturing group, or the word Paris.</p>\n\n<p>Replace the match with your link only if the capturing group did not match anything.</p>\n\n<p>E.g. in C#:</p>\n\n<pre><code>resultString = \n Regex.Replace(\n subjectString, \n \"(<a[^>]*>.*?</a>)|Paris\", \n new MatchEvaluator(ComputeReplacement));\n\npublic String ComputeReplacement(Match m) {\n if (m.groups(1).Success) {\n return m.groups(1).Value;\n } else {\n return \"<a href=\\\"link to paris\\\">Paris</a>\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3467838,
"author": "alexfv",
"author_id": 418418,
"author_profile": "https://Stackoverflow.com/users/418418",
"pm_score": 0,
"selected": false,
"text": "<pre><code> $pattern = 'Paris';\n $text = 'i\\'m living <a href=\"Paris\" atl=\"Paris link\">in Paris</a>, near Paris <a href=\"gare\">Gare du Nord</a>, i love Paris.';\n\n // 1. Define 2 arrays:\n // $matches[1] - array of links with our keyword\n // $matches[2] - array of keyword\n preg_match_all('@(<a[^>]*?>[^<]*?'.$pattern.'[^<]*?</a>)|(?<!\\pL)('.$pattern.')(?!\\pL)@', $text, $matches);\n\n // Exists keywords for replace? Define first keyword without tag <a>\n $number = array_search($pattern, $matches[2]);\n\n // Keyword exists, let's go rock\n if ($number !== FALSE) {\n\n // Replace all link with temporary value\n foreach ($matches[1] as $k => $tag) {\n $text = preg_replace('@(<a[^>]*?>[^<]*?'.$pattern.'[^<]*?</a>)@', 'KEYWORD_IS_ALREADY_LINK_'.$k, $text, 1);\n }\n\n // Replace our keywords with link\n $text = preg_replace('/(?<!\\pL)('.$pattern.')(?!\\pL)/', '<a href=\"\">'.$pattern.'</a>', $text);\n\n // Return link\n foreach ($matches[1] as $k => $tag) {\n\n $text = str_replace('KEYWORD_IS_ALREADY_LINK_'.$k, $tag, $text);\n }\n\n // It's work!\n echo $text;\n }\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35937/"
] |
I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.
Example:
```
i'm living <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>, i love Paris.
```
would become
```
i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.
```
|
You could search for this regular expression:
```
(<a[^>]*>.*?</a>)|Paris
```
This regex matches a link, which it captures into the first (and only) capturing group, or the word Paris.
Replace the match with your link only if the capturing group did not match anything.
E.g. in C#:
```
resultString =
Regex.Replace(
subjectString,
"(<a[^>]*>.*?</a>)|Paris",
new MatchEvaluator(ComputeReplacement));
public String ComputeReplacement(Match m) {
if (m.groups(1).Success) {
return m.groups(1).Value;
} else {
return "<a href=\"link to paris\">Paris</a>";
}
}
```
|
276,033 |
<p>How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?</p>
<p>To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.</p>
|
[
{
"answer_id": 276039,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 1,
"selected": false,
"text": "<p>Presumably there's more to this question than it first appears.</p>\n\n<p>FTP supports DIR to list directory contents, RMDIR to remove directories and DEL to delete files, so it supports the operations you need.</p>\n\n<p>Or are you asking how to iterate over an FTP directory tree?</p>\n\n<p>Do you have a preferred/required implementation language for this?</p>\n"
},
{
"answer_id": 276407,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly.</p>\n\n<pre><code>function scan_ftp_dir($conn, $dir, $pattern) {\n $files = ftp_nlist($conn, $dir);\n if (!$files) {\n return;\n }\n\n foreach ($files as $file) {\n //the quickest way i can think of to check if is a directory\n if (ftp_size($conn, $file) == -1) {\n\n //get just the directory name\n $dirName = substr($file, strrpos($file, '/') + 1);\n\n if (preg_match($pattern, $dirName)) {\n echo $file . ' matched pattern';\n } else { \n //directory didn't match pattern, recurse \n scan_ftp_dir($conn, $file, $pattern);\n }\n } \n }\n}\n</code></pre>\n\n<p>Then do something like this</p>\n\n<pre><code>$host = 'localhost';\n$user = 'user';\n$pass = 'pass';\n\n\nif (false === ($conn = ftp_connect($host))) {\n die ('cannot connect');\n}\n\nif (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');\n\n\nscan_ftp_dir($conn, '.', '/^beginswith/');\n</code></pre>\n\n<p>Unfortunately you can only delete an empty directory with <code>ftp_rmdir()</code>, but if you look <a href=\"http://theserverpages.com/php/manual/en/function.ftp-rmdir.php\" rel=\"nofollow noreferrer\">here</a> there is a function called <code>ftp_rmAll()</code> which you could use to remove whole directory structures which you find.</p>\n\n<p>Also I have only tested on Unix the trick of using the fail status returned from <code>ftp_size()</code> as a method of checking if an item returned by <code>ftp_nlist()</code> is a directory.</p>\n"
},
{
"answer_id": 294076,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 0,
"selected": false,
"text": "<p>Well, this is the script I ended up using. It's a rather specific instance where one would have to use this, but if you are in the same predicament I was in, simply put in your ftp server address, username, password, the name of the folders you want deleted, and the path of the folder to start in and this will iterate through the directory, deleting all folders that match the name. There is a bug with reconnecting if the connection to the server is broken so you might need to run the script again if it disconnects.</p>\n\n<pre><code>\nif( $argc == 2 ) {\n $directoryToSearch = $argv[1];\n $host = '';\n $username = '';\n $password = '';\n $connection = connect( $host, $username, $password );\n deleteDirectoriesWithName( $connection, 'directoryToDelete', $directoryToSearch );\n ftp_close( $connection );\n exit( 0 );\n}\nelse {\n cliPrint( \"This script currently only supports 1 argument.\\n\");\n cliPrint( \"Usage: php deleteDirectories.php directoryNameToSearch\\n\");\n exit( 1 );\n}\n\n/**\n * Recursively traverse directories and files starting with the path\n * passed in and then delete all directories that match the name\n * passed in\n * @param $connection the connection resource to the database. \n * @param $name the name of the directories that should be * deleted.\n * @param $path the path to start searching from\n */\nfunction deleteDirectoriesWithName( &$connection, $name, $path ) {\n global $host, $username, $password;\n cliPrint( \"At path: $path\\n\" );\n //Get a list of files in the directory\n $list = ftp_nlist( $connection, $path );\n if ( empty( $list ) ) {\n $rawList = ftp_rawlist( $connection, $path );\n if( empty( $rawList ) ) {\n cliPrint( \"Reconnecting\\n\");\n ftp_close( $connection );\n $connection = connect( $host, $username, $password );\n cliPrint( \"Reconnected\\n\" );\n deleteDirectoriesWithName( $connection, $name, $path );\n return true;\n }\n\n $pathToPass = addSlashToEnd( $path );\n $list = RawlistToNlist( $rawList, $pathToPass );\n }\n //If we have selected a directory, then 'visit' the files (or directories) in the dir\n if ( $list[0] != $path ) {\n $path = addSlashToEnd( $path );\n //iterate through all of the items listed in the directory\n foreach ( $list as $item ) {\n //if the directory matches the name to be deleted, delete it recursively\n if ( $item == $name ) {\n DeleteDirRecursive( $connection, $path . $item );\n }\n\n //otherwise continue traversing\n else if ( $item != '..' && $item != '.' ) {\n deleteDirectoriesWithName( $connection, $name, $path . $item );\n }\n }\n }\n return true;\n}\n\n/**\n *Put output to STDOUT\n */\nfunction cliPrint( $string ) {\n fwrite( STDOUT, $string );\n}\n\n/**\n *Connect to the ftp server\n */\nfunction connect( $host, $username, $password ) {\n $connection = ftp_connect( $host );\n if ( !$connection ) {\n die('Could not connect to server: ' . $host );\n }\n $loginSuccessful = ftp_login( $connection, $username, $password );\n if ( !$loginSuccessful ) {\n die( 'Could not login as: ' . $username . '@' . $host );\n }\n cliPrint( \"Connection successful\\n\" );\n return $connection;\n}\n\n/**\n * Delete the provided directory and all its contents from the FTP-server.\n *\n * @param string $path Path to the directory on the FTP-server relative to\n * the current working directory\n */\nfunction DeleteDirRecursive(&$resource, $path) {\n global $host, $username, $password;\n cliPrint( $path . \"\\n\" );\n $result_message = \"\";\n\n //Get a list of files and directories in the current directory\n $list = ftp_nlist($resource, $path);\n\n if ( empty($list) ) {\n $listToPass = ftp_rawlist( $resource, $path );\n if ( empty( $listToPass ) ) {\n cliPrint( \"Reconnecting\\n\" );\n ftp_close( $resource );\n $resource = connect( $host, $username, $password );\n $result_message = \"Reconnected\\n\";\n cliPrint( \"Reconnected\\n\" );\n $result_message .= DeleteDirRecursive( $resource, $path );\n return $result_message;\n }\n $list = RawlistToNlist( $listToPass, addSlashToEnd( $path ) );\n }\n\n //if the current path is a directory, recursively delete the file within and then\n //delete the empty directory\n if ($list[0] != $path) {\n $path = addSlashToEnd( $path );\n foreach ($list as $item) {\n if ($item != \"..\" && $item != \".\") {\n $result_message .= DeleteDirRecursive($resource, $path . $item);\n }\n }\n cliPrint( 'Delete: ' . $path . \"\\n\" );\n if (ftp_rmdir ($resource, $path)) {\n\n cliPrint( \"Successfully deleted $path\\n\" );\n } else {\n\n cliPrint( \"There was a problem deleting $path\\n\" );\n }\n }\n //otherwise delete the file\n else {\n cliPrint( 'Delete file: ' . $path . \"\\n\" );\n if (ftp_delete ($resource, $path)) {\n cliPrint( \"Successfully deleted $path\\n\" );\n } else {\n\n cliPrint( \"There was a problem deleting $path\\n\" );\n }\n }\n return $result_message;\n}\n\n/**\n* Convert a result from ftp_rawlist() to a result of ftp_nlist()\n*\n* @param array $rawlist Result from ftp_rawlist();\n* @param string $path Path to the directory on the FTP-server relative \n* to the current working directory\n* @return array An array with the paths of the files in the directory\n*/\nfunction RawlistToNlist($rawlist, $path) {\n $array = array();\n foreach ($rawlist as $item) {\n $filename = trim(substr($item, 55, strlen($item) - 55));\n if ($filename != \".\" || $filename != \"..\") {\n $array[] = $filename;\n }\n }\n return $array;\n}\n\n/**\n *Adds a '/' to the end of the path if it is not already present.\n */\nfunction addSlashToEnd( $path ) {\n $endOfPath = substr( $path, strlen( $path ) - 1, 1 );\n if( $endOfPath == '/' ) {\n $pathEnding = '';\n }\n else {\n $pathEnding = '/';\n }\n\n return $path . $pathEnding;\n}\n</code>\n</pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] |
How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?
To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.
|
Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly.
```
function scan_ftp_dir($conn, $dir, $pattern) {
$files = ftp_nlist($conn, $dir);
if (!$files) {
return;
}
foreach ($files as $file) {
//the quickest way i can think of to check if is a directory
if (ftp_size($conn, $file) == -1) {
//get just the directory name
$dirName = substr($file, strrpos($file, '/') + 1);
if (preg_match($pattern, $dirName)) {
echo $file . ' matched pattern';
} else {
//directory didn't match pattern, recurse
scan_ftp_dir($conn, $file, $pattern);
}
}
}
}
```
Then do something like this
```
$host = 'localhost';
$user = 'user';
$pass = 'pass';
if (false === ($conn = ftp_connect($host))) {
die ('cannot connect');
}
if (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');
scan_ftp_dir($conn, '.', '/^beginswith/');
```
Unfortunately you can only delete an empty directory with `ftp_rmdir()`, but if you look [here](http://theserverpages.com/php/manual/en/function.ftp-rmdir.php) there is a function called `ftp_rmAll()` which you could use to remove whole directory structures which you find.
Also I have only tested on Unix the trick of using the fail status returned from `ftp_size()` as a method of checking if an item returned by `ftp_nlist()` is a directory.
|
276,040 |
<p>Generally I connect and retrieve data using the standard way (error checking removed for simplicity):</p>
<pre><code>$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
</code></pre>
<p>Where my_function does some useful things witht that particular row.</p>
<p>What is the equivalent code using objects?</p>
|
[
{
"answer_id": 276059,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the mysql_fetch_object()</p>\n\n<p><a href=\"http://is2.php.net/manual/en/function.mysql-fetch-object.php\" rel=\"nofollow noreferrer\">http://is2.php.net/manual/en/function.mysql-fetch-object.php</a></p>\n"
},
{
"answer_id": 276065,
"author": "I GIVE TERRIBLE ADVICE",
"author_id": 35344,
"author_profile": "https://Stackoverflow.com/users/35344",
"pm_score": 3,
"selected": true,
"text": "<p>Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.</p>\n\n<pre><code>$dbh = new PDO(\"mysql:host=$hostname;dbname=$db\", $username, $password); //connect to the database\n//each :keyword represents a parameter or value to be bound later\n$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');\n\n# Variables are set here.\n$query->bindParam(':id', $id); // this is a pass by reference \n$query->bindValue(':pass', $pass); // this is a pass by value\n\n$query->execute(); // query is run\n\n// to get all the data at once\n$res = $query->fetchall();\nprint_r($res);\n</code></pre>\n\n<p>see <a href=\"http://ca3.php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO driver at php.net</a></p>\n\n<p>Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.</p>\n\n<p>There is also the <a href=\"http://ca3.php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">mysqli</a> extension to do a similar task, but I personally find PDO to be cleaner.</p>\n\n<p>What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.</p>\n\n<p>You can then use <a href=\"http://ca3.php.net/manual/en/pdostatement.fetchobject.php\" rel=\"nofollow noreferrer\">$query->fetchobject</a> to retrieve your data as an object.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
Generally I connect and retrieve data using the standard way (error checking removed for simplicity):
```
$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
```
Where my\_function does some useful things witht that particular row.
What is the equivalent code using objects?
|
Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.
```
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference
$query->bindValue(':pass', $pass); // this is a pass by value
$query->execute(); // query is run
// to get all the data at once
$res = $query->fetchall();
print_r($res);
```
see [PDO driver at php.net](http://ca3.php.net/manual/en/book.pdo.php)
Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.
There is also the [mysqli](http://ca3.php.net/manual/en/book.mysqli.php) extension to do a similar task, but I personally find PDO to be cleaner.
What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.
You can then use [$query->fetchobject](http://ca3.php.net/manual/en/pdostatement.fetchobject.php) to retrieve your data as an object.
|
276,052 |
<p>How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.</p>
<p>There seems to be a few possible ways of extracting that from my search:</p>
<ol>
<li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/" rel="noreferrer">PSI</a> (that currently seems not actively developed and not supported on multiple platforms) or something like <a href="http://www.i-scream.org/pystatgrab/" rel="noreferrer">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p>
</li>
<li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/" rel="noreferrer">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p>
</li>
</ol>
<p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
|
[
{
"answer_id": 276164,
"author": "user35952",
"author_id": 35952,
"author_profile": "https://Stackoverflow.com/users/35952",
"pm_score": -1,
"selected": false,
"text": "<p>I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above. </p>\n"
},
{
"answer_id": 276304,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "<p>\"... current system status (current CPU, RAM, free disk space, etc.)\" And \"*nix and Windows platforms\" can be a difficult combination to achieve.</p>\n\n<p>The operating systems are fundamentally different in the way they manage these resources. Indeed, they differ in core concepts like defining what counts as system and what counts as application time.</p>\n\n<p>\"Free disk space\"? What counts as \"disk space?\" All partitions of all devices? What about foreign partitions in a multi-boot environment?</p>\n\n<p>I don't think there's a clear enough consensus between Windows and *nix that makes this possible. Indeed, there may not even be any consensus between the various operating systems called Windows. Is there a single Windows API that works for both XP and Vista?</p>\n"
},
{
"answer_id": 276934,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 4,
"selected": false,
"text": "<p>Here's something I put together a while ago, it's windows only but may help you get part of what you need done.</p>\n<p>Derived from:\n"for sys available mem"\n<a href=\"http://msdn2.microsoft.com/en-us/library/aa455130.aspx\" rel=\"nofollow noreferrer\">http://msdn2.microsoft.com/en-us/library/aa455130.aspx</a></p>\n<p>"individual process information and python script examples"\n<a href=\"http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true</a></p>\n<p>NOTE: the WMI interface/process is also available for performing similar tasks\nI'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this, then may want to investigate the WMI tools a vailable.</p>\n<p>WMI for python:</p>\n<p><a href=\"http://tgolden.sc.sabren.com/python/wmi.html\" rel=\"nofollow noreferrer\">http://tgolden.sc.sabren.com/python/wmi.html</a></p>\n<p>The code:</p>\n<pre><code>'''\nMonitor window processes\n\nderived from:\n>for sys available mem\nhttp://msdn2.microsoft.com/en-us/library/aa455130.aspx\n\n> individual process information and python script examples\nhttp://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true\n\nNOTE: the WMI interface/process is also available for performing similar tasks\n I'm not using it here because the current method covers my needs, but if someday it's needed\n to extend or improve this module, then may want to investigate the WMI tools available.\n WMI for python:\n http://tgolden.sc.sabren.com/python/wmi.html\n'''\n\n__revision__ = 3\n\nimport win32com.client\nfrom ctypes import *\nfrom ctypes.wintypes import *\nimport pythoncom\nimport pywintypes\nimport datetime\n\n\nclass MEMORYSTATUS(Structure):\n _fields_ = [\n ('dwLength', DWORD),\n ('dwMemoryLoad', DWORD),\n ('dwTotalPhys', DWORD),\n ('dwAvailPhys', DWORD),\n ('dwTotalPageFile', DWORD),\n ('dwAvailPageFile', DWORD),\n ('dwTotalVirtual', DWORD),\n ('dwAvailVirtual', DWORD),\n ]\n\n\ndef winmem():\n x = MEMORYSTATUS() # create the structure\n windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes\n return x \n\n\nclass process_stats:\n '''process_stats is able to provide counters of (all?) the items available in perfmon.\n Refer to the self.supported_types keys for the currently supported 'Performance Objects'\n \n To add logging support for other data you can derive the necessary data from perfmon:\n ---------\n perfmon can be run from windows 'run' menu by entering 'perfmon' and enter.\n Clicking on the '+' will open the 'add counters' menu,\n From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key.\n --> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent)\n For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary,\n keyed by the 'Performance Object' name as mentioned above.\n ---------\n \n NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly.\n \n Initially the python implementation was derived from:\n http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true\n '''\n def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]):\n '''process_names_list == the list of all processes to log (if empty log all)\n perf_object_list == list of process counters to log\n filter_list == list of text to filter\n print_results == boolean, output to stdout\n '''\n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n \n self.process_name_list = process_name_list\n self.perf_object_list = perf_object_list\n self.filter_list = filter_list\n \n self.win32_perf_base = 'Win32_PerfFormattedData_'\n \n # Define new datatypes here!\n self.supported_types = {\n 'NETFramework_NETCLRMemory': [\n 'Name',\n 'NumberTotalCommittedBytes',\n 'NumberTotalReservedBytes',\n 'NumberInducedGC', \n 'NumberGen0Collections',\n 'NumberGen1Collections',\n 'NumberGen2Collections',\n 'PromotedMemoryFromGen0',\n 'PromotedMemoryFromGen1',\n 'PercentTimeInGC',\n 'LargeObjectHeapSize'\n ],\n \n 'PerfProc_Process': [\n 'Name',\n 'PrivateBytes',\n 'ElapsedTime',\n 'IDProcess',# pid\n 'Caption',\n 'CreatingProcessID',\n 'Description',\n 'IODataBytesPersec',\n 'IODataOperationsPersec',\n 'IOOtherBytesPersec',\n 'IOOtherOperationsPersec',\n 'IOReadBytesPersec',\n 'IOReadOperationsPersec',\n 'IOWriteBytesPersec',\n 'IOWriteOperationsPersec' \n ]\n }\n \n def get_pid_stats(self, pid):\n this_proc_dict = {}\n \n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n if not self.perf_object_list:\n perf_object_list = self.supported_types.keys()\n \n for counter_type in perf_object_list:\n strComputer = "."\n objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")\n objSWbemServices = objWMIService.ConnectServer(strComputer,"root\\cimv2")\n \n query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)\n colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread \n \n if len(colItems) > 0: \n for objItem in colItems:\n if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess:\n \n for attribute in self.supported_types[counter_type]:\n eval_str = 'objItem.%s' % (attribute)\n this_proc_dict[attribute] = eval(eval_str)\n \n this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]\n break\n\n return this_proc_dict \n \n \n def get_stats(self):\n '''\n Show process stats for all processes in given list, if none given return all processes \n If filter list is defined return only the items that match or contained in the list\n Returns a list of result dictionaries\n ''' \n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n proc_results_list = []\n if not self.perf_object_list:\n perf_object_list = self.supported_types.keys()\n \n for counter_type in perf_object_list:\n strComputer = "."\n objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")\n objSWbemServices = objWMIService.ConnectServer(strComputer,"root\\cimv2")\n \n query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)\n colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread\n \n try: \n if len(colItems) > 0:\n for objItem in colItems:\n found_flag = False\n this_proc_dict = {}\n \n if not self.process_name_list:\n found_flag = True\n else:\n # Check if process name is in the process name list, allow print if it is\n for proc_name in self.process_name_list:\n obj_name = objItem.Name\n if proc_name.lower() in obj_name.lower(): # will log if contains name\n found_flag = True\n break\n \n if found_flag:\n for attribute in self.supported_types[counter_type]:\n eval_str = 'objItem.%s' % (attribute)\n this_proc_dict[attribute] = eval(eval_str)\n \n this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]\n proc_results_list.append(this_proc_dict)\n \n except pywintypes.com_error, err_msg:\n # Ignore and continue (proc_mem_logger calls this function once per second)\n continue\n return proc_results_list \n\n \ndef get_sys_stats():\n ''' Returns a dictionary of the system stats'''\n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n x = winmem()\n \n sys_dict = { \n 'dwAvailPhys': x.dwAvailPhys,\n 'dwAvailVirtual':x.dwAvailVirtual\n }\n return sys_dict\n\n \nif __name__ == '__main__':\n # This area used for testing only\n sys_dict = get_sys_stats()\n \n stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[])\n proc_results = stats_processor.get_stats()\n \n for result_dict in proc_results:\n print result_dict\n \n import os\n this_pid = os.getpid()\n this_proc_results = stats_processor.get_pid_stats(this_pid)\n \n print 'this proc results:'\n print this_proc_results\n</code></pre>\n"
},
{
"answer_id": 2468983,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 10,
"selected": true,
"text": "<p><a href=\"https://pypi.python.org/pypi/psutil\" rel=\"noreferrer\">The psutil library</a> gives you information about CPU, RAM, etc., on a variety of platforms:</p>\n<blockquote>\n<p>psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.</p>\n<p>It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).</p>\n</blockquote>\n<hr />\n<p>Some examples:</p>\n<pre><code>#!/usr/bin/env python\nimport psutil\n# gives a single float value\npsutil.cpu_percent()\n# gives an object with many fields\npsutil.virtual_memory()\n# you can convert that object to a dictionary \ndict(psutil.virtual_memory()._asdict())\n# you can have the percentage of used RAM\npsutil.virtual_memory().percent\n79.2\n# you can calculate percentage of available memory\npsutil.virtual_memory().available * 100 / psutil.virtual_memory().total\n20.8\n</code></pre>\n<p>Here's other documentation that provides more concepts and interest concepts:</p>\n<ul>\n<li><a href=\"https://psutil.readthedocs.io/en/latest/\" rel=\"noreferrer\">https://psutil.readthedocs.io/en/latest/</a></li>\n</ul>\n"
},
{
"answer_id": 36337011,
"author": "LeoG",
"author_id": 2390826,
"author_profile": "https://Stackoverflow.com/users/2390826",
"pm_score": 1,
"selected": false,
"text": "<p>You can use psutil or psmem with subprocess\nexample code</p>\n<pre><code>import subprocess\ncmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) \nout,error = cmd.communicate() \nmemory = out.splitlines()\n</code></pre>\n<p>Reference</p>\n<p><a href=\"https://github.com/Leo-g/python-flask-cmd\" rel=\"nofollow noreferrer\">https://github.com/Leo-g/python-flask-cmd</a></p>\n"
},
{
"answer_id": 38984517,
"author": "wordsforthewise",
"author_id": 4549682,
"author_profile": "https://Stackoverflow.com/users/4549682",
"pm_score": 7,
"selected": false,
"text": "<p>Use the <a href=\"https://pypi.org/project/psutil/\" rel=\"noreferrer\">psutil library</a>. On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently.\nYou can check your version of psutil by doing this in Python:</p>\n<pre><code>from __future__ import print_function # for Python2\nimport psutil\nprint(psutil.__version__)\n</code></pre>\n<p>To get some memory and CPU stats:</p>\n<pre><code>from __future__ import print_function\nimport psutil\nprint(psutil.cpu_percent())\nprint(psutil.virtual_memory()) # physical memory usage\nprint('memory % used:', psutil.virtual_memory()[2])\n</code></pre>\n<p>The <code>virtual_memory</code> (tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04.</p>\n<p>You can also get the memory used by the current Python instance:</p>\n<pre><code>import os\nimport psutil\npid = os.getpid()\npython_process = psutil.Process(pid)\nmemoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think\nprint('memory use:', memoryUse)\n</code></pre>\n<p>which gives the current memory use of your Python script.</p>\n<p>There are some more in-depth examples on the <a href=\"https://pypi.org/project/psutil/\" rel=\"noreferrer\">pypi page for psutil</a>.</p>\n"
},
{
"answer_id": 42249349,
"author": "CodeGench",
"author_id": 5203370,
"author_profile": "https://Stackoverflow.com/users/5203370",
"pm_score": 5,
"selected": false,
"text": "<p>Below codes, without external libraries worked for me. I tested at Python 2.7.9</p>\n<p><strong>CPU Usage</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n \nCPU_Pct=str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))\nprint("CPU Usage = " + CPU_Pct) # print results\n</code></pre>\n<p><strong>And Ram Usage, Total, Used and Free</strong></p>\n<pre><code>import os\nmem=str(os.popen('free -t -m').readlines())\n"""\nGet a whole line of memory output, it will be something like below\n[' total used free shared buffers cached\\n', \n'Mem: 925 591 334 14 30 355\\n', \n'-/+ buffers/cache: 205 719\\n', \n'Swap: 99 0 99\\n', \n'Total: 1025 591 434\\n']\n So, we need total memory, usage and free memory.\n We should find the index of capital T which is unique at this string\n"""\nT_ind=mem.index('T')\n"""\nThan, we can recreate the string with this information. After T we have,\n"Total: " which has 14 characters, so we can start from index of T +14\nand last 4 characters are also not necessary.\nWe can create a new sub-string using this information\n"""\nmem_G=mem[T_ind+14:-4]\n"""\nThe result will be like\n1025 603 422\nwe need to find first index of the first space, and we can start our substring\nfrom from 0 to this index number, this will give us the string of total memory\n"""\nS1_ind=mem_G.index(' ')\nmem_T=mem_G[0:S1_ind]\n"""\nSimilarly we will create a new sub-string, which will start at the second value. \nThe resulting string will be like\n603 422\nAgain, we should find the index of first space and than the \ntake the Used Memory and Free memory.\n"""\nmem_G1=mem_G[S1_ind+8:]\nS2_ind=mem_G1.index(' ')\nmem_U=mem_G1[0:S2_ind]\n\nmem_F=mem_G1[S2_ind+8:]\nprint 'Summary = ' + mem_G\nprint 'Total Memory = ' + mem_T +' MB'\nprint 'Used Memory = ' + mem_U +' MB'\nprint 'Free Memory = ' + mem_F +' MB'\n</code></pre>\n"
},
{
"answer_id": 42275253,
"author": "Hrabal",
"author_id": 3008185,
"author_profile": "https://Stackoverflow.com/users/3008185",
"pm_score": 6,
"selected": false,
"text": "<p>Only for Linux:\nOne-liner for the RAM usage with only stdlib dependency:</p>\n<pre><code>import os\ntot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])\n</code></pre>\n"
},
{
"answer_id": 49467859,
"author": "anoneemus",
"author_id": 8564727,
"author_profile": "https://Stackoverflow.com/users/8564727",
"pm_score": 3,
"selected": false,
"text": "<p>I feel like these answers were written for Python 2, and in any case nobody's made mention of the standard <a href=\"https://docs.python.org/3/library/resource.html\" rel=\"noreferrer\"><code>resource</code></a> package that's available for Python 3. It provides commands for obtaining the resource <em>limits</em> of a given process (the calling Python process by default). This isn't the same as getting the current <em>usage</em> of resources by the system as a whole, but it could solve some of the same problems like e.g. \"I want to make sure I only use X much RAM with this script.\"</p>\n"
},
{
"answer_id": 52569857,
"author": "Rahul",
"author_id": 1249924,
"author_profile": "https://Stackoverflow.com/users/1249924",
"pm_score": 4,
"selected": false,
"text": "<p>We chose to use usual information source for this because we could find instantaneous fluctuations in free memory and felt querying the <strong>meminfo</strong> data source was helpful. This also helped us get a few more related parameters that were pre-parsed.</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>import os\n\nlinux_filepath = \"/proc/meminfo\"\nmeminfo = dict(\n (i.split()[0].rstrip(\":\"), int(i.split()[1]))\n for i in open(linux_filepath).readlines()\n)\nmeminfo[\"memory_total_gb\"] = meminfo[\"MemTotal\"] / (2 ** 20)\nmeminfo[\"memory_free_gb\"] = meminfo[\"MemFree\"] / (2 ** 20)\nmeminfo[\"memory_available_gb\"] = meminfo[\"MemAvailable\"] / (2 ** 20)\n</code></pre>\n\n<p><strong>Output for reference</strong> (we stripped all newlines for further analysis)</p>\n\n<blockquote>\n <p>MemTotal: 1014500 kB MemFree: 562680 kB MemAvailable: 646364 kB\n Buffers: 15144 kB Cached: 210720 kB SwapCached: 0 kB Active: 261476 kB\n Inactive: 128888 kB Active(anon): 167092 kB Inactive(anon): 20888 kB\n Active(file): 94384 kB Inactive(file): 108000 kB Unevictable: 3652 kB\n Mlocked: 3652 kB SwapTotal: 0 kB SwapFree: 0 kB Dirty: 0 kB Writeback:\n 0 kB AnonPages: 168160 kB Mapped: 81352 kB Shmem: 21060 kB Slab: 34492\n kB SReclaimable: 18044 kB SUnreclaim: 16448 kB KernelStack: 2672 kB\n PageTables: 8180 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB\n CommitLimit: 507248 kB Committed_AS: 1038756 kB VmallocTotal:\n 34359738367 kB VmallocUsed: 0 kB VmallocChunk: 0 kB HardwareCorrupted:\n 0 kB AnonHugePages: 88064 kB CmaTotal: 0 kB CmaFree: 0 kB\n HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp:\n 0 Hugepagesize: 2048 kB DirectMap4k: 43008 kB DirectMap2M: 1005568 kB</p>\n</blockquote>\n"
},
{
"answer_id": 52586129,
"author": "Subhash",
"author_id": 9691238,
"author_profile": "https://Stackoverflow.com/users/9691238",
"pm_score": 2,
"selected": false,
"text": "<p>This script for CPU usage:</p>\n\n<pre><code>import os\n\ndef get_cpu_load():\n \"\"\" Returns a list CPU Loads\"\"\"\n result = []\n cmd = \"WMIC CPU GET LoadPercentage \"\n response = os.popen(cmd + ' 2>&1','r').read().strip().split(\"\\r\\n\")\n for load in response[1:]:\n result.append(int(load))\n return result\n\nif __name__ == '__main__':\n print get_cpu_load()\n</code></pre>\n"
},
{
"answer_id": 52933232,
"author": "Jay",
"author_id": 5387972,
"author_profile": "https://Stackoverflow.com/users/5387972",
"pm_score": 1,
"selected": false,
"text": "<p>Based on the cpu usage code by @Hrabal, this is what I use:</p>\n\n<pre><code>from subprocess import Popen, PIPE\n\ndef get_cpu_usage():\n ''' Get CPU usage on Linux by reading /proc/stat '''\n\n sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)\n top_vals = [int(val) for val in sub.communicate()[0].split('\\n')[0].split[1:5]]\n\n return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])\n</code></pre>\n"
},
{
"answer_id": 55782626,
"author": "Saptarshi Ghosh",
"author_id": 11390909,
"author_profile": "https://Stackoverflow.com/users/11390909",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><p>For CPU details use <strong>psutil</strong> library </p>\n\n<blockquote>\n <p><a href=\"https://psutil.readthedocs.io/en/latest/#cpu\" rel=\"nofollow noreferrer\">https://psutil.readthedocs.io/en/latest/#cpu</a> </p>\n</blockquote></li>\n<li><p>For RAM Frequency (in MHz) use the built in Linux library <strong>dmidecode</strong> and manipulate the output a bit ;). this command needs root permission hence supply your password too. just copy the following commend replacing <strong>mypass</strong> with your password </p></li>\n</ul>\n\n<blockquote>\n <p><code>import os</code> <br><br>\n <code>os.system(\"echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2\")</code></p>\n \n <p>------------------- Output ---------------------------<br>\n 1600 MT/s <br> \n Unknown <br>\n 1600 MT/s <br>\n Unknown 0 <br></p>\n</blockquote>\n\n<ul>\n<li>more specificly <br>\n<code>[i for i in os.popen(\"echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2\").read().split(' ') if i.isdigit()]</code></li>\n</ul>\n\n<blockquote>\n <p>-------------------------- output ------------------------- <br>\n ['1600', '1600']</p>\n</blockquote>\n"
},
{
"answer_id": 61910245,
"author": "Pe Dro",
"author_id": 9625777,
"author_profile": "https://Stackoverflow.com/users/9625777",
"pm_score": 4,
"selected": false,
"text": "<p>To get a <strong>line-by-line</strong> memory and time analysis of your program, I suggest using <code>memory_profiler</code> and <code>line_profiler</code>.</p>\n<p><strong>Installation:</strong></p>\n<pre><code># Time profiler\n$ pip install line_profiler\n# Memory profiler\n$ pip install memory_profiler\n# Install the dependency for a faster analysis\n$ pip install psutil\n</code></pre>\n<p>The common part is, you specify which function you want to analyse by using the respective decorators.</p>\n<p>Example: I have several functions in my Python file <code>main.py</code> that I want to analyse. One of them is <code>linearRegressionfit()</code>. I need to use the decorator <code>@profile</code> that helps me profile the code with respect to both: Time & Memory.</p>\n<p><strong>Make the following changes to the function definition</strong></p>\n<pre><code>@profile\ndef linearRegressionfit(Xt,Yt,Xts,Yts):\n lr=LinearRegression()\n model=lr.fit(Xt,Yt)\n predict=lr.predict(Xts)\n # More Code\n</code></pre>\n<p>For <strong>Time Profiling</strong>,</p>\n<p><strong>Run:</strong></p>\n<pre><code>$ kernprof -l -v main.py\n</code></pre>\n<p>Output</p>\n<pre><code>Total time: 0.181071 s\nFile: main.py\nFunction: linearRegressionfit at line 35\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 35 @profile\n 36 def linearRegressionfit(Xt,Yt,Xts,Yts):\n 37 1 52.0 52.0 0.1 lr=LinearRegression()\n 38 1 28942.0 28942.0 75.2 model=lr.fit(Xt,Yt)\n 39 1 1347.0 1347.0 3.5 predict=lr.predict(Xts)\n 40 \n 41 1 4924.0 4924.0 12.8 print("train Accuracy",lr.score(Xt,Yt))\n 42 1 3242.0 3242.0 8.4 print("test Accuracy",lr.score(Xts,Yts))\n</code></pre>\n<p>For <strong>Memory Profiling</strong>,</p>\n<p><strong>Run:</strong></p>\n<pre><code>$ python -m memory_profiler main.py\n</code></pre>\n<p>Output</p>\n<pre><code>Filename: main.py\n\nLine # Mem usage Increment Line Contents\n================================================\n 35 125.992 MiB 125.992 MiB @profile\n 36 def linearRegressionfit(Xt,Yt,Xts,Yts):\n 37 125.992 MiB 0.000 MiB lr=LinearRegression()\n 38 130.547 MiB 4.555 MiB model=lr.fit(Xt,Yt)\n 39 130.547 MiB 0.000 MiB predict=lr.predict(Xts)\n 40 \n 41 130.547 MiB 0.000 MiB print("train Accuracy",lr.score(Xt,Yt))\n 42 130.547 MiB 0.000 MiB print("test Accuracy",lr.score(Xts,Yts))\n</code></pre>\n<p>Also, the memory profiler results can also be plotted using <code>matplotlib</code> using</p>\n<pre><code>$ mprof run main.py\n$ mprof plot\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/EXEXg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/EXEXg.png\" alt=\"enter image description here\" /></a>\nNote: Tested on</p>\n<p><code>line_profiler</code> version == 3.0.2</p>\n<p><code>memory_profiler</code> version == 0.57.0</p>\n<p><code>psutil</code> version == 5.7.0</p>\n<hr />\n<p>EDIT: The results from the profilers can be parsed using the <a href=\"https://github.com/pra-dan/TAMPPA/blob/master/README.md\" rel=\"noreferrer\">TAMPPA</a> package. Using it, we can get line-by-line desired plots as\n<img src=\"https://github.com/pra-dan/TAMPPA/raw/master/resources/mem_res.png\" alt=\"plot\" /></p>\n"
},
{
"answer_id": 62778466,
"author": "sudhirkondle",
"author_id": 10437493,
"author_profile": "https://Stackoverflow.com/users/10437493",
"pm_score": 3,
"selected": false,
"text": "<p>Taken feedback from first response and done small changes</p>\n<pre><code>#!/usr/bin/env python\n#Execute commond on windows machine to install psutil>>>>python -m pip install psutil\nimport psutil\n\nprint (' ')\nprint ('----------------------CPU Information summary----------------------')\nprint (' ')\n\n# gives a single float value\nvcc=psutil.cpu_count()\nprint ('Total number of CPUs :',vcc)\n\nvcpu=psutil.cpu_percent()\nprint ('Total CPUs utilized percentage :',vcpu,'%')\n\nprint (' ')\nprint ('----------------------RAM Information summary----------------------')\nprint (' ')\n# you can convert that object to a dictionary \n#print(dict(psutil.virtual_memory()._asdict()))\n# gives an object with many fields\nvvm=psutil.virtual_memory()\n\nx=dict(psutil.virtual_memory()._asdict())\n\ndef forloop():\n for i in x:\n print (i,"--",x[i]/1024/1024/1024)#Output will be printed in GBs\n\nforloop()\nprint (' ')\nprint ('----------------------RAM Utilization summary----------------------')\nprint (' ')\n# you can have the percentage of used RAM\nprint('Percentage of used RAM :',psutil.virtual_memory().percent,'%')\n#79.2\n# you can calculate percentage of available memory\nprint('Percentage of available RAM :',psutil.virtual_memory().available * 100 / psutil.virtual_memory().total,'%')\n#20.8\n</code></pre>\n"
},
{
"answer_id": 64772402,
"author": "Leroy Kayanda",
"author_id": 1960902,
"author_profile": "https://Stackoverflow.com/users/1960902",
"pm_score": 2,
"selected": false,
"text": "<p>you can read /proc/meminfo to get used memory</p>\n<pre><code>file1 = open('/proc/meminfo', 'r') \n\nfor line in file1: \n if 'MemTotal' in line: \n x = line.split()\n memTotal = int(x[1])\n \n if 'Buffers' in line: \n x = line.split()\n buffers = int(x[1])\n \n if 'Cached' in line and 'SwapCached' not in line: \n x = line.split()\n cached = int(x[1])\n \n if 'MemFree' in line: \n x = line.split()\n memFree = int(x[1])\n\nfile1.close()\n\npercentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )\nprint(percentage_used)\n</code></pre>\n"
},
{
"answer_id": 65236700,
"author": "Rea Haas",
"author_id": 8808983,
"author_profile": "https://Stackoverflow.com/users/8808983",
"pm_score": 3,
"selected": false,
"text": "<p>This aggregate all the goodies:\n<code>psutil</code> + <code>os</code> to get Unix & Windows compatibility:\nThat allows us to get:</p>\n<ol>\n<li>CPU</li>\n<li>memory</li>\n<li>disk</li>\n</ol>\n<p>code:</p>\n<pre><code>import os\nimport psutil # need: pip install psutil\n\nIn [32]: psutil.virtual_memory()\nOut[32]: svmem(total=6247907328, available=2502328320, percent=59.9, used=3327135744, free=167067648, active=3671199744, inactive=1662668800, buffers=844783616, cached=1908920320, shared=123912192, slab=613048320)\n\nIn [33]: psutil.virtual_memory().percent\nOut[33]: 60.0\n\nIn [34]: psutil.cpu_percent()\nOut[34]: 5.5\n\nIn [35]: os.sep\nOut[35]: '/'\n\nIn [36]: psutil.disk_usage(os.sep)\nOut[36]: sdiskusage(total=50190790656, used=41343860736, free=6467502080, percent=86.5)\n\nIn [37]: psutil.disk_usage(os.sep).percent\nOut[37]: 86.5\n</code></pre>\n"
},
{
"answer_id": 68611754,
"author": "CodeFarmer",
"author_id": 479008,
"author_profile": "https://Stackoverflow.com/users/479008",
"pm_score": 0,
"selected": false,
"text": "<p>Run with crontab won't print pid</p>\n<p>Setup: <code>*/1 * * * * sh dog.sh</code> this line in <code>crontab -e</code></p>\n<pre><code>import os\nimport re\n\nCUT_OFF = 90\n\ndef get_cpu_load():\n cmd = "ps -Ao user,uid,comm,pid,pcpu --sort=-pcpu | head -n 2 | tail -1"\n response = os.popen(cmd, 'r').read()\n arr = re.findall(r'\\S+', response)\n print(arr)\n needKill = float(arr[-1]) > CUT_OFF\n if needKill:\n r = os.popen(f"kill -9 {arr[-2]}")\n print('kill:', r)\n\nif __name__ == '__main__':\n # Test CPU with \n # $ stress --cpu 1\n # crontab -e\n # Every 1 min\n # */1 * * * * sh dog.sh\n # ctlr o, ctlr x\n # crontab -l\n print(get_cpu_load())\n</code></pre>\n"
},
{
"answer_id": 69511430,
"author": "Karol Zlot",
"author_id": 8896457,
"author_profile": "https://Stackoverflow.com/users/8896457",
"pm_score": 5,
"selected": false,
"text": "<p>One can get real time CPU and RAM monitoring by combining <code>tqdm</code> and <code>psutil</code>. It may be handy when running heavy computations / processing.</p>\n<p><a href=\"https://i.stack.imgur.com/NaEJh.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NaEJh.gif\" alt=\"cli cpu and ram usage progress bars\" /></a></p>\n<p>It also works in Jupyter without any code changes:</p>\n<p><a href=\"https://i.stack.imgur.com/TWCpo.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TWCpo.gif\" alt=\"Jupyter cpu and ram usage progress bars\" /></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>from tqdm import tqdm\nfrom time import sleep\nimport psutil\n\nwith tqdm(total=100, desc='cpu%', position=1) as cpubar, tqdm(total=100, desc='ram%', position=0) as rambar:\n while True:\n rambar.n=psutil.virtual_memory().percent\n cpubar.n=psutil.cpu_percent()\n rambar.refresh()\n cpubar.refresh()\n sleep(0.5)\n</code></pre>\n<p>It's convenient to put those progress bars in separate process using <a href=\"https://docs.python.org/3/library/multiprocessing.html\" rel=\"noreferrer\">multiprocessing</a> library.</p>\n<p>This code snippet is also <a href=\"https://gist.github.com/karolzlot/26864e21e7347ce41f71f87f156ea266\" rel=\"noreferrer\">available as a gist</a>.</p>\n"
},
{
"answer_id": 70867664,
"author": "Chen Levy",
"author_id": 110488,
"author_profile": "https://Stackoverflow.com/users/110488",
"pm_score": 0,
"selected": false,
"text": "<p>Shell-out not needed for <a href=\"https://stackoverflow.com/users/5203370\">@CodeGench</a>'s <a href=\"https://stackoverflow.com/a/42249349/\">solution</a>, so assuming Linux and Python's standard libraries:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def cpu_load(): \n with open("/proc/stat", "r") as stat:\n (key, user, nice, system, idle, _) = (stat.readline().split(None, 5))\n assert key == "cpu", "'cpu ...' should be the first line in /proc/stat"\n busy = int(user) + int(nice) + int(system)\n return 100 * busy / (busy + int(idle))\n\n</code></pre>\n"
},
{
"answer_id": 74062355,
"author": "user19926715",
"author_id": 19926715,
"author_profile": "https://Stackoverflow.com/users/19926715",
"pm_score": 1,
"selected": false,
"text": "<p>You can always use the library recently released <code>SystemScripter</code> by using the command <code>pip install SystemScripter</code>. This is a library that uses the other library like <code>psutil</code> among others to create a full library of system information that spans from CPU to disk information.\nFor current CPU usage use the function:</p>\n<pre><code>SystemScripter.CPU.CpuPerCurrentUtil(SystemScripter.CPU()) #class init as self param if not work\n</code></pre>\n<p>This gets the usage percentage or use:</p>\n<pre><code>SystemScripter.CPU.CpuCurrentUtil(SystemScripter.CPU())\n</code></pre>\n<p><a href=\"https://pypi.org/project/SystemScripter/#description\" rel=\"nofollow noreferrer\">https://pypi.org/project/SystemScripter/#description</a></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35935/"
] |
How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.
There seems to be a few possible ways of extracting that from my search:
1. Using a library such as [PSI](http://www.psychofx.com/psi/trac/wiki/) (that currently seems not actively developed and not supported on multiple platforms) or something like [pystatgrab](http://www.i-scream.org/pystatgrab/) (again no activity since 2007 it seems and no support for Windows).
2. Using platform specific code such as using a `os.popen("ps")` or similar for the \*nix systems and `MEMORYSTATUS` in `ctypes.windll.kernel32` (see [this recipe on ActiveState](http://code.activestate.com/recipes/511491/)) for the Windows platform. One could put a Python class together with all those code snippets.
It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?
|
[The psutil library](https://pypi.python.org/pypi/psutil) gives you information about CPU, RAM, etc., on a variety of platforms:
>
> psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.
>
>
> It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).
>
>
>
---
Some examples:
```
#!/usr/bin/env python
import psutil
# gives a single float value
psutil.cpu_percent()
# gives an object with many fields
psutil.virtual_memory()
# you can convert that object to a dictionary
dict(psutil.virtual_memory()._asdict())
# you can have the percentage of used RAM
psutil.virtual_memory().percent
79.2
# you can calculate percentage of available memory
psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
20.8
```
Here's other documentation that provides more concepts and interest concepts:
* <https://psutil.readthedocs.io/en/latest/>
|
276,066 |
<p>I need a function count_permutations() that returns the number of permutations of a given range. <em>Assuming that the range is allowed to be modified, and starts at the first permutation,</em> I could naively implement this as repeated calls to next_permutation() as below:</p>
<pre><code>template<class Ret, class Iter>
Ret count_permutations(Iter first, Iter last)
{
Ret ret = 0;
do {
++ret;
} while (next_permutation(first, last));
return ret;
}
</code></pre>
<p><em>Is there a faster way that doesn't require iterating through all the permutations to find the answer? It could still assume that the input can be modified, and starts in the first permutation, but obviously if it is possible to implement without those assumtions it'd be great too.</em></p>
|
[
{
"answer_id": 276068,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 4,
"selected": true,
"text": "<p>The number of permutations for a range where all the elements are unique is n! where n is the length of the range.</p>\n\n<p>If there are duplicate elements, you can use n!/(n_0!)...(n_m!) where n_0...n_m are the lengths of duplicate ranges.</p>\n\n<p>So for example [1,2,3] has 3! = 6 permutations while [1,2,2] has 3!/2! = 3 permutations.</p>\n\n<p><strong>EDIT:</strong> A better example is [1,2,2,3,3,3] which has 6!/2!3! = 60 permutations.</p>\n"
},
{
"answer_id": 276077,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 0,
"selected": false,
"text": "<p>In math the function factorial !n represents the number of permutations of n elements. </p>\n\n<p>As Can Berg and Greg suggested, if there are repeated elements in a set, to take them into account, we must divide the factorial by the number of permutations of each indistinguishable group (groups composed of identical elements).</p>\n\n<p>The following implementation counts the number of permutations of the elements in the range [first, end). The range is not required to be sorted.</p>\n\n<pre><code>// generic factorial implementation...\n\nint factorial(int number) {\n int temp;\n if(number <= 1) return 1;\n temp = number * factorial(number - 1);\n return temp;\n}\n\ntemplate<class Ret, class Iter>\nRet count_permutations(Iter first, Iter end)\n{\n std::map<typename Iter::value_type, int> counter;\n Iter it = first;\n for( ; it != end; ++it) {\n counter[*it]++;\n }\n\n int n = 0;\n typename std::map<typename Iter::value_type, int>::iterator mi = counter.begin();\n for(; mi != counter.end() ; mi++)\n if ( mi->second > 1 )\n n += factorial(mi->second);\n\n return factorial(std::distance(first,end))/n;\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
I need a function count\_permutations() that returns the number of permutations of a given range. *Assuming that the range is allowed to be modified, and starts at the first permutation,* I could naively implement this as repeated calls to next\_permutation() as below:
```
template<class Ret, class Iter>
Ret count_permutations(Iter first, Iter last)
{
Ret ret = 0;
do {
++ret;
} while (next_permutation(first, last));
return ret;
}
```
*Is there a faster way that doesn't require iterating through all the permutations to find the answer? It could still assume that the input can be modified, and starts in the first permutation, but obviously if it is possible to implement without those assumtions it'd be great too.*
|
The number of permutations for a range where all the elements are unique is n! where n is the length of the range.
If there are duplicate elements, you can use n!/(n\_0!)...(n\_m!) where n\_0...n\_m are the lengths of duplicate ranges.
So for example [1,2,3] has 3! = 6 permutations while [1,2,2] has 3!/2! = 3 permutations.
**EDIT:** A better example is [1,2,2,3,3,3] which has 6!/2!3! = 60 permutations.
|
276,072 |
<p>I just picked up Agile Web Development with Rails 3rd Ed., and I'm going thru the Depot Application chapters, and I have a question about Product/Item options.</p>
<p>If I wanted to modify the product catalog and store so that products could have options (size, color, whatever), where/how would I do that?</p>
<p>Let's say I'm selling t-shirts, and they come in different sizes. I don't feel like that's something that really needs a model created to handle sizes, so I thought I could just add it as a select box in the html in the store's view.</p>
<p>But, each Add to Cart button is wrapped by a form tag that is automatically generated by button_to, and doesn't seem to give me the ability to pass additional parameters to my cart. How can I get the size of the item added into the POST to add_to_cart?</p>
<p>The helper in my view:</p>
<pre><code><%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>
</code></pre>
<p>The form that it generates:</p>
<pre><code><form method="post" action="/store/add_to_cart/3" class="button-to">
</code></pre>
|
[
{
"answer_id": 276083,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 0,
"selected": false,
"text": "<p>I'd drop the <code>button_to</code> helper and use a proper form, submitting the product properties to the <code>add_to_cart</code> action.</p>\n\n<pre><code><% form_for(@product) do |f| %>\n<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>\n# other properties...\n<%= f.submit 'Add to Cart' %>\n<% end %>\n</code></pre>\n"
},
{
"answer_id": 277937,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 0,
"selected": false,
"text": "<p>You will need to add attributes to your model. For that, you will need to create a migration to update your database table. I only have the 2nd edition of the book, but there's a section called \"Iteration A2: Add a missing column\" that describes how to do this. I assume a similar section would be in the 3rd edition.</p>\n\n<p>After doing that, you can follow Can Berk Güder's suggestion and replace the button by a form.</p>\n"
},
{
"answer_id": 278388,
"author": "Cameron Price",
"author_id": 35526,
"author_profile": "https://Stackoverflow.com/users/35526",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure why you wouldn't store size, unless what you mean is that you'd store size as part of cart_item rather than product, which would be fine. In that case you'd do something like this:</p>\n\n<pre><code><% form_for(@cart_item) do |f| %>\n<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>\n<%= f.hidden_field :product_id, :value => @product.id %> \n# other properties...\n<%= f.submit 'Add to Cart' %>\n<% end %>\n</code></pre>\n"
},
{
"answer_id": 280000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, it's 2 days later, and I figured it out. This is what I had to do-</p>\n\n<h1>1, in my store view:</h1>\n\n<pre><code><% form_for @product, :url => {:action => \"add_to_cart\", :id => @product} do |f| %>\n <select name=\"productsize\" id=\"productsize\">\n <option value=\"L\">L</option>\n <option value=\"XL\">XL</option>\n </select>\n <%= f.submit 'Add to Cart' %>\n<% end %>\n</code></pre>\n\n<h1>2, added to my store controller:</h1>\n\n<pre><code>productsize = params[:productsize]\[email protected]_product(product, productsize)\n</code></pre>\n\n<p>Had to get productsize from params, and then pass it with the rest of the product model to the cart model's add_product action.</p>\n\n<h1>3, adjusted the cart model to accept the argument, and:</h1>\n\n<pre><code>@items << CartItem.new(product, productsize)\n</code></pre>\n\n<p>Passed it along with the rest of the product model to create a new Cart Item and add it to items.</p>\n\n<h1>4, added to the cart_item model:</h1>\n\n<pre><code>attr_reader :product, :quantity, :productsize\n\ndef initialize(product, productsize)\n@product = product\n@productsize = productsize\n</code></pre>\n\n<p>to read in productsize and initialize Cart Item.</p>\n\n<h1>5, added to my add_to_cart view:</h1>\n\n<pre><code>Size: <%=h item.productsize %>\n</code></pre>\n\n<p>To display it for the user.</p>\n\n<p>That's it. If there is an easier or DRYer way to go about it, I'm all ears (eyes?).</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I just picked up Agile Web Development with Rails 3rd Ed., and I'm going thru the Depot Application chapters, and I have a question about Product/Item options.
If I wanted to modify the product catalog and store so that products could have options (size, color, whatever), where/how would I do that?
Let's say I'm selling t-shirts, and they come in different sizes. I don't feel like that's something that really needs a model created to handle sizes, so I thought I could just add it as a select box in the html in the store's view.
But, each Add to Cart button is wrapped by a form tag that is automatically generated by button\_to, and doesn't seem to give me the ability to pass additional parameters to my cart. How can I get the size of the item added into the POST to add\_to\_cart?
The helper in my view:
```
<%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>
```
The form that it generates:
```
<form method="post" action="/store/add_to_cart/3" class="button-to">
```
|
Ok, it's 2 days later, and I figured it out. This is what I had to do-
1, in my store view:
====================
```
<% form_for @product, :url => {:action => "add_to_cart", :id => @product} do |f| %>
<select name="productsize" id="productsize">
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<%= f.submit 'Add to Cart' %>
<% end %>
```
2, added to my store controller:
================================
```
productsize = params[:productsize]
@cart.add_product(product, productsize)
```
Had to get productsize from params, and then pass it with the rest of the product model to the cart model's add\_product action.
3, adjusted the cart model to accept the argument, and:
=======================================================
```
@items << CartItem.new(product, productsize)
```
Passed it along with the rest of the product model to create a new Cart Item and add it to items.
4, added to the cart\_item model:
=================================
```
attr_reader :product, :quantity, :productsize
def initialize(product, productsize)
@product = product
@productsize = productsize
```
to read in productsize and initialize Cart Item.
5, added to my add\_to\_cart view:
==================================
```
Size: <%=h item.productsize %>
```
To display it for the user.
That's it. If there is an easier or DRYer way to go about it, I'm all ears (eyes?).
|
276,087 |
<p>I am working on a web application that is designed to display a bunch of data that is updated periodically with AJAX. The general usage scenario would be that a user would leave it open all day and take a glance at it now and then.</p>
<p>I am encountering a problem where the browsers memory footprint is growing slowly over time. This is happening in both Firefox and IE 7 (Although not in Chrome). After a few hours, it can cause IE7 to have a footprint of ~200MB and FF3 to have a footprint of ~400MB.</p>
<p>After a lot of testing, I have found that the memory leak only occurs if the AJAX calls are being responded to. If the server doesn't respond to anything, I can leave the page open for hours and the footprint won't grow.</p>
<p>I am using prototype for my AJAX calls. So, I'm guessing there is an issue with the onSuccess callback creating these memory leaks. </p>
<p>Does anyone have any tips on preventing memory leaks with prototype / AJAX? Or any methods on how to troubleshoot this problem?</p>
<p>EDIT: found out the issue lies in a js graphing library I am using. Can be seen <a href="http://code.google.com/p/flotr/issues/detail?id=5" rel="noreferrer">here</a>. </p>
|
[
{
"answer_id": 276092,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": -1,
"selected": false,
"text": "<p>I may be wrong but it sounds like you are creating closures around the response object. Each response object will be different which results in an increased memory footprint.</p>\n"
},
{
"answer_id": 276124,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 5,
"selected": true,
"text": "<p>The biggest thing you can watch out for is events, and how you assign them.</p>\n\n<p>For instance, take this scenario (since you haven't provided one):</p>\n\n<pre><code><div id=\"ajaxResponseTarget\">\n ...\n</div>\n<script type=\"text/javascript\">\n $(someButton).observe('click', function() {\n new Ajax.Updater($('ajaxResponseTarget'), someUrl, {\n onSuccess: function() {\n $$('#ajaxResponseTarget .someButtonClass').invoke('observe', 'click', function() {\n ...\n });\n }\n });\n });\n</script>\n</code></pre>\n\n<p>This will create a memory leak, because when <code>#ajaxResponseTarget</code> is updated (internally, Prototype will use <code>innerHTML</code>) elements with <code>click</code> events will be removed from the document without their events being removed. The second time you click <code>someButton</code>, you will then have twice as many event handlers, and garbage collection can't remove the first set.</p>\n\n<p>A way to avoid this is to use event delegation:</p>\n\n<pre><code><div id=\"ajaxResponseTarget\">\n ...\n</div>\n<script type=\"text/javascript\">\n $('ajaxResponseTarget').observe('click', function(e) {\n if(e.element().match('.someButtonClass')) {\n ...\n }\n });\n $(someButton).observe('click', function() {\n new Ajax.Updater($('ajaxResponseTarget'), someUrl);\n });\n</script>\n</code></pre>\n\n<p>Because of the way DOM events work, the \"click\" on <code>.someButtonClass</code> will fire also on <code>#ajaxResponseTarget</code>, and Prototype makes it dead simple to determine what element was the target of the event. No events are assigned to elements <em>within</em> <code>#ajaxResponseTarget</code>, so there is no way for replacing its contents to orphan events from targets within.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12983/"
] |
I am working on a web application that is designed to display a bunch of data that is updated periodically with AJAX. The general usage scenario would be that a user would leave it open all day and take a glance at it now and then.
I am encountering a problem where the browsers memory footprint is growing slowly over time. This is happening in both Firefox and IE 7 (Although not in Chrome). After a few hours, it can cause IE7 to have a footprint of ~200MB and FF3 to have a footprint of ~400MB.
After a lot of testing, I have found that the memory leak only occurs if the AJAX calls are being responded to. If the server doesn't respond to anything, I can leave the page open for hours and the footprint won't grow.
I am using prototype for my AJAX calls. So, I'm guessing there is an issue with the onSuccess callback creating these memory leaks.
Does anyone have any tips on preventing memory leaks with prototype / AJAX? Or any methods on how to troubleshoot this problem?
EDIT: found out the issue lies in a js graphing library I am using. Can be seen [here](http://code.google.com/p/flotr/issues/detail?id=5).
|
The biggest thing you can watch out for is events, and how you assign them.
For instance, take this scenario (since you haven't provided one):
```
<div id="ajaxResponseTarget">
...
</div>
<script type="text/javascript">
$(someButton).observe('click', function() {
new Ajax.Updater($('ajaxResponseTarget'), someUrl, {
onSuccess: function() {
$$('#ajaxResponseTarget .someButtonClass').invoke('observe', 'click', function() {
...
});
}
});
});
</script>
```
This will create a memory leak, because when `#ajaxResponseTarget` is updated (internally, Prototype will use `innerHTML`) elements with `click` events will be removed from the document without their events being removed. The second time you click `someButton`, you will then have twice as many event handlers, and garbage collection can't remove the first set.
A way to avoid this is to use event delegation:
```
<div id="ajaxResponseTarget">
...
</div>
<script type="text/javascript">
$('ajaxResponseTarget').observe('click', function(e) {
if(e.element().match('.someButtonClass')) {
...
}
});
$(someButton).observe('click', function() {
new Ajax.Updater($('ajaxResponseTarget'), someUrl);
});
</script>
```
Because of the way DOM events work, the "click" on `.someButtonClass` will fire also on `#ajaxResponseTarget`, and Prototype makes it dead simple to determine what element was the target of the event. No events are assigned to elements *within* `#ajaxResponseTarget`, so there is no way for replacing its contents to orphan events from targets within.
|
276,088 |
<p>My ASP.NET application allows users to upload and download large files. Both procedures involve reading and writing filestreams. What should I do to ensure the application doesn't hang or crash when it handles a large file? Should the file operations be handled on a worker thread for example?</p>
|
[
{
"answer_id": 276098,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 2,
"selected": true,
"text": "<p>Make sure you properly buffer the files so that they don't take inordinate amounts of memory in the system.</p>\n\n<p>e.g. excerpt from a download application, inside the while loop that reads the file:</p>\n\n<pre><code>// Read the data in buffer.\nlength = iStream.Read(buffer, 0, bufferSize);\n\n// Write the data to the current output stream.\nResponse.OutputStream.Write(buffer, 0, length);\n</code></pre>\n\n<p>Where bufferSize is something reasonable, e.g. 100000 bytes, the trade-off is that it will be slower for smaller buffer sizes.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/812406\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/812406</a></p>\n\n<p>Edit: Also be sure that IIS is set to take a large enough <a href=\"http://dwnz.spaces.live.com/Blog/cns!BCC0973FC7B19D91!643.entry\" rel=\"nofollow noreferrer\">request length</a> (IIS7) and timeout.</p>\n"
},
{
"answer_id": 276111,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 0,
"selected": false,
"text": "<p>Unless this is the primary purpose of your site consider partitioning these operations to a separate application, e.g. a sub-application or sub-domain. Besides reducing risk this would also simplify scaling out as your user base grows.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
My ASP.NET application allows users to upload and download large files. Both procedures involve reading and writing filestreams. What should I do to ensure the application doesn't hang or crash when it handles a large file? Should the file operations be handled on a worker thread for example?
|
Make sure you properly buffer the files so that they don't take inordinate amounts of memory in the system.
e.g. excerpt from a download application, inside the while loop that reads the file:
```
// Read the data in buffer.
length = iStream.Read(buffer, 0, bufferSize);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
```
Where bufferSize is something reasonable, e.g. 100000 bytes, the trade-off is that it will be slower for smaller buffer sizes.
<http://support.microsoft.com/kb/812406>
Edit: Also be sure that IIS is set to take a large enough [request length](http://dwnz.spaces.live.com/Blog/cns!BCC0973FC7B19D91!643.entry) (IIS7) and timeout.
|
276,099 |
<p>I want to read a mac id from command line and convert it to an array of <code>uint8_t</code> values to use it in a struct. I can not get it to work. I have a vector of string for the mac id split about <code>:</code> and I want to use <code>stringstream</code> to convert them with no luck. What I am missing?</p>
<pre><code>int parseHex(const string &num){
stringstream ss(num);
ss << std::hex;
int n;
ss >> n;
return n;
}
uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
v = StringSplit( mac , ":" );
for( int j = 0 ; j < v.size() ; j++ ){
tgt_mac[j] = parseHex(v.at(j));
}
</code></pre>
|
[
{
"answer_id": 276149,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are using the std::hex in the wrong place:</p>\n\n<pre><code>#include <sstream>\n#include <iostream>\n\nint main()\n{\n std::string h(\"a5\");\n std::stringstream s(h);\n int x;\n\n s >> std::hex >> x;\n std::cout << \"X(\" << x << \")\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 276496,
"author": "Steven",
"author_id": 27577,
"author_profile": "https://Stackoverflow.com/users/27577",
"pm_score": 2,
"selected": false,
"text": "<p>Your problem may be in the output of the parsed data. The \"<<\" operator makes decisions on how to display data based on the data type passed it, and uint8_t may be getting interpretted as a char. Make sure you cast the array values to ints when printing, or investigate in a debugger.</p>\n\n<p>The sample program:</p>\n\n<pre><code>uint8_t tgt_mac[6] = {0};\nstd::stringstream ss( \"AA:BB:CC:DD:EE:11\" );\nchar trash;\n\nfor ( int i = 0; i < 6; i++ )\n{\n int foo;\n ss >> std::hex >> foo >> trash;\n tgt_mac[i] = foo;\n std::cout << std::hex << \"Reading: \" << foo << std::endl;\n}\n\nstd::cout << \"As int array: \" << std::hex\n << (int) tgt_mac[0]\n << \":\"\n << (int) tgt_mac[1]\n << \":\"\n << (int) tgt_mac[2]\n << \":\"\n << (int) tgt_mac[3]\n << \":\"\n << (int) tgt_mac[4]\n << \":\"\n << (int) tgt_mac[5]\n << std::endl;\nstd::cout << \"As unint8_t array: \" << std::hex\n << tgt_mac[0]\n << \":\"\n << tgt_mac[1]\n << \":\"\n << tgt_mac[2]\n << \":\"\n << tgt_mac[3]\n << \":\"\n << tgt_mac[4]\n << \":\"\n << tgt_mac[5]\n << std::endl;\n</code></pre>\n\n<p>Gives the following output ( cygwin g++ )</p>\n\n<pre><code>Reading: aa\nReading: bb\nReading: cc\nReading: dd\nReading: ee\nReading: 11\nAs int array: aa:bb:cc:dd:ee:11\nAs unint8_t array: ª:»:I:Y:î:◄\n</code></pre>\n"
},
{
"answer_id": 276534,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>First I want to point out that I think @Steven's answer is a very good one - indeed I noticed the same: the values are correct, but the output looks awkward. This is due to <code>ostream& operator<<( ostream&, unsigned char )</code> being used, since the <code>uint8_t</code> type you used is a typedef for <code>unsigned char</code> (as I found in the linux man pages). Note that on VC++, the typedef isn't there, and you have to use <code>unsigned __int8</code> instead (which will also route you to the <code>char</code> specialization).</p>\n\n<p>Next, you can <em>test</em> your code like this (output-independent):</p>\n\n<pre><code>assert( uint8_t( parseHex( \"00\" ) ) == uint8_t(0) );\nassert( uint8_t( parseHex( \"01\" ) ) == uint8_t(1) );\n//...\nassert( uint8_t( parseHex( \"ff\" ) ) == uint8_t(255) );\n</code></pre>\n\n<p>In addition to Steven's answer, I just want to point out the existence of the <code>transform</code> algorithm, which could still simplify your code.</p>\n\n<pre><code>for( int j = 0 ; j < v.size() ; j++ ){\n tgt_mac[j] = parseHex(v.at(j)); \n}\n</code></pre>\n\n<p>Writes in one line:</p>\n\n<pre><code>std::transform( v.begin(), v.end(), tgt_mac, &parseHex );\n</code></pre>\n\n<p>(And I know that hasn't to do with the question...)</p>\n\n<p>(See <a href=\"http://codepad.org/d8roEuBP\" rel=\"nofollow noreferrer\">codepad.org</a> for what it then looks like)</p>\n"
},
{
"answer_id": 328332,
"author": "D.Shawley",
"author_id": 41747,
"author_profile": "https://Stackoverflow.com/users/41747",
"pm_score": 2,
"selected": false,
"text": "<p>I hate to answer this in this fashion, but <code>sscanf()</code> is probably the most succinct way to parse out a MAC address. It handles zero/non-zero padding, width checking, case folding, and all of that other stuff that no one likes to deal with. Anyway, here's my not so C++ version:</p>\n\n<pre><code>void\nparse_mac(std::vector<uint8_t>& out, std::string const& in) {\n unsigned int bytes[6];\n if (std::sscanf(in.c_str(),\n \"%02x:%02x:%02x:%02x:%02x:%02x\",\n &bytes[0], &bytes[1], &bytes[2],\n &bytes[3], &bytes[4], &bytes[5]) != 6)\n {\n throw std::runtime_error(in+std::string(\" is an invalid MAC address\"));\n }\n out.assign(&bytes[0], &bytes[6]);\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29742/"
] |
I want to read a mac id from command line and convert it to an array of `uint8_t` values to use it in a struct. I can not get it to work. I have a vector of string for the mac id split about `:` and I want to use `stringstream` to convert them with no luck. What I am missing?
```
int parseHex(const string &num){
stringstream ss(num);
ss << std::hex;
int n;
ss >> n;
return n;
}
uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
v = StringSplit( mac , ":" );
for( int j = 0 ; j < v.size() ; j++ ){
tgt_mac[j] = parseHex(v.at(j));
}
```
|
Your problem may be in the output of the parsed data. The "<<" operator makes decisions on how to display data based on the data type passed it, and uint8\_t may be getting interpretted as a char. Make sure you cast the array values to ints when printing, or investigate in a debugger.
The sample program:
```
uint8_t tgt_mac[6] = {0};
std::stringstream ss( "AA:BB:CC:DD:EE:11" );
char trash;
for ( int i = 0; i < 6; i++ )
{
int foo;
ss >> std::hex >> foo >> trash;
tgt_mac[i] = foo;
std::cout << std::hex << "Reading: " << foo << std::endl;
}
std::cout << "As int array: " << std::hex
<< (int) tgt_mac[0]
<< ":"
<< (int) tgt_mac[1]
<< ":"
<< (int) tgt_mac[2]
<< ":"
<< (int) tgt_mac[3]
<< ":"
<< (int) tgt_mac[4]
<< ":"
<< (int) tgt_mac[5]
<< std::endl;
std::cout << "As unint8_t array: " << std::hex
<< tgt_mac[0]
<< ":"
<< tgt_mac[1]
<< ":"
<< tgt_mac[2]
<< ":"
<< tgt_mac[3]
<< ":"
<< tgt_mac[4]
<< ":"
<< tgt_mac[5]
<< std::endl;
```
Gives the following output ( cygwin g++ )
```
Reading: aa
Reading: bb
Reading: cc
Reading: dd
Reading: ee
Reading: 11
As int array: aa:bb:cc:dd:ee:11
As unint8_t array: ª:»:I:Y:î:◄
```
|
276,102 |
<p>Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?</p>
<p>I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.</p>
<p>something like:</p>
<pre><code>global_catch()
{
MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
exit(-1);
}
global_catch(Exception *except)
{
MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
exit(-1);
}
</code></pre>
|
[
{
"answer_id": 276110,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 6,
"selected": true,
"text": "<p>This can be used to catch unexpected exceptions.</p>\n\n<pre><code>catch (...)\n{\n std::cout << \"OMG! an unexpected exception has been caught\" << std::endl;\n}\n</code></pre>\n\n<p>Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.</p>\n"
},
{
"answer_id": 276141,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "<p>This is what I always do in main()</p>\n\n<pre><code>int main()\n{\n try\n {\n // Do Work\n }\n catch(std::exception const& e)\n {\n Log(e.what());\n // If you are feeling mad (not in main) you could rethrow! \n }\n catch(...)\n {\n Log(\"UNKNOWN EXCEPTION\");\n // If you are feeling mad (not in main) you could rethrow! \n }\n}\n</code></pre>\n"
},
{
"answer_id": 276163,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/ms680634.aspx\" rel=\"noreferrer\">SetUnhandledExceptionFilter</a> on Windows, which will catch all unhandled SEH exceptions.</p>\n\n<p>Generally this will be sufficient for all your problems as IIRC all the C++ exceptions are implemented as SEH.</p>\n"
},
{
"answer_id": 276280,
"author": "paavo256",
"author_id": 34911,
"author_profile": "https://Stackoverflow.com/users/34911",
"pm_score": 3,
"selected": false,
"text": "<p>Without any catch block, you won't catch any exceptions. You can have a catch(...) block in your main() (and its equivalent in each additional thread). In this catch block you can recover the exception details and you can do something about them, like logging and exit. </p>\n\n<p>However, there are also downside about a general catch(...) block: the system finds that the exception has been handled by you, so it does not give any more help. On Unix/Linux, this help would constitute creating a CORE file, which you could load into the debugger and see the original location of the unexcepted exception. If you are handling it with catch(...) this information would be already lost.</p>\n\n<p>On Windows, there are no CORE files, so I would suggest to have the catch(...) block. From that block, you would typically call a function to resurrect the actual exception:</p>\n\n<pre><code>std::string ResurrectException()\n try {\n throw;\n } catch (const std::exception& e) {\n return e.what();\n } catch (your_custom_exception_type& e) {\n return e.ToString();\n } catch(...) {\n return \"Ünknown exception!\";\n }\n}\n\n\nint main() {\n try {\n // your code here\n } catch(...) {\n std::string message = ResurrectException();\n std::cerr << \"Fatal exception: \" << message << \"\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 276296,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Update</strong>: This covers c++98 only.</p>\n\n<p>From <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">More Effective C++</a> by Meyers (pg 76), you could define a function that gets called when a function generates an exception that is not defined by its exception specification.</p>\n\n<pre><code>void convertUnexpected()\n{\n // You could redefine the exception here into a known exception\n // throw UnexpectedException();\n\n // ... or I suppose you could log an error and exit.\n}\n</code></pre>\n\n<p>In your application register the function: </p>\n\n<pre><code>std::set_unexpected( convertUnexpected );\n</code></pre>\n\n<p>Your function convertUnexpected() will get called if a function generates an exception that is not defined by its exception specification... which means this only works if you are using exception specifications. ;( </p>\n"
},
{
"answer_id": 276590,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 1,
"selected": false,
"text": "<p>Use catch (...) in all of your exception barriers (not just the main thread). I suggest that you always rethrow (...) and redirect standard output/error to the log file, as you can't do meaningful RTTI on (...). OTOH, compiler like GCC will output a fairly detailed description about the unhandled exception: the type, the value of what() etc.</p>\n"
},
{
"answer_id": 9618664,
"author": "kralyk",
"author_id": 786102,
"author_profile": "https://Stackoverflow.com/users/786102",
"pm_score": 5,
"selected": false,
"text": "<p>Check out <a href=\"http://en.cppreference.com/w/cpp/error/set_terminate\" rel=\"nofollow noreferrer\"><code>std::set_terminate()</code></a></p>\n<p>Edit: Here's a full-fledged example with exception matching:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <exception>\n#include <stdexcept>\n\nstruct FooException: std::runtime_error {\n FooException(const std::string& what): std::runtime_error(what) {}\n};\n\nint main() {\n std::set_terminate([]() {\n try {\n std::rethrow_exception(std::current_exception());\n } catch (const FooException& e) {\n std::cerr << "Unhandled FooException: " << e.what() << std::endl;\n } catch (const std::exception& e) {\n std::cerr << "Unhandled exception: " << e.what() << std::endl;\n } catch (...) {\n std::cerr << "Unhandled exception of unknown type" << std::endl;\n }\n\n std::abort();\n });\n\n throw FooException("Bad things have happened.");\n // throw std::runtime_error("Bad things have happened.");\n // throw 9001;\n}\n</code></pre>\n"
},
{
"answer_id": 37947336,
"author": "scrutari",
"author_id": 547270,
"author_profile": "https://Stackoverflow.com/users/547270",
"pm_score": 3,
"selected": false,
"text": "<p>Provided that C++11 is available, this approach may be used (see example from: <a href=\"http://en.cppreference.com/w/cpp/error/rethrow_exception\" rel=\"noreferrer\">http://en.cppreference.com/w/cpp/error/rethrow_exception</a>):</p>\n\n<pre><code>#include <iostream>\n#include <exception>\n\nvoid onterminate() {\n try {\n auto unknown = std::current_exception();\n if (unknown) {\n std::rethrow_exception(unknown);\n } else {\n std::cerr << \"normal termination\" << std::endl;\n }\n } catch (const std::exception& e) { // for proper `std::` exceptions\n std::cerr << \"unexpected exception: \" << e.what() << std::endl;\n } catch (...) { // last resort for things like `throw 1;`\n std::cerr << \"unknown exception\" << std::endl;\n }\n}\n\nint main () {\n std::set_terminate(onterminate); // set custom terminate handler\n // code which may throw...\n return 0;\n}\n</code></pre>\n\n<p>This approach also allows you to customize console output for unhandled exceptions: to have something like this</p>\n\n<pre><code>unexpected exception: wrong input parameters\nAborted\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>terminate called after throwing an instance of 'std::logic_error'\n what(): wrong input parameters\nAborted\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?
I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.
something like:
```
global_catch()
{
MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
exit(-1);
}
global_catch(Exception *except)
{
MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
exit(-1);
}
```
|
This can be used to catch unexpected exceptions.
```
catch (...)
{
std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}
```
Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.
|
276,121 |
<p>I have been using netbeans as a tool for my java, and i have a problem. I read <a href="http://www.netbeans.org/kb/61/java/gui-db-custom.html" rel="nofollow noreferrer">this tutorial</a> and then i tried to create a table using this SQL:</p>
<pre><code>CREATE TABLE CUSTOMERS (
ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(30),
ADDRESS VARCHAR(30),
CITY VARCHAR(30),
STATE_ VARCHAR(30),
ZIP VARCHAR(15),
COUNTRY_ID INTEGER,
PHONE VARCHAR(15),
EMAIL_ADDRESS VARCHAR(50)
)ENGINE=INNODB;
</code></pre>
<p>When i tried to run it, I got this error message:</p>
<blockquote>
<p>sql state 42X01 : Syntax error :
encountered "AUTO_INCREMENT" at line 2
column 29</p>
</blockquote>
<p>and when i delete the AUTO_INCREMENT, another error:</p>
<blockquote>
<p>detected ENGINE=INNODB;</p>
</blockquote>
<p>can someone help me? Thanks.</p>
|
[
{
"answer_id": 276129,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 1,
"selected": false,
"text": "<p>my sugestion would be the following</p>\n\n<pre><code>CREATE TABLE CUSTOMERS \n( ID INTEGER NOT NULL auto_increment,\nFIRST_NAME VARCHAR(20), \nLAST_NAME VARCHAR(30), \nADDRESS VARCHAR(30), \nCITY VARCHAR(30), \nSTATE_ VARCHAR(30), \nZIP VARCHAR(15), \nCOUNTRY_ID INTEGER, \nPHONE VARCHAR(15), \nEMAIL_ADDRESS VARCHAR(50),\nPRIMARY KEY (ID));\n</code></pre>\n\n<p>Dunno what the engine=innodb is for, have you tried without it?</p>\n"
},
{
"answer_id": 276133,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "<p>You seem to be using MySQL syntax with another database engine. The parts it complained about are precisely the MySQL-specific ones.</p>\n"
},
{
"answer_id": 276167,
"author": "staktrace",
"author_id": 12050,
"author_profile": "https://Stackoverflow.com/users/12050",
"pm_score": 0,
"selected": false,
"text": "<p>The \"engine=innodb\" part specifies the database engine that gets used in the database. With MySQL you can specify different engines like \"InnoDB\", \"MyISAM\", etc. They have different properties and features - some allow foreign indexes, some do not. Some have different locking mechanisms, some have different atomicity/rollback properties. I don't know the details but if you need a really high-performance database setup you should investigate which engine is best for each type of table you're creating. Also, all my database experience has been with MySQL and I'm not sure if that's what you're using.</p>\n"
},
{
"answer_id": 29659770,
"author": "Siegs",
"author_id": 4793693,
"author_profile": "https://Stackoverflow.com/users/4793693",
"pm_score": -1,
"selected": false,
"text": "<p>Been a long time but if anybody else stumbles on this like I did, a solution that worked for me is instead of using <code>auto_increment</code>, describe the ID column as </p>\n\n<p><code>ID INTEGER GENERATED ALWAYS AS IDENTITY, WHATEVER VARCHAR(20), ETC ETC...</code></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have been using netbeans as a tool for my java, and i have a problem. I read [this tutorial](http://www.netbeans.org/kb/61/java/gui-db-custom.html) and then i tried to create a table using this SQL:
```
CREATE TABLE CUSTOMERS (
ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(30),
ADDRESS VARCHAR(30),
CITY VARCHAR(30),
STATE_ VARCHAR(30),
ZIP VARCHAR(15),
COUNTRY_ID INTEGER,
PHONE VARCHAR(15),
EMAIL_ADDRESS VARCHAR(50)
)ENGINE=INNODB;
```
When i tried to run it, I got this error message:
>
> sql state 42X01 : Syntax error :
> encountered "AUTO\_INCREMENT" at line 2
> column 29
>
>
>
and when i delete the AUTO\_INCREMENT, another error:
>
> detected ENGINE=INNODB;
>
>
>
can someone help me? Thanks.
|
You seem to be using MySQL syntax with another database engine. The parts it complained about are precisely the MySQL-specific ones.
|
276,126 |
<p>Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).</p>
<p>I would probably be making two separate queries, one to first find the list of questions, then another query to find all tags which belonged to the list of questions.</p>
<p><em>Approach 1:</em></p>
<p>Then I would probably be using nested repeaters and doing a select statement in the code-behind on each nested repeater "OnItemDataBind"...</p>
<p><em>Approach 2:</em></p>
<p>Or with the two datasets, I would use C# code to create a business entity of each of the "Questions" and have a property called "Tags". I would then loop through my tags dataset and assign the property.</p>
<p>What's more efficient? Are there any other alternatives?</p>
|
[
{
"answer_id": 276158,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "<p>If you do two separate queries, you can still make them in one call to the database, and get back two resultsets.</p>\n\n<p>Instead of DataSets, you could use the more efficient DataReader (with two resultsets). Loop through the resultsets and populate Question objects with associated Tag objects or properties. Put those objects in an ArrayList or a generic List, and you can bind it to your Repeater.</p>\n\n<p>Instead of doing anything in code-behind, you should consider moving that code to at least a data access layer (class) if you don't need a business logic layer (another class).</p>\n\n<p>All of these suggestions only apply if your app is non-trivial. Using OO methods does add to the code, but if you are doing anything beyond displaying the information, it would be better to start off with a good OO architecture (DAL and BLL, if not MVC).</p>\n"
},
{
"answer_id": 276240,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 3,
"selected": true,
"text": "<p>I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):</p>\n\n<p>In the aspx page:</p>\n\n<pre><code><asp:DataList ID=\"dlMenuOne\" runat=\"server\" onitemdatabound=\"dlMenu_ItemDataBound\" >\n <ItemTemplate>\n //your object\n\n <asp:DataList ID=\"dlMenuTwo\" runat=\"server\" onitemdatabound=\"dlMenuTwo_ItemDataBound\">\n <ItemTemplate>\n //your object's child items\n\n <asp:DataList ID=\"dlMenuThree\" runat=\"server\">\n <ItemTemplate>\n //child item's child items \n </ItemTemplate>\n </asp:DataList>\n\n </ItemTemplate>\n </asp:DataList> \n\n </ItemTemplate>\n </asp:DataList>\n</code></pre>\n\n<p>then in the code behind:</p>\n\n<pre><code>protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n DataListItem parentList = e.Item;\n DataList dlMenuTwo = (DataList)parentList.FindControl(\"dlMenuTwo\");\n MenuItem item = (MenuItem)parentList.DataItem;\n dlMenuTwo.DataSource = _menu.GetChildItems(item);\n dlMenuTwo.DataBind();\n}\n</code></pre>\n\n<p>this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (_menu.GetChildItems(item))</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32372/"
] |
Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).
I would probably be making two separate queries, one to first find the list of questions, then another query to find all tags which belonged to the list of questions.
*Approach 1:*
Then I would probably be using nested repeaters and doing a select statement in the code-behind on each nested repeater "OnItemDataBind"...
*Approach 2:*
Or with the two datasets, I would use C# code to create a business entity of each of the "Questions" and have a property called "Tags". I would then loop through my tags dataset and assign the property.
What's more efficient? Are there any other alternatives?
|
I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):
In the aspx page:
```
<asp:DataList ID="dlMenuOne" runat="server" onitemdatabound="dlMenu_ItemDataBound" >
<ItemTemplate>
//your object
<asp:DataList ID="dlMenuTwo" runat="server" onitemdatabound="dlMenuTwo_ItemDataBound">
<ItemTemplate>
//your object's child items
<asp:DataList ID="dlMenuThree" runat="server">
<ItemTemplate>
//child item's child items
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
```
then in the code behind:
```
protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)
{
DataListItem parentList = e.Item;
DataList dlMenuTwo = (DataList)parentList.FindControl("dlMenuTwo");
MenuItem item = (MenuItem)parentList.DataItem;
dlMenuTwo.DataSource = _menu.GetChildItems(item);
dlMenuTwo.DataBind();
}
```
this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (\_menu.GetChildItems(item))
|
276,132 |
<p>I'm setting up an Internet-facing ASP.NET MVC application, on Windows 2008. It uses SQL Server 2008 for its database. I'm looking for best-practices for securing it.</p>
<p>I found <a href="http://www.enterprisenetworkingplanet.com/netsecur/article.php/3552711" rel="nofollow noreferrer">this article</a>, but it's a bit dated now. How much of that advice is still valuable?</p>
<p>Some background -- it's a personal site, behind my home NAT/firewall box; and I'll only forward ports 80 and 443 to it. The IIS server itself is a Windows 2008 host running on HyperV (I only have one physical box to spare).</p>
<p>One useful thing that's mentioned in that article (which had occurred to me already) is that the IIS box shouldn't be a member of the domain, so that an intruder can't easily get off the box. I'll be removing it from the domain in a moment :)</p>
<p>What other tips should I (and anyone deploying to a bigger environment) bear in mind?</p>
<p>I know that this isn't strictly a programming-related question (there's no source code in it!), but I guess that most programmers have to dabble in operations stuff when it comes to deployment recommendations.</p>
|
[
{
"answer_id": 276158,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "<p>If you do two separate queries, you can still make them in one call to the database, and get back two resultsets.</p>\n\n<p>Instead of DataSets, you could use the more efficient DataReader (with two resultsets). Loop through the resultsets and populate Question objects with associated Tag objects or properties. Put those objects in an ArrayList or a generic List, and you can bind it to your Repeater.</p>\n\n<p>Instead of doing anything in code-behind, you should consider moving that code to at least a data access layer (class) if you don't need a business logic layer (another class).</p>\n\n<p>All of these suggestions only apply if your app is non-trivial. Using OO methods does add to the code, but if you are doing anything beyond displaying the information, it would be better to start off with a good OO architecture (DAL and BLL, if not MVC).</p>\n"
},
{
"answer_id": 276240,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 3,
"selected": true,
"text": "<p>I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):</p>\n\n<p>In the aspx page:</p>\n\n<pre><code><asp:DataList ID=\"dlMenuOne\" runat=\"server\" onitemdatabound=\"dlMenu_ItemDataBound\" >\n <ItemTemplate>\n //your object\n\n <asp:DataList ID=\"dlMenuTwo\" runat=\"server\" onitemdatabound=\"dlMenuTwo_ItemDataBound\">\n <ItemTemplate>\n //your object's child items\n\n <asp:DataList ID=\"dlMenuThree\" runat=\"server\">\n <ItemTemplate>\n //child item's child items \n </ItemTemplate>\n </asp:DataList>\n\n </ItemTemplate>\n </asp:DataList> \n\n </ItemTemplate>\n </asp:DataList>\n</code></pre>\n\n<p>then in the code behind:</p>\n\n<pre><code>protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n DataListItem parentList = e.Item;\n DataList dlMenuTwo = (DataList)parentList.FindControl(\"dlMenuTwo\");\n MenuItem item = (MenuItem)parentList.DataItem;\n dlMenuTwo.DataSource = _menu.GetChildItems(item);\n dlMenuTwo.DataBind();\n}\n</code></pre>\n\n<p>this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (_menu.GetChildItems(item))</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
I'm setting up an Internet-facing ASP.NET MVC application, on Windows 2008. It uses SQL Server 2008 for its database. I'm looking for best-practices for securing it.
I found [this article](http://www.enterprisenetworkingplanet.com/netsecur/article.php/3552711), but it's a bit dated now. How much of that advice is still valuable?
Some background -- it's a personal site, behind my home NAT/firewall box; and I'll only forward ports 80 and 443 to it. The IIS server itself is a Windows 2008 host running on HyperV (I only have one physical box to spare).
One useful thing that's mentioned in that article (which had occurred to me already) is that the IIS box shouldn't be a member of the domain, so that an intruder can't easily get off the box. I'll be removing it from the domain in a moment :)
What other tips should I (and anyone deploying to a bigger environment) bear in mind?
I know that this isn't strictly a programming-related question (there's no source code in it!), but I guess that most programmers have to dabble in operations stuff when it comes to deployment recommendations.
|
I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):
In the aspx page:
```
<asp:DataList ID="dlMenuOne" runat="server" onitemdatabound="dlMenu_ItemDataBound" >
<ItemTemplate>
//your object
<asp:DataList ID="dlMenuTwo" runat="server" onitemdatabound="dlMenuTwo_ItemDataBound">
<ItemTemplate>
//your object's child items
<asp:DataList ID="dlMenuThree" runat="server">
<ItemTemplate>
//child item's child items
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
```
then in the code behind:
```
protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)
{
DataListItem parentList = e.Item;
DataList dlMenuTwo = (DataList)parentList.FindControl("dlMenuTwo");
MenuItem item = (MenuItem)parentList.DataItem;
dlMenuTwo.DataSource = _menu.GetChildItems(item);
dlMenuTwo.DataBind();
}
```
this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (\_menu.GetChildItems(item))
|
276,166 |
<p>table data of 2 columns "category" and "subcategory"</p>
<p>i want to get a collection of "category", [subcategories]
using code below i get duplicates. Puting .Distinct() after outer "from" does not help much. What do i miss?</p>
<pre><code> var rootcategories = (from p in sr.products
orderby p.category
select new
{
category = p.category,
subcategories = (
from p2 in sr.products
where p2.category == p.category
select p2.subcategory).Distinct()
}).Distinct();
</code></pre>
<p>sr.products looks like this</p>
<pre><code>category subcategory
----------------------
cat1 subcat1
cat1 subcat2
cat2 subcat3
cat2 subcat3
</code></pre>
<p>what i get in results is </p>
<pre><code>cat1, [subcat1,subcat2]
cat1, [subcat1,subcat2]
</code></pre>
<p>but i only want one entry</p>
<p>solved my problem with this code:</p>
<pre><code> var rootcategories2 = (from p in sr.products
group p.subcategory by p.category into subcats
select subcats);
</code></pre>
<p>now maybe it is time to think of what was the right question.. (-:</p>
|
[
{
"answer_id": 276171,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need 2 \"Distinct()\" calls, one for the main categories and another for the subcategories.</p>\n\n<p>This should work for you:</p>\n\n<pre><code>var mainCategories = (from p in products select p.category).Distinct();\n\nvar rootCategories =\n from c in mainCategories\n select new {\n category = c,\n subcategories = (from p in products\n where p.category == c\n select p.subcategory).Distinct()\n };\n</code></pre>\n"
},
{
"answer_id": 276191,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 1,
"selected": false,
"text": "<p>Your main query is on Products, so you're going to get records for each product. Switch it around so you're querying on Category, but filtering on Product.Category</p>\n"
},
{
"answer_id": 276199,
"author": "user35959",
"author_id": 35959,
"author_profile": "https://Stackoverflow.com/users/35959",
"pm_score": 2,
"selected": false,
"text": "<p>The algorithm behind Distinct() needs a way to tell if 2 objects in the source IEnumerable are equal.\nThe default method for that is to compare 2 objects by their reference and therefore its likely that no 2 objects are \"equal\" since you are creating them with the \"new\" keyword.</p>\n\n<p>What you have to do is to write a custom class which implements IEnumerable and pass that to the Distinct() call.</p>\n"
},
{
"answer_id": 276202,
"author": "Alexander Taran",
"author_id": 35954,
"author_profile": "https://Stackoverflow.com/users/35954",
"pm_score": 4,
"selected": true,
"text": "<p>solved with this code</p>\n\n<pre><code> var rootcategories2 = (from p in sr.products\n group p.subcategory by p.category into subcats\n\n select subcats);\n</code></pre>\n\n<p>thanks everyone</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35954/"
] |
table data of 2 columns "category" and "subcategory"
i want to get a collection of "category", [subcategories]
using code below i get duplicates. Puting .Distinct() after outer "from" does not help much. What do i miss?
```
var rootcategories = (from p in sr.products
orderby p.category
select new
{
category = p.category,
subcategories = (
from p2 in sr.products
where p2.category == p.category
select p2.subcategory).Distinct()
}).Distinct();
```
sr.products looks like this
```
category subcategory
----------------------
cat1 subcat1
cat1 subcat2
cat2 subcat3
cat2 subcat3
```
what i get in results is
```
cat1, [subcat1,subcat2]
cat1, [subcat1,subcat2]
```
but i only want one entry
solved my problem with this code:
```
var rootcategories2 = (from p in sr.products
group p.subcategory by p.category into subcats
select subcats);
```
now maybe it is time to think of what was the right question.. (-:
|
solved with this code
```
var rootcategories2 = (from p in sr.products
group p.subcategory by p.category into subcats
select subcats);
```
thanks everyone
|
276,173 |
<p>What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with <code>delete[]</code>. </p>
<p>Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.</p>
<pre><code>TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder )
: TextFileProcessor_Base( theConstStringFinder )
, m_ThreadHandle ( NULL )
, m_startNLSearch ( 0 )
, m_endNLSearch ( 0 )
, m_LineEndGetIdx ( 0 )
, m_LineEndPutIdx ( 0 )
, m_LineEnds ( new const void*[ sc_LineEndSize ] )
{
;
}
</code></pre>
|
[
{
"answer_id": 276201,
"author": "Ather",
"author_id": 1065163,
"author_profile": "https://Stackoverflow.com/users/1065163",
"pm_score": 1,
"selected": false,
"text": "<p>Write each method or function argument on a separate line such that it can be easily commented.</p>\n\n<pre><code>int ReturnMaxValue(\n int* inputList, /* the list of integer values from which to get the maximum */\n long size, /* count of the number of integer values in inputList */\n char* extraArgs /* additional arguments that a caller can provide. */\n)\n</code></pre>\n"
},
{
"answer_id": 276276,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>Document the return values on the function line, so they are very easy to find.</p>\n\n<pre><code>int function(void) /* return 1 on success, 0 on failure */ \n{\n return 1;\n};\n</code></pre>\n"
},
{
"answer_id": 276302,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this counts as an idiom, but I tend to use <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">doxygen</a>-style inline comments even when the project isn't -yet- using doxygen...</p>\n\n<pre><code>bool MyObjects::isUpToSomething() ///< Is my object up to something \n</code></pre>\n\n<p>(aside. my comments are not usually quite that lame.)</p>\n"
},
{
"answer_id": 276481,
"author": "zerbp",
"author_id": 35744,
"author_profile": "https://Stackoverflow.com/users/35744",
"pm_score": 4,
"selected": false,
"text": "<p>In <code>if</code> statements, when there are difficult conditions, you can clearly show which level each condition is using indentation.</p>\n\n<pre><code>if ( ( (var1A == var2A)\n || (var1B == var2B))\n && ( (var1C == var2C)\n || (var1D == var2D)))\n{\n // do something\n}\n</code></pre>\n"
},
{
"answer_id": 276550,
"author": "Prembo",
"author_id": 24376,
"author_profile": "https://Stackoverflow.com/users/24376",
"pm_score": 5,
"selected": false,
"text": "<p>I like lining up code/initializations in 'columns'... Proves very useful when editing with a 'column' mode capable editor and also seems to be a lot easier for me to read... </p>\n\n<pre><code>int myVar = 1; // comment 1\nint myLongerVar = 200; // comment 2\n\nMyStruct arrayOfMyStruct[] = \n{ \n // Name, timeout, valid\n {\"A string\", 1000, true }, // Comment 1\n {\"Another string\", 2000, false }, // Comment 2 \n {\"Yet another string\", 11111000, false }, // Comment 3\n {NULL, 5, true }, // Comment 4\n};\n</code></pre>\n\n<p>In contrast, the same code not indented and formatted as above would appear... (A little harder to read to my eyes)</p>\n\n<pre><code>int myVar = 1; // comment 1\nint myLongerVar = 200; // comment 2\n\nMyStruct arrayOfMyStruct[] = \n{ \n // Name, timeout, valid\n {\"A string\", 1000, true},// Comment 1\n {\"Another string\", 2000, false }, // Comment 2 \n {\"Yet another string\", 11111000,false}, // Comment 3\n {NULL, 5, true }, // Comment 4\n};\n</code></pre>\n"
},
{
"answer_id": 276560,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 3,
"selected": false,
"text": "<p>No favorites but I <em>will</em> fix code that has:</p>\n\n<ol>\n<li>tabs - causes misalignment in many IDEs and code review tools, because they don't always agree on tab at mod 8 spaces.</li>\n<li>lines longer than 80 columns - let's face it, shorter lines are more readable. My brain can parse most coding conventions, as long as the lines are short.</li>\n<li>lines with trailing whitespaces - git will complain about it as whitespace <em>errors</em>, which show up as red blobs in diffs, which is annoying.</li>\n</ol>\n\n<p>Here is a one-liner to find the offending files:</p>\n\n<pre><code>git grep -I -E '<tab>|.{81,}| *$' | cut -f1 -d: | sort -u\n</code></pre>\n\n<p>where <code><tab></code> is the tab character (POSIX regexp doesn't do \\t)</p>\n"
},
{
"answer_id": 276570,
"author": "kshahar",
"author_id": 33982,
"author_profile": "https://Stackoverflow.com/users/33982",
"pm_score": 7,
"selected": true,
"text": "<p>When creating enumerations, put them in a namespace so that you can access them with a meaningful name:</p>\n\n<pre><code>namespace EntityType {\n enum Enum {\n Ground = 0,\n Human,\n Aerial,\n Total\n };\n}\n\nvoid foo(EntityType::Enum entityType)\n{\n if (entityType == EntityType::Ground) {\n /*code*/\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong>: However, this technique has become obsolete in C++11. <em>Scoped enumeration</em> (declared with <code>enum class</code> or <code>enum struct</code>) should be used instead: it is more type-safe, concise, and flexible. With old-style enumerations the values are placed in the outer scope. With new-style enumeration they are placed within the scope of the <code>enum class</code> name.<br>\nPrevious example rewritten using scoped enumeration (also known as <em>strongly typed enumeration</em>):</p>\n\n<pre><code>enum class EntityType {\n Ground = 0,\n Human,\n Aerial,\n Total\n};\n\nvoid foo(EntityType entityType)\n{\n if (entityType == EntityType::Ground) {\n /*code*/\n }\n}\n</code></pre>\n\n<p>There are other significant benefits from using scoped enumerations: absence of implicit cast, possible forward declaration, and ability to use custom underlying type (not the default <code>int</code>).</p>\n"
},
{
"answer_id": 276577,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>re: ididak</p>\n\n<p>I fix code that breaks long statements into too many short lines.</p>\n\n<p>Let's face it: it's not the 90's any more.\nIf your company can't afford widescreen LCDs for its coders, you need to get a better job :)</p>\n"
},
{
"answer_id": 278764,
"author": "mempko",
"author_id": 8863,
"author_profile": "https://Stackoverflow.com/users/8863",
"pm_score": 2,
"selected": false,
"text": "<p>I really like putting a small statement on the same line as an if</p>\n\n<pre><code>int myFunc(int x) {\n if(x >20) return -1;\n //do other stuff ....\n}\n</code></pre>\n"
},
{
"answer_id": 280590,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 0,
"selected": false,
"text": "<p>I always nitpick and edit the following:</p>\n\n<ul>\n<li>Superfluous newlines</li>\n<li>No newline at EOF</li>\n</ul>\n"
},
{
"answer_id": 280625,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>It's useful to put function names on a new line, so you can grep like </p>\n\n<pre><code>grep -R '^fun_name' .\n</code></pre>\n\n<p>for them. I've seen that style used for a loads of GNU projects and like it:</p>\n\n<pre><code>static void\nfun_name (int a, int b) {\n /* ... */\n}\n</code></pre>\n"
},
{
"answer_id": 280637,
"author": "Terminus",
"author_id": 7053,
"author_profile": "https://Stackoverflow.com/users/7053",
"pm_score": 0,
"selected": false,
"text": "<p>I usually stick to KNF described in *BSD <a href=\"http://www.openbsd.org/cgi-bin/man.cgi?query=style&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html\" rel=\"nofollow noreferrer\">STYLE(9)</a></p>\n"
},
{
"answer_id": 282402,
"author": "Jamie Hale",
"author_id": 34533,
"author_profile": "https://Stackoverflow.com/users/34533",
"pm_score": 3,
"selected": false,
"text": "<p>After working with someone who was partly blind - and at his request - I switched to using many more spaces. I didn't like it at the time, but now I prefer it. Off the top of my head, the only place where there isn't whitespace between identifiers and keywords and whatnot is <em>after</em> a function name and before the following parentheses.</p>\n\n<pre><code>void foo( int a, int b )\n{\n int c = a + ( a * ( a * b ) );\n if ( c > 12 )\n c += 9;\n return foo( 2, c );\n}\n</code></pre>\n"
},
{
"answer_id": 282745,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": -1,
"selected": false,
"text": "<p>I tend to put an else on all of my ifs.</p>\n\n<pre><code>if (condition)\n{\n complicated code goes here\n}\nelse\n{\n /* This is a comment as to why the else path isn't significant */ \n}\n</code></pre>\n\n<p>Even though it annoys my coworkers.\nYou can tell at a glance, that I considered the else case during coding.</p>\n"
},
{
"answer_id": 2034320,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 6,
"selected": false,
"text": "<h2>RAII: Resource Acquisition Is Initialization</h2>\n\n<p>RAII may be the most important idiom. It is the idea that resources should be mapped to objects, so that their lifetimes are managed automatically according to the scope in which those objects are declared.</p>\n\n<p>For example, if a file handle was declared on the stack, it should be implicitly closed once we return from the function (or loop, or whichever scope it was declared inside). If a dynamic memory allocation was allocated as a member of a class, it should be implicitly freed when that class instance is destroyed. And so on. Every kind of resource—memory allocations, file handles, database connections, sockets, and any other kind of resource that has to be acquired and released—should be wrapped inside such a RAII class, whose lifetime is determined by the scope in which it was declared.</p>\n\n<p>One major advantage of this is that C++ guarantees that destructors are called when an object goes out of scope, <em>regardless of how control is leaving that scope</em>. Even if an exception is thrown, all local objects will go out of scope, and so their associated resources will get cleaned up.</p>\n\n<pre><code>void foo() {\n std::fstream file(\"bar.txt\"); // open a file \"bar.txt\"\n if (rand() % 2) {\n // if this exception is thrown, we leave the function, and so\n // file's destructor is called, which closes the file handle.\n throw std::exception();\n }\n // if the exception is not called, we leave the function normally, and so\n // again, file's destructor is called, which closes the file handle.\n}\n</code></pre>\n\n<p>Regardless of how we leave the function, and of what happens after the file is opened, we don't need to explicitly close the file, or handle exceptions (e.g. try-finally) within that function. Instead, the file gets cleaned up because it is tied to a local object that gets destroyed when it goes out of scope.</p>\n\n<p>RAII is also less-commonly known as SBRM (Scope-Bound Resource Management).</p>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://www.ddj.com/cpp/184403758\" rel=\"noreferrer\">ScopeGuard</a> allows code to \"automatically invoke an 'undo' operation .. in the event that an exception is thrown.\"</li>\n</ul>\n"
},
{
"answer_id": 2034352,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 5,
"selected": false,
"text": "<h2>pImpl: Pointer-to-Implementation</h2>\n\n<p>The pImpl idiom is a very useful way to decouple the interface of a class from its implementation.</p>\n\n<p>Normally, a class definition must contain member variables as well as methods, which may expose too much information. For example, a member variable may be of a type defined in a header that we don't wish to include everywhere. </p>\n\n<p>The <code>windows.h</code> header is a prime example here. We may wish to wrap a <code>HANDLE</code> or another Win32 type inside a class, but we can't put a <code>HANDLE</code> in the class definition without having to include <code>windows.h</code> everywhere the class is used.</p>\n\n<p>The solution then is to create a <i>P</i>rivate <i>IMPL</i>ementation or <i>P</i>ointer-to-<i>IMPL</i>ementation of the class, and let the public implementation store only a pointer to the private one, and forward all member methods.</p>\n\n<p>For example:</p>\n\n<pre><code>class private_foo; // a forward declaration a pointer may be used\n\n// foo.h\nclass foo {\npublic:\n foo();\n ~foo();\n void bar();\nprivate:\n private_foo* pImpl;\n};\n\n// foo.cpp\n#include whichever header defines the types T and U\n\n// define the private implementation class\nclass private_foo {\npublic:\n void bar() { /*...*/ }\n\nprivate:\n T member1;\n U member2;\n};\n\n// fill in the public interface function definitions:\nfoo::foo() : pImpl(new private_foo()) {}\nfoo::~foo() { delete pImpl; }\nvoid foo::bar() { pImpl->bar(); }\n</code></pre>\n\n<p>The implementation of <code>foo</code> is now decoupled from its public interface, so that</p>\n\n<ul>\n<li>it can use members and types from other headers without requiring these dependencies to be present when the class is used, and</li>\n<li>the implementation can be modified without forcing a recompile of the code that uses the class.</li>\n</ul>\n\n<p>Users of the class simply include the header, which contains nothing specific about the implementation of the class. All implementation details are contained inside <code>foo.cpp</code>.</p>\n"
},
{
"answer_id": 2034357,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest PIMPL or as James Coplien originally called it \"Handle Body\".</p>\n\n<p>This idiom allows you to completely decouple interface from implementation. When working on the rewrite and re-release of a major CORBA middleware component, this idiom was used to completely decouple the API from the implementation.</p>\n\n<p>This practically eliminated any possibility reverse engineering.</p>\n\n<p>An excellent resource for C++ idioms is James Coplien's excellent book \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0201548550\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Advanced C++ Programming Styles and Idioms</a>\". Highly recommended!</p>\n\n<p><strong>Edit:</strong> As pointed out below by Neil, this book is quite out of date with many of his recommendations actually being incorporated into the C++ standard itself. However, I still find it to be a source of useful info, esp. in the form of his <a href=\"http://users.rcn.com/jcoplien/Patterns/C++Idioms/EuroPLoP98.html\" rel=\"nofollow noreferrer\">PLoP paper on C++ idioms</a> where many idioms were recast into patterm form.</p>\n"
},
{
"answer_id": 2034439,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<h2>CRTP: Curiously Recurring Template Pattern</h2>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"noreferrer\">CRTP</a> happens when you pass a class as a template parameter to its base class:</p>\n\n<pre><code>template<class Derived>\nstruct BaseCRTP {};\n\nstruct Example : BaseCRTP<Example> {};\n</code></pre>\n\n<p>Within the base class, it can get ahold of the derived instance, <em>complete with the derived type</em>, simply by casting (either <em>static_cast</em> or <em>dynamic_cast</em> work):</p>\n\n<pre><code>template<class Derived>\nstruct BaseCRTP {\n void call_foo() {\n Derived& self = *static_cast<Derived*>(this);\n self.foo();\n }\n};\n\nstruct Example : BaseCRTP<Example> {\n void foo() { cout << \"foo()\\n\"; }\n};\n</code></pre>\n\n<p>In effect, <em>call_foo</em> has been <em>injected</em> into the derived class with full access to the derived class's members.</p>\n\n<p>Feel free to edit and add specific examples of use, possibly to <a href=\"https://stackoverflow.com/questions/2032881/creating-a-new-object-from-dynamic-type-info/2033034#2033034\">other SO posts</a>.</p>\n"
},
{
"answer_id": 2034447,
"author": "RC.",
"author_id": 22118,
"author_profile": "https://Stackoverflow.com/users/22118",
"pm_score": 5,
"selected": false,
"text": "<h2>Copy-swap</h2>\n\n<p>The copy-swap idiom provides exception-safe copying. It requires that a correct copy ctor and swap are implemented.</p>\n\n<pre><code>struct String {\n String(String const& other);\n\n String& operator=(String copy) { // passed by value\n copy.swap(*this); // nothrow swap\n return *this; // old resources now in copy, released in its dtor\n }\n\n void swap(String& other) throw() {\n using std::swap; // enable ADL, defaulting to std::swap\n swap(data_members, other.data_members);\n }\n\nprivate:\n Various data_members;\n};\nvoid swap(String& a, String& b) { // provide non-member for ADL\n a.swap(b);\n}\n</code></pre>\n\n<p>You can also implement the swap method with ADL (Argument Dependent Lookup) <a href=\"https://stackoverflow.com/questions/1996548/segmentation-fault-in-overloading-operator/1996586#1996586\">directly</a>.</p>\n\n<p>This idiom is important because it handles self-assignment<sup>[1]</sup>, makes the strong exception guarantee<sup>[2]</sup>, and is often very easy to write.</p>\n\n<hr>\n\n<p><sup>[1]</sup> Even though self-assignment isn't handled as efficiently as possible, it's supposed to be <em>rare</em>, so if it never happens, this is actually faster.</p>\n\n<p><sup>[2]</sup> If any exception is thrown, the state of the object (<code>*this</code>) is not modified.</p>\n"
},
{
"answer_id": 2034549,
"author": "Jerry Coffin",
"author_id": 179910,
"author_profile": "https://Stackoverflow.com/users/179910",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if it qualifies as an idiom, exactly, but quite a bit of heavy-duty template programming depends (often heavily) on SFINAE (substitution failure is not an error). A couple of the answers to <a href=\"https://stackoverflow.com/questions/982808/c-sfinae-examples\">a previous question</a> have examples.</p>\n"
},
{
"answer_id": 2034614,
"author": "seh",
"author_id": 31818,
"author_profile": "https://Stackoverflow.com/users/31818",
"pm_score": 3,
"selected": false,
"text": "<h2>Compile-time polymorphism</h2>\n\n<p>(Also known as syntactic polymorphism and static polymorphism, contrast with runtime polymorphism.)</p>\n\n<p>With template functions, one can write code that relies on type constructors and call signatures of families of parametrized types, without having to introduce a common base class.</p>\n\n<p>In the book <a href=\"http://www.elementsofprogramming.com/book.html\" rel=\"noreferrer\"><em>Elements of Programming</em></a>, the authors refer to this treatment of types as <em>abstract genera</em>. With <em>concepts</em> one can specify the requirements on such type parameters, though C++ doesn't mandate such specifications.</p>\n\n<p>Two simple examples:</p>\n\n<pre><code>#include <stdexcept>\n\ntemplate <typename T>\nT twice(T n) {\n return 2 * n;\n}\n\nInIt find(InIt f, InIt l,\n typename std::iterator_traits<InIt>::reference v)\n{\n while (f != l && *f != v)\n ++f;\n return f;\n} \n\nint main(int argc, char* argv[]) {\n if (6 != twice(3))\n throw std::logic_error(\"3 x 2 = 6\");\n\n int const nums[] = { 1, 2, 3 };\n if (nums + 4 != find(nums, nums + 4, 42))\n throw std::logic_error(\"42 should not have been found.\");\n\n return 0;\n}\n</code></pre>\n\n<p>One can call <code>twice</code> with any regular type that has a binary <code>*</code> operator defined. Similarly, one can call <code>find()</code> with any types that are comparable and that model <em>Input Iterator</em>. One set of code operates similarly on different types, with no shared base classes in sight.</p>\n\n<p>Of course, what's really going on here is that it's the same source code being <em>expanded</em> into various type-specific functions at template instantiation time, each with separate generated machine code. Accommodating the same set of types without templates would have required either 1) separate hand-written functions with specific signatures, or 2) runtime polymorphism through virtual functions.</p>\n"
},
{
"answer_id": 2034627,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 3,
"selected": false,
"text": "<h2>Template and Hook</h2>\n\n<p>This is a way to handle as much as possible in a framework and give a <em>door</em> or <em>hook</em> for customization by users of a framework. Also known as Hotspot and <a href=\"http://pages.cpsc.ucalgary.ca/~kremer/patterns/templateMethod.html\" rel=\"noreferrer\">Template Method</a>.</p>\n\n<pre><code>class Class {\n void PrintInvoice(); // Called Template (boilerplate) which uses CalcRate()\n virtual void CalcRate() = 0; // Called Hook\n}\n\nclass SubClass : public Class {\n virtual void CalcRate(); // Customized method\n}\n</code></pre>\n\n<p>Described by <a href=\"http://en.wikipedia.org/wiki/Wolfgang_Pree\" rel=\"noreferrer\">Wolfgang Pree</a> in his book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201422948\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Design Patterns for Object-Oriented Software Development</a>.</p>\n"
},
{
"answer_id": 3852294,
"author": "franji1",
"author_id": 346104,
"author_profile": "https://Stackoverflow.com/users/346104",
"pm_score": 3,
"selected": false,
"text": "<h2>if/while/for parenthesized expression(s) WITH a space separator</h2>\n\n<pre><code>if (expression) // preferred - if keyword sticks out more\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>if(expression) // looks too much like a void function call\n</code></pre>\n\n<p>I guess this implies that I like my function calls to NOT have a space separator</p>\n\n<pre><code>foo(parm1, parm2);\n</code></pre>\n"
},
{
"answer_id": 6424851,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 4,
"selected": false,
"text": "<p>Public Top - Private Down</p>\n\n<p>A seemingly small optimization, but ever since I switched to this convention, I have a way more fun time to grasp my classes, especially after I haven't looked at them for 42 years.</p>\n\n<p>Having a consistent member visibility, going from points of frequent interest down to the boring stuff, is extremely helpful, especially when the code ought to be self-documenting.</p>\n\n<p>(sidenote for qt-users: slots come before signals because they should be callable like non-slot member functions, and apart from their slottyness be indistinguishable from non-slots)</p>\n\n<ul>\n<li>Public, protected, private</li>\n<li>then Factory, ctor, dtor, copying, swapping</li>\n<li>then the class' Interface\nAt the very last, in a seperate <code>private:</code> section, comes the data (ideally only an impl-pointer).</li>\n</ul>\n\n<p>This rule also helps a ton if you have problems keeping your class declaration uncluttered.</p>\n\n<pre><code>class Widget : public Purple {\npublic:\n // Factory methods.\n Widget FromRadians (float);\n Widget FromDegrees (float);\n\n // Ctors, rule of three, swap\n Widget();\n Widget (Widget const&);\n Widget &operator = (Widget const &);\n void swap (Widget &) throw();\n\n // Member methods.\n float area() const;\n\n // in case of qt {{ \npublic slots:\n void invalidateBlackHole();\n\nsignals:\n void areaChanged (float);\n // }}\n\nprotected: \n // same as public, but for protected members\n\n\nprivate: \n // same as public, but for private members\n\nprivate:\n // data\n float widgetness_;\n bool isMale_;\n};\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18256/"
] |
What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with `delete[]`.
Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.
```
TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder )
: TextFileProcessor_Base( theConstStringFinder )
, m_ThreadHandle ( NULL )
, m_startNLSearch ( 0 )
, m_endNLSearch ( 0 )
, m_LineEndGetIdx ( 0 )
, m_LineEndPutIdx ( 0 )
, m_LineEnds ( new const void*[ sc_LineEndSize ] )
{
;
}
```
|
When creating enumerations, put them in a namespace so that you can access them with a meaningful name:
```
namespace EntityType {
enum Enum {
Ground = 0,
Human,
Aerial,
Total
};
}
void foo(EntityType::Enum entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
```
**EDIT**: However, this technique has become obsolete in C++11. *Scoped enumeration* (declared with `enum class` or `enum struct`) should be used instead: it is more type-safe, concise, and flexible. With old-style enumerations the values are placed in the outer scope. With new-style enumeration they are placed within the scope of the `enum class` name.
Previous example rewritten using scoped enumeration (also known as *strongly typed enumeration*):
```
enum class EntityType {
Ground = 0,
Human,
Aerial,
Total
};
void foo(EntityType entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
```
There are other significant benefits from using scoped enumerations: absence of implicit cast, possible forward declaration, and ability to use custom underlying type (not the default `int`).
|
276,177 |
<p>In my ASP.NET 1.1 application, I am compressing and replacing the hidden Viewstate variable with an alternate compressed value, stored in a hidden field called __VSTATE. This works well but on a few occasions, submitting a page causes the common "potentially dangerous Request.Form value ..." error.</p>
<p>I examined the __VSTATE value and nothing seems to be potentially dangerous. I was able to reproduce the error with a completely stripped down version of the page and __VSTATE value as shown below. Pressing the submit button causes the error. The page works fine if I change the value to "".</p>
<pre><code><%@ Page Language="vb" AutoEventWireup="false" Codebehind="Dangerous.aspx.vb" Inherits="Dynalabs.Dangerous" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body MS_POSITIONING="FlowLayout">
<form id="Form1" method="post" runat="server">
<input type="hidden" id="__VSTATE" runat="server" value="Onw=" />
<asp:Button ID="btnSubmit" Runat="server" Text="Submit" />
</form>
</body>
</html>
</code></pre>
<p>Changing the field name to "MyHiddenWT" made no difference. Removing the runat="server" did stop the error but that just means that .NET only examines server side controls. I also tried some additional values and found that of the following:</p>
<pre><code>"Anw=", "Bnw=", "Cnw=", ... "Nnw=", "Onw=", "Pnw=", ... "Znw=",
</code></pre>
<p>"Onw=" is the only one that causes the problem. Is the captial O being seen as an octal value somehow?</p>
<p>Can someone explain why this value is triggering the error message? I'm also looking for a solution but, please, do not tell me to remove page validation. That's the same as saying a car with bad brakes can be fixed by not driving the car.</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 276270,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "<p>My first guess is that it looks like a \"OnSomething=\" javascript event declaration.</p>\n\n<p>It's a little weird that only the capital O triggers the error, did you test on the lowercase o as well?</p>\n\n<p>Can you try these: \"OnClick=\", \"abc OnClick=\", \"onclick=\", \"abc onclick=\", \"anw=\", \"bnw=\", ...</p>\n\n<hr>\n\n<p>If \"OnSomething=x\" javascript is a problem, then simply adding another character to your values should do the trick. Maybe a simple 'v' should do.</p>\n\n<pre><code><input type=\"hidden\" id=\"__VSTATE\" runat=\"server\" value=\"vOnw=\" />\n</code></pre>\n\n<p>And then on submit, you remove the extra character before decoding.</p>\n\n<p>Or better yet, upgrade to 2.0.</p>\n"
},
{
"answer_id": 276480,
"author": "ZLA",
"author_id": 35955,
"author_profile": "https://Stackoverflow.com/users/35955",
"pm_score": 0,
"selected": false,
"text": "<p>You've got the essence of the reason. Here's the best link in a response I got from another site:</p>\n\n<p><a href=\"http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet.security/browse_thread/thread/d91d89511401e979\" rel=\"nofollow noreferrer\">http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet.security/browse_thread/thread/d91d89511401e979</a></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35955/"
] |
In my ASP.NET 1.1 application, I am compressing and replacing the hidden Viewstate variable with an alternate compressed value, stored in a hidden field called \_\_VSTATE. This works well but on a few occasions, submitting a page causes the common "potentially dangerous Request.Form value ..." error.
I examined the \_\_VSTATE value and nothing seems to be potentially dangerous. I was able to reproduce the error with a completely stripped down version of the page and \_\_VSTATE value as shown below. Pressing the submit button causes the error. The page works fine if I change the value to "".
```
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Dangerous.aspx.vb" Inherits="Dynalabs.Dangerous" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body MS_POSITIONING="FlowLayout">
<form id="Form1" method="post" runat="server">
<input type="hidden" id="__VSTATE" runat="server" value="Onw=" />
<asp:Button ID="btnSubmit" Runat="server" Text="Submit" />
</form>
</body>
</html>
```
Changing the field name to "MyHiddenWT" made no difference. Removing the runat="server" did stop the error but that just means that .NET only examines server side controls. I also tried some additional values and found that of the following:
```
"Anw=", "Bnw=", "Cnw=", ... "Nnw=", "Onw=", "Pnw=", ... "Znw=",
```
"Onw=" is the only one that causes the problem. Is the captial O being seen as an octal value somehow?
Can someone explain why this value is triggering the error message? I'm also looking for a solution but, please, do not tell me to remove page validation. That's the same as saying a car with bad brakes can be fixed by not driving the car.
Thank you in advance.
|
My first guess is that it looks like a "OnSomething=" javascript event declaration.
It's a little weird that only the capital O triggers the error, did you test on the lowercase o as well?
Can you try these: "OnClick=", "abc OnClick=", "onclick=", "abc onclick=", "anw=", "bnw=", ...
---
If "OnSomething=x" javascript is a problem, then simply adding another character to your values should do the trick. Maybe a simple 'v' should do.
```
<input type="hidden" id="__VSTATE" runat="server" value="vOnw=" />
```
And then on submit, you remove the extra character before decoding.
Or better yet, upgrade to 2.0.
|
276,188 |
<p>C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ?</p>
|
[
{
"answer_id": 276197,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Type-safe <code>printf</code></li>\n</ul>\n"
},
{
"answer_id": 276223,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>Allowing things like Boost.Function to take arbitrary numbers of parameters</p>\n"
},
{
"answer_id": 277487,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "<ol>\n<li><strong>Type-safe printf</strong></li>\n<li>Forwarding of arbitrary many constructor arguments in <strong>factory methods</strong></li>\n<li>Having <strong>arbitrary</strong> base-classes allows for putting and removing useful <strong>policies</strong>.</li>\n<li>Initializing by moving <strong>heterogenous typed objects</strong> directly into a container by having a variadic template'd constructor.</li>\n<li>Having a <strong>literal operator</strong> that can calculate a value for a user defined literal (like \"10110b\").</li>\n</ol>\n\n<p>Sample to 3:</p>\n\n<pre><code>template<typename... T> struct flexible : T... { flexible(): T()... { } };\n</code></pre>\n\n<p>Sample to 4:</p>\n\n<pre><code>struct my_container { template<typename... T> my_container(T&&... t) { } };\nmy_container c = { a, b, c };\n</code></pre>\n\n<p>Sample to 5: </p>\n\n<pre><code>template<char... digits>\nint operator \"\" b() { return convert<digits...>::value; }\n</code></pre>\n\n<p>See this example code: <a href=\"https://stackoverflow.com/questions/537303/binary-literals/538101#538101\">here</a></p>\n"
},
{
"answer_id": 7298163,
"author": "Kerido",
"author_id": 261388,
"author_profile": "https://Stackoverflow.com/users/261388",
"pm_score": 2,
"selected": false,
"text": "<p>I just wrote an <a href=\"http://www.codeproject.com/KB/cpp/com_variadic_templates.aspx\" rel=\"nofollow\">article</a> on how to implement multiple COM interfaces and keep your code compact and elegant with C++0x variadic templates.</p>\n"
},
{
"answer_id": 10752014,
"author": "S. Weiser",
"author_id": 1417067,
"author_profile": "https://Stackoverflow.com/users/1417067",
"pm_score": 0,
"selected": false,
"text": "<p>Type safety of every call with dynamic argument number.</p>\n"
},
{
"answer_id": 12038087,
"author": "cppist",
"author_id": 1486168,
"author_profile": "https://Stackoverflow.com/users/1486168",
"pm_score": 1,
"selected": false,
"text": "<p>I have implemented an NDArray (N-dimentional array) and it has the method setSizes with variadic count of arguments. Using variadic template arguments is type safer than using variadic function arguments, moreover I can control count of parameters passed to this function in compile time only with variadic template arguments.</p>\n\n<pre><code>void setSizes(uintmax_t currentSize) {\n static_assert(1 == NDimensions, \"Invalid count of arguments given to setSizes.\");\n\n size_ = currentSize;\n data_ = new NDArrayReferenceType[currentSize];\n}\n\ntemplate <typename... Sizes>\nvoid setSizes(uintmax_t currentSize, Sizes... sizes) {\n static_assert(sizeof...(Sizes) + 1 == NDimensions, \"Invalid count of arguments given to setSizes.\");\n\n size_ = currentSize;\n data_ = new NDArrayReferenceType[currentSize];\n\n for (uintmax_t i = 0; i < currentSize; i++) {\n data_[i]->setSizes(sizes...);\n }\n}\n</code></pre>\n\n<p>I have also implemented a universal constructor wrapper for my self-made SmartPointer. It wraps over all user-defined constructor of type of raw pointer.</p>\n\n<pre><code>template <typename TSmartPointer, typename... Args>\nstatic inline void initialize(TSmartPointer *smartPointer, Args... args) {\n smartPointer->pointer_ = new typename TSmartPointer::PointerType(std::forward<Args>(args)...);\n smartPointer->__retain();\n}\n</code></pre>\n\n<p>This code seems to be inobvious, this is a part of initializer of the SmartPointer for the case whether SmartPointer should automatically call the constructor of pointer at the acquisition of the SmartPointer (RAII). In case of abstract classes it is unable to call the constructor.</p>\n\n<p>So, if I have a type AbstractObject, which is SmartPointer of an abstract class, and the type ConcreteObject, which is SmartPointer of class with constructor that takes two ints, I can write following code:</p>\n\n<pre><code>AbstractObject object = ConcreteObject(42, 42);\n</code></pre>\n\n<p>It is like C# and Java (but with RAII) and it works for me in C++/GCC 4.8 =)</p>\n"
},
{
"answer_id": 12039740,
"author": "PaperBirdMaster",
"author_id": 499359,
"author_profile": "https://Stackoverflow.com/users/499359",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe the talk by Andrei Alexandrescu on the Going Native 2012 event, will be of your interest:</p>\n\n<p><a href=\"http://video.ch9.ms/ch9/5174/7feb4b38-591d-478f-8341-9fd4012d5174/GN12AndreiAlexandrescuVariadicTemplates_high_ch9.mp4\" rel=\"nofollow\">Here</a> is the video and <a href=\"http://ecn.channel9.msdn.com/events/GoingNative12/GN12VariadicTemplatesAreFunadic.pdf\" rel=\"nofollow\">Here</a> the documentation.</p>\n"
},
{
"answer_id": 35366278,
"author": "vitaut",
"author_id": 471164,
"author_profile": "https://Stackoverflow.com/users/471164",
"pm_score": 0,
"selected": false,
"text": "<p>Type-safe printf has been mentioned in other answers, but more generally variadic templates can be used to implement formatting functions that don't require passing type information via format specifiers at all. For example, the <a href=\"https://github.com/cppformat/cppformat\" rel=\"nofollow\">C++ Format library</a> implements formatting functions similar to Python's <a href=\"https://docs.python.org/2/library/stdtypes.html#str.format\" rel=\"nofollow\">str.format</a>:</p>\n\n<pre><code>fmt::print(\"I'd rather be {1} than {0}.\", \"right\", \"happy\");\n</code></pre>\n\n<p>in addition to safe printf. The types of arguments are captured automatically using variadic templates in C++11.</p>\n\n<p>This makes printf specifiers like <code>lld</code> or notorious <code>PRIdPTR</code> unnecessary and instead of</p>\n\n<pre><code>std::printf(\"Local number: %\" PRIdPTR \"\\n\\n\", someIntPtr);\n</code></pre>\n\n<p>one can simply use</p>\n\n<pre><code>fmt::printf(\"Local number: %d\\n\\n\", someIntPtr);\n</code></pre>\n\n<p><strong>Disclaimer</strong>: I'm the author of this library</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19630/"
] |
C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ?
|
1. **Type-safe printf**
2. Forwarding of arbitrary many constructor arguments in **factory methods**
3. Having **arbitrary** base-classes allows for putting and removing useful **policies**.
4. Initializing by moving **heterogenous typed objects** directly into a container by having a variadic template'd constructor.
5. Having a **literal operator** that can calculate a value for a user defined literal (like "10110b").
Sample to 3:
```
template<typename... T> struct flexible : T... { flexible(): T()... { } };
```
Sample to 4:
```
struct my_container { template<typename... T> my_container(T&&... t) { } };
my_container c = { a, b, c };
```
Sample to 5:
```
template<char... digits>
int operator "" b() { return convert<digits...>::value; }
```
See this example code: [here](https://stackoverflow.com/questions/537303/binary-literals/538101#538101)
|
276,198 |
<p>What would be the best way to manage large number of instances of the same class in MATLAB?</p>
<p>Using the naive way produces absymal results:</p>
<pre><code>classdef Request
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> a=[];
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 5.426852 seconds.
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 31.261500 seconds.
</code></pre>
<p>Inheriting handle drastically improve the results:</p>
<pre><code>classdef RequestH < handle
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.174573 seconds.
</code></pre>
<p>but still not an acceptable performance, especially considering the increasing reallocation overhead </p>
<p>Is there a way to preallocate class array? Any ideas on how to manage lange quantities of object effectively?</p>
<p>Thanks,<br>
Dani</p>
|
[
{
"answer_id": 276530,
"author": "Marc",
"author_id": 8478,
"author_profile": "https://Stackoverflow.com/users/8478",
"pm_score": 2,
"selected": false,
"text": "<p><code>repmat</code> is your friend:</p>\n\n<pre><code>b = repmat(Request, 1000, 1);\n\nElapsed time is 0.056720 seconds\n\n\nb = repmat(RequestH, 1000, 1);\nElapsed time is 0.021749 seconds.\n</code></pre>\n\n<p>Growing by appending is abysmally slow, which is why mlint calls it out.</p>\n"
},
{
"answer_id": 285407,
"author": "b3.",
"author_id": 14946,
"author_profile": "https://Stackoverflow.com/users/14946",
"pm_score": 3,
"selected": true,
"text": "<p>This solution expands on <a href=\"https://stackoverflow.com/questions/276198/matlab-class-array#276530\">Marc's answer</a>. Use <strong>repmat</strong> to initialize an array of RequestH objects and then use a loop to create the desired objects:</p>\n\n<pre><code>>> a = repmat(RequestH,10000,1);tic,for i=1:10000 a(i)=RequestH;end;toc\nElapsed time is 0.396645 seconds.\n</code></pre>\n\n<p>This is an improvement over:</p>\n\n<pre><code>>> a=[];tic,for i=1:10000 a=[a RequestH];end;toc\nElapsed time is 2.313368 seconds.\n</code></pre>\n"
},
{
"answer_id": 2417773,
"author": "jjkparker",
"author_id": 283735,
"author_profile": "https://Stackoverflow.com/users/283735",
"pm_score": 3,
"selected": false,
"text": "<p>Coming to this late, but would this not be another solution?</p>\n\n<pre><code>a = Request.empty(1000,0); tic; for i=1:1000, a(i)=Request; end; toc;\nElapsed time is 0.087539 seconds.\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>a(1000, 1) = Request;\nElapsed time is 0.019755 seconds.\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28772/"
] |
What would be the best way to manage large number of instances of the same class in MATLAB?
Using the naive way produces absymal results:
```
classdef Request
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> a=[];
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 5.426852 seconds.
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 31.261500 seconds.
```
Inheriting handle drastically improve the results:
```
classdef RequestH < handle
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.174573 seconds.
```
but still not an acceptable performance, especially considering the increasing reallocation overhead
Is there a way to preallocate class array? Any ideas on how to manage lange quantities of object effectively?
Thanks,
Dani
|
This solution expands on [Marc's answer](https://stackoverflow.com/questions/276198/matlab-class-array#276530). Use **repmat** to initialize an array of RequestH objects and then use a loop to create the desired objects:
```
>> a = repmat(RequestH,10000,1);tic,for i=1:10000 a(i)=RequestH;end;toc
Elapsed time is 0.396645 seconds.
```
This is an improvement over:
```
>> a=[];tic,for i=1:10000 a=[a RequestH];end;toc
Elapsed time is 2.313368 seconds.
```
|
276,206 |
<p>I have a form made up of multiple, optional subparts - each of which is enclosed in a</p>
<pre><code><div class="details"></div>
</code></pre>
<p>When editing the form I would like to hide those subparts which aren't as yet completed, and obviously I would like to do it unobtrusively. To simplify things I'm just checking to see if those fields whose name ends in 'surname' are empty, and then show/hide appropriately. So far, I have this.</p>
<pre><code>//hide the all of the element class details
$(".details").each(function (i) {
if ($('input[name$=surname]:empty',this).length == 1) {
$(this).hide();
} else {
$(this).show();
}
});
</code></pre>
<p>Of course, the :empty selector may be wrong, or indeed inappropriate. (Of course what I really want to do is show any parts where any fields are completed, but I thought I'd start with just checking the most important one.)</p>
<p>I would be greatful if anyone could anyone point me in the right direction...</p>
|
[
{
"answer_id": 276221,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 4,
"selected": true,
"text": "<p>No selector love? Not exactly sure it's what you're really looking for but this hides all details elements with an empty input inside. Perhaps it's a clue.</p>\n\n<pre><code><div class=\"details\">\n <input type=\"text\" name=\"surname\" />\n</div>\n\n<script type=\"text/javascript\">\n $(\".details input[@value='']\").parents(\".details\").hide();\n</script>\n</code></pre>\n"
},
{
"answer_id": 276241,
"author": "Kevin Gorski",
"author_id": 35806,
"author_profile": "https://Stackoverflow.com/users/35806",
"pm_score": 1,
"selected": false,
"text": "<p>This may have just been a typo, but you also don't need / shouldn't have a CSS class name of \".details\" in your markup, just \"details\". The dot prefix is part of the CSS/jQuery selector syntax.</p>\n\n<p>According to the <a href=\"http://docs.jquery.com/Selectors/empty\" rel=\"nofollow noreferrer\">documentation</a>, \":empty\" finds empty elements (as in containing no child elements), not form elements without values (an empty textbox). Checking for the value attribute equating to an empty string will work for single line text inputs, but you'd need a more complex query for including text areas, radio buttons, etc.</p>\n"
},
{
"answer_id": 276294,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>This would probably do the requested thing:</p>\n\n<pre><code>$(\"div.details input\").each(function () {\n if (this.value == \"\")\n $(this).parents(\"div.details\").eq(1).hide();\n else\n $(this).parents(\"div.details\").eq(1).show();\n});\n</code></pre>\n\n<p>To affect only fields with \"surname\" in the name attribute, do the obvious:</p>\n\n<pre><code>$(\"div.details input[name$=surname]\").each(function () { /* etc... */\n</code></pre>\n"
},
{
"answer_id": 276327,
"author": "Dycey",
"author_id": 35961,
"author_profile": "https://Stackoverflow.com/users/35961",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks guys - the [value=\"\"] was the piece I was missing. In case anyone else wonders, the barebones jQuery that did the trick (thanks to cristian) was</p>\n\n<pre><code> //hide the all of the element class details\n $(\".details\").each(function (i) {\n if ($('input[name$=surname][value=\"\"]',this).length == 1) { \n $(this).hide();\n console.log('hiding');\n } else {\n $(this).show();\n console.log('showing');\n }\n });\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35961/"
] |
I have a form made up of multiple, optional subparts - each of which is enclosed in a
```
<div class="details"></div>
```
When editing the form I would like to hide those subparts which aren't as yet completed, and obviously I would like to do it unobtrusively. To simplify things I'm just checking to see if those fields whose name ends in 'surname' are empty, and then show/hide appropriately. So far, I have this.
```
//hide the all of the element class details
$(".details").each(function (i) {
if ($('input[name$=surname]:empty',this).length == 1) {
$(this).hide();
} else {
$(this).show();
}
});
```
Of course, the :empty selector may be wrong, or indeed inappropriate. (Of course what I really want to do is show any parts where any fields are completed, but I thought I'd start with just checking the most important one.)
I would be greatful if anyone could anyone point me in the right direction...
|
No selector love? Not exactly sure it's what you're really looking for but this hides all details elements with an empty input inside. Perhaps it's a clue.
```
<div class="details">
<input type="text" name="surname" />
</div>
<script type="text/javascript">
$(".details input[@value='']").parents(".details").hide();
</script>
```
|
276,212 |
<p>I have a table in a database that represents dates textually (i.e. "2008-11-09") and I would like to replace them with the UNIX timestamp. However, I don't think that MySQL is capable of doing the conversion on its own, so I'd like to write a little script to do the conversion. The way I can think to do it involves getting all the records in the table, iterating through them, and updating the database records. However, with no primary key, I can't easily get the exact record I need to update.</p>
<p>Is there a way to get MySQL to assign temporary IDs to records during a SELECT so that I refer back to them when doing UPDATEs?</p>
|
[
{
"answer_id": 276225,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 1,
"selected": false,
"text": "<p>If for some reason you do have to iterate (the other answers cover the situation where you don't), I can think of two ways to do it (these aren't MySQL-specific):</p>\n\n<ol>\n<li><p>Add a column to the table that's an auto-assigned number. Use that as the PK for your updates, then drop the column afterwards (or just keep it around for future use).</p></li>\n<li><p>In a table with no defined PK, as long as there are no exact duplicate rows, you can use the entire row as a composite PK; just use every column in the row as your distinguishing characteristic. i.e., if the table has 3 columns, \"name\", \"address\", and \"updated\", do the following:</p>\n\n<p>UPDATE mytable SET updated = [timestamp value] WHERE name = [name] AND address = [address] AND timestamp = [old timestamp]</p></li>\n</ol>\n\n<p>Many data access frameworks use this exact strategy to implement optimistic concurrency.</p>\n"
},
{
"answer_id": 276226,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 1,
"selected": false,
"text": "<p>No, you should be able to do this with a single update statement. If all of the dates are yyyy-mm-dd and they are just stored in some sort of text column instead of DATETIME, you can just move the data over. SQL would be like:</p>\n\n<pre><code>ALTER TABLE t ADD COLUMN dates DATETIME;\nUPDATE t set t.dates=t.olddate;\n</code></pre>\n\n<p>This shouldn't be dependent on a PK because MySQL can scan through each row in the table. The only time PK's become an issue is if you need to update a single row, but the row may not be unique.</p>\n"
},
{
"answer_id": 276228,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>Does this not do it?</p>\n\n<pre><code>UPDATE\n MyTable\nSET\n MyTimeStamp = UNIX_TIMESTAMP(MyDateTime);\n</code></pre>\n"
},
{
"answer_id": 276234,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>You can generate values during a <code>SELECT</code> using the MySQL user variables feature, but these values do not refer to the row; they're temporary parts of the result set only. You can't use them in <code>UPDATE</code> statements.</p>\n\n<pre><code>SET @v := 0;\nSELECT @v:=@v+1, * FROM mytable;\n</code></pre>\n\n<p>Here's how I'd solve the problem. You're going to have to create another column for your UNIX timestamps anyway, so you can add it first. Then convert the values in the old datetime column to the UNIX timestamp and place it in the new column. Then drop the old textual datetime column.</p>\n\n<pre><code>ALTER TABLE mytable ADD COLUMN unix_timestamp INT UNSIGNED NOT NULL DEFAULT 0;\n\nUPDATE mytable\nSET unix_timestamp = UNIX_TIMESTAMP( STR_TO_DATE( text_timestamp, '%Y-%m-%d' ) );\n\nALTER TABLE mytable DROP COLUMN text_timestamp;\n</code></pre>\n\n<p>Of course you should confirm that the conversion has been done correctly before you drop the old column!</p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp\" rel=\"nofollow noreferrer\"><code>UNIX_TIMESTAMP()</code></a> and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date\" rel=\"nofollow noreferrer\"><code>STR_TO_DATE()</code></a></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] |
I have a table in a database that represents dates textually (i.e. "2008-11-09") and I would like to replace them with the UNIX timestamp. However, I don't think that MySQL is capable of doing the conversion on its own, so I'd like to write a little script to do the conversion. The way I can think to do it involves getting all the records in the table, iterating through them, and updating the database records. However, with no primary key, I can't easily get the exact record I need to update.
Is there a way to get MySQL to assign temporary IDs to records during a SELECT so that I refer back to them when doing UPDATEs?
|
Does this not do it?
```
UPDATE
MyTable
SET
MyTimeStamp = UNIX_TIMESTAMP(MyDateTime);
```
|
276,249 |
<p>I have this form:</p>
<pre><code><form name="customize">
Only show results within
<select name="distance" id="slct_distance">
<option>25</option>
<option>50</option>
<option>100</option>
<option value="10000" selected="selected">Any</option>
</select> miles of zip code
<input type="text" class="text" name="zip_code" id="txt_zip_code" />
<span id="customize_validation_msg"></span>
</form>
</code></pre>
<p>How can I select the <code>input</code> and <code>select</code> with one jQuery selector?</p>
<p>I tried this but it selected all of the selects and inputs on the page:</p>
<pre><code>$("form[name='customize'] select,input")
</code></pre>
|
[
{
"answer_id": 276267,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 2,
"selected": false,
"text": "<p>For me your suggestion worked. You could also use</p>\n\n<pre><code>form[name='customize'] select, form[name='customize'] input\n</code></pre>\n\n<p>Both selectors work as I see it. Maybe the the problem lies somewhere else?</p>\n\n<p>I tried</p>\n\n<pre><code>$(\"form[name='customize'] select, input\").css( 'font-size', '80px' );\n</code></pre>\n\n<p>on your example HTML. The font size for select and input changed.</p>\n\n<p>--- edit ---</p>\n\n<p>My suggestion above is the right one. It selects just the elements in the customize-form.</p>\n"
},
{
"answer_id": 276284,
"author": "Kevin Gorski",
"author_id": 35806,
"author_profile": "https://Stackoverflow.com/users/35806",
"pm_score": 6,
"selected": true,
"text": "<p>The comma in the selector string separates completely separate expressions, just like in CSS, so the selector you've given gets the select elements within the form named \"customize\" and all inputs on the form (as you've described). It sounds like you want something like this:</p>\n\n<pre><code>$(\"form[name='customize'] select, form[name='customize'] input\")\n</code></pre>\n\n<p>or if you're not into repitition, this:</p>\n\n<pre><code>$(\"form[name='customize']\").children(\"select, input\")\n</code></pre>\n"
},
{
"answer_id": 276299,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 3,
"selected": false,
"text": "<p>A shorter syntax $(selector,parentselector) is also possible.\nExample on this page :</p>\n\n<pre><code>// all spans\n$(\"span\").css(\"background-color\",\"#ff0\");\n\n// spans below a post-text class\n$(\"span\", \".post-text\").css(\"background-color\",\"#f00\");\n</code></pre>\n\n<p>Edit -- I forgot the particular case of several kind of children !</p>\n\n<pre><code>// spans and p's below a post-text class\n$(\"span,p\", \".post-text\").css(\"background-color\",\"#f00\");\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
I have this form:
```
<form name="customize">
Only show results within
<select name="distance" id="slct_distance">
<option>25</option>
<option>50</option>
<option>100</option>
<option value="10000" selected="selected">Any</option>
</select> miles of zip code
<input type="text" class="text" name="zip_code" id="txt_zip_code" />
<span id="customize_validation_msg"></span>
</form>
```
How can I select the `input` and `select` with one jQuery selector?
I tried this but it selected all of the selects and inputs on the page:
```
$("form[name='customize'] select,input")
```
|
The comma in the selector string separates completely separate expressions, just like in CSS, so the selector you've given gets the select elements within the form named "customize" and all inputs on the form (as you've described). It sounds like you want something like this:
```
$("form[name='customize'] select, form[name='customize'] input")
```
or if you're not into repitition, this:
```
$("form[name='customize']").children("select, input")
```
|
276,253 |
<p>C#: How do you pass an object in a function parameter?</p>
<pre><code>public void MyFunction(TextBox txtField)
{
txtField.Text = "Hi.";
}
</code></pre>
<p>Would the above be valid? Or?</p>
|
[
{
"answer_id": 276263,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 4,
"selected": true,
"text": "<p>So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods.</p>\n"
},
{
"answer_id": 276269,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Yup, that will work. You're not actually passing an object - you're passing in a <em>reference</em> to the object.</p>\n\n<p>See <a href=\"http://pobox.com/~skeet/csharp/parameters.html\" rel=\"noreferrer\">\"Parameter passing in C#\"</a> for details when it comes to pass-by-ref vs pass-by-value.</p>\n"
},
{
"answer_id": 276279,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>For any reference-type, that is fine - you have passed the <em>reference</em> to the object, but there is only one object, so changes are visible to the caller.</p>\n\n<p>The main time that <em>won't</em> work is for \"structs\" (value-types) - but they really shouldn't be mutable anyway (i.e. they shouldn't really have editable properties).</p>\n\n<p>If you <em>needed</em> to do this with a struct, you could add \"ref\" - i.e.</p>\n\n<pre><code>public void MyFunction(ref MyMutableStruct whatever)\n{\n whatever.Value = \"Hi.\"; // but avoid mutable structs in the first place!\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
C#: How do you pass an object in a function parameter?
```
public void MyFunction(TextBox txtField)
{
txtField.Text = "Hi.";
}
```
Would the above be valid? Or?
|
So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods.
|
276,254 |
<p>I have a window (derived from JFrame) and I want to disable the close button during certain operations which are not interruptible. I know I can make the button not do anything (or call a handler in a WindowListener) by calling</p>
<pre><code>setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
</code></pre>
<p>but I would like to make it clear visually that it is pointless to click it.</p>
|
[
{
"answer_id": 276482,
"author": "bdumitriu",
"author_id": 35415,
"author_profile": "https://Stackoverflow.com/users/35415",
"pm_score": 4,
"selected": true,
"text": "<p>If I understand it correctly, <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6199687\" rel=\"noreferrer\">this bug report</a> indicates that this is currently not possible.</p>\n"
},
{
"answer_id": 279826,
"author": "Malfist",
"author_id": 12243,
"author_profile": "https://Stackoverflow.com/users/12243",
"pm_score": 5,
"selected": false,
"text": "<p>This is probably the best you are going to get:</p>\n\n<pre><code>setUndecorated(true);\ngetRootPane().setWindowDecorationStyle(JRootPane.NONE);\n</code></pre>\n\n<p>This will remove the entire titlebar, java doesn't really specify a way to remove individual components of the titlebar</p>\n\n<p>edit:</p>\n\n<p>There may be a way, check out these threads:</p>\n\n<ul>\n<li><a href=\"http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=015407\" rel=\"noreferrer\">link 1</a> </li>\n<li><a href=\"http://forums.sun.com/thread.jspa?messageID=10255068\" rel=\"noreferrer\">link 2</a></li>\n</ul>\n"
},
{
"answer_id": 9117824,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 3,
"selected": false,
"text": "<p>For those coming to this later than 2008, there has been a change making it possible to do this. See <a href=\"http://www.coderanch.com/t/344419/GUI/java/deactivate-close-minimise-resizable-window\" rel=\"nofollow\">this link</a></p>\n\n<p>Second response from the bottom shows how to do it by name.</p>\n"
},
{
"answer_id": 27587807,
"author": "Ab Hin",
"author_id": 1497868,
"author_profile": "https://Stackoverflow.com/users/1497868",
"pm_score": -1,
"selected": false,
"text": "<p>Please try this</p>\n\n<pre><code>frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {\n e.getWindow().setVisible(false);\n try {\n wait();\n } catch (InterruptedException ex) {\n Logger.getLogger(WindowsActions.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n });\n</code></pre>\n"
},
{
"answer_id": 29060254,
"author": "Vörös Richárd",
"author_id": 4673020,
"author_profile": "https://Stackoverflow.com/users/4673020",
"pm_score": 3,
"selected": false,
"text": "<p>This will help you:</p>\n\n<pre><code>frame.setDefaultCloseOperation(0);\n</code></pre>\n"
},
{
"answer_id": 53951512,
"author": "Cancer000",
"author_id": 10840859,
"author_profile": "https://Stackoverflow.com/users/10840859",
"pm_score": 0,
"selected": false,
"text": "<p>To simply make them disappear, try the following:</p>\n\n<pre><code>setUndecorated(true);\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18308/"
] |
I have a window (derived from JFrame) and I want to disable the close button during certain operations which are not interruptible. I know I can make the button not do anything (or call a handler in a WindowListener) by calling
```
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
```
but I would like to make it clear visually that it is pointless to click it.
|
If I understand it correctly, [this bug report](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6199687) indicates that this is currently not possible.
|
276,266 |
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p>
<blockquote>
<p>The error is "IOError: [Errorno
Invalid output device (no default
output device)] -9996</p>
</blockquote>
<p>Is there another library I could try to use? Another method?</p>
|
[
{
"answer_id": 276322,
"author": "lpfavreau",
"author_id": 35935,
"author_profile": "https://Stackoverflow.com/users/35935",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at pymedia? It looks as easy as this to play a WAV file:</p>\n\n<pre><code>import time, wave, pymedia.audio.sound as sound\nf= wave.open('YOUR FILE NAME', 'rb')\nsampleRate= f.getframerate()\nchannels= f.getnchannels()\nformat= sound.AFMT_S16_LE\nsnd= sound.Output(sampleRate, channels, format)\ns= f.readframes(300000)\nsnd.play(s)\nwhile snd.isPlaying(): time.sleep(0.05)\n</code></pre>\n\n<p>Ref: <a href=\"http://pymedia.org/tut/play_wav.html\" rel=\"nofollow noreferrer\">http://pymedia.org/tut/play_wav.html</a></p>\n\n<p>Of course, you can have a look at the Python wiki under Audio (<a href=\"http://wiki.python.org/moin/Audio/\" rel=\"nofollow noreferrer\">http://wiki.python.org/moin/Audio/</a>) for other libraries such as <a href=\"https://docs.python.org/library/wave.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/wave.html</a> or again in Python's wiki under Game Libraries (<a href=\"http://wiki.python.org/moin/PythonGameLibraries\" rel=\"nofollow noreferrer\">http://wiki.python.org/moin/PythonGameLibraries</a>) that will point you to bindings to OpenAL or Pygame that has sound modules.</p>\n\n<p>And finally, although I don't know the limitations of pyaudio, your error message sounds more like the library is not able to find the default output device more than the device is in use by another process. Maybe have a look at what output device is returned by the <code>get_default_output_device_info</code> of pyaudio and compare it to whatever's your default setting in Ubuntu.</p>\n"
},
{
"answer_id": 277274,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://wxpython.org/\" rel=\"noreferrer\">wxPython</a></p>\n\n<pre><code>sound = wx.Sound('sound.wav')\nsound.Play(wx.SOUND_SYNC)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sound.Play(wx.SOUND_ASYNC)\n</code></pre>\n\n<p><a href=\"http://svn.wxwidgets.org/viewvc/wx/wxPython/tags/wxPy-2.8.9.1/wxPython/demo/Sound.py?view=markup\" rel=\"noreferrer\">Here</a> is an example from the wxPython demo.</p>\n"
},
{
"answer_id": 277429,
"author": "Mauli",
"author_id": 917,
"author_profile": "https://Stackoverflow.com/users/917",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not absolutely sure if that fulfills your requirements, but I immediately thought PyGame</p>\n\n<p><a href=\"http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound\" rel=\"nofollow noreferrer\" title=\"PyGame Sound Module\">http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound</a></p>\n\n<pre><code>from pygame import mixer\n\nmixer.init()\ns = mixer.Sound('sound.wav')\ns.play()\n</code></pre>\n"
},
{
"answer_id": 36284017,
"author": "Erwin Mayer",
"author_id": 541420,
"author_profile": "https://Stackoverflow.com/users/541420",
"pm_score": 2,
"selected": false,
"text": "<p>You can try <a href=\"http://simpleaudio.readthedocs.org/en/latest/index.html\" rel=\"nofollow\">Simpleaudio</a>:</p>\n\n<pre><code>> pip install simpleaudio\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>import simpleaudio as sa\n\nwave_obj = sa.WaveObject.from_wave_file(\"path/to/file.wav\")\nplay_obj = wave_obj.play()\nplay_obj.wait_done()\n</code></pre>\n"
},
{
"answer_id": 48409739,
"author": "Nae",
"author_id": 7032856,
"author_profile": "https://Stackoverflow.com/users/7032856",
"pm_score": 1,
"selected": false,
"text": "<p>I found <a href=\"https://pypi.python.org/pypi/playsound\" rel=\"nofollow noreferrer\"><code>playsound</code></a> to be the simplest.</p>\n\n<pre><code>from playsound import playsound\n\nis_synchronus = False\nplaysound(r\"C:\\Windows\\Media\\chimes.wav\", is_synchronus)\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14520/"
] |
I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.
>
> The error is "IOError: [Errorno
> Invalid output device (no default
> output device)] -9996
>
>
>
Is there another library I could try to use? Another method?
|
You can use [wxPython](http://wxpython.org/)
```
sound = wx.Sound('sound.wav')
sound.Play(wx.SOUND_SYNC)
```
or
```
sound.Play(wx.SOUND_ASYNC)
```
[Here](http://svn.wxwidgets.org/viewvc/wx/wxPython/tags/wxPy-2.8.9.1/wxPython/demo/Sound.py?view=markup) is an example from the wxPython demo.
|
276,278 |
<p>Comparing LinkedLists and Arrays while also comparing their differences with sorted and unsorted data</p>
<ul>
<li>Adding </li>
<li>Removing</li>
<li>Retrieving </li>
<li>Sorting</li>
<li>Overall speed</li>
<li>Overall memory usage</li>
</ul>
<p>Actual questions</p>
<blockquote>
<p>Discuss the feasibility of implementing an unsorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application?</p>
<p>Discuss the feasibility of implementing a sorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application? </p>
<p>Based on your answers to the previous questions, summarize the costs and benefits of using linked lists in an application.</p>
</blockquote>
<p>My answers/input:</p>
<blockquote>
<p>LinkedLists have to allocate memory everytime a new Node is added, useful when adding many Nodes and size keeps changing but generally slower when adding few elements</p>
<p>Arrays allocated memory at the beggining of the program run, resizing list slow (adding many elements slow if have to resize)</p>
<p>Retrieval is faster in array due to indexing</p>
<p>Adding/removing faster in LinkedList due to pointers</p>
</blockquote>
|
[
{
"answer_id": 276314,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure what class this is for, but for a CS program, you will have to do better than \"is slow\" and \"is fast\". Try to quantify that, in terms of number-of-operations-needed. You should be familiar with a machinery typically used for such quantification -use that machinery.</p>\n"
},
{
"answer_id": 276361,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 3,
"selected": true,
"text": "<p>On unsorted vs. sorted. I'll do one, then you really do need to do your homework</p>\n\n<p>Stackoverflow markup really needs tables to do this one. You want to say how \"expensive\" the operation is for the unsorted/array, sorted/array, unsorted/linked-list, sorted/linked-list</p>\n\n<p>One final point: \"speed of the application\" is a hint to consider more than just the speed of the individual operations. </p>\n\n<pre><code>* Adding\n</code></pre>\n\n<p>Unsorted: Array adding is O(1) unless resizing needed - just add it to the end. You might want to discuss a resizing strategy that minimises the overhead (hint: don't just increase the size by one)</p>\n\n<p>Sorted: Array adding is O(n) - finding the place to add it is O(log(n)), but you need to move half the elements up (on average) to make romm for the new one</p>\n\n<p>Unsorted: Linked list is O(1) - add it to the start or end of the list.</p>\n\n<p>Sorted: Linked list is O(n) - although you can again add the element in O(1), you need to scan through half the list on average to find the place to put it.</p>\n\n<p>So, over to you for the rest. Post an answer, and we'll critique it, but to get the most from your (presumably) expensive educatiom, you really need to do some work on this :)</p>\n\n<pre><code>* Removing\n* Retrieving\n* Sorting\n* Overall speed\n* Overall memory usage\n</code></pre>\n"
},
{
"answer_id": 276376,
"author": "twodayslate",
"author_id": 27570,
"author_profile": "https://Stackoverflow.com/users/27570",
"pm_score": 0,
"selected": false,
"text": "<p>@Paul: Thanks</p>\n\n<blockquote>\n <ul>\n <li>Removing</li>\n </ul>\n</blockquote>\n\n<p>Unsorted & sorted: Array removing is O(n) - have to move all element over to fill 'hole'</p>\n\n<p>Unsorted & sorted: Linked list is O(1) - Change pointers as needed</p>\n"
},
{
"answer_id": 50168373,
"author": "Sandeep Singh",
"author_id": 4067548,
"author_profile": "https://Stackoverflow.com/users/4067548",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Here is a C++ code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let’s try out a sample C++ program to understand the problem statement better.\n</code></pre>\n\n<p>// CPP program to demonstrate processing\n// time of sorted and unsorted array</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n#include <ctime>\nusing namespace std;\n\nconst int N = 100001;\n\nint main()\n{\n int arr[N];\n\n // Assign random values to array\n for (int i=0; i<N; i++)\n arr[i] = rand()%N;\n\n // for loop for unsorted array\n int count = 0;\n double start = clock();\n for (int i=0; i<N; i++)\n if (arr[i] < N/2)\n count++;\n\n double end = clock();\n cout << \"Time for unsorted array :: \"\n << ((end - start)/CLOCKS_PER_SEC)\n << endl;\n sort(arr, arr+N);\n\n // for loop for sorted array\n count = 0;\n start = clock();\n\n for (int i=0; i<N; i++)\n if (arr[i] < N/2)\n count++;\n\n end = clock();\n cout << \"Time for sorted array :: \"\n << ((end - start)/CLOCKS_PER_SEC)\n << endl;\n\n return 0;\n}\n</code></pre>\n\n<p>//Output of the code</p>\n\n<pre><code>Output :\n\nExecution 1:\nTime for an unsorted array: 0.00108\nTime for a sorted array: 0.00053\n\nExecution 2:\nTime for an unsorted array: 0.001101\nTime for a sorted array: 0.000593\n\nExecution 3:\nTime for an unsorted array: 0.0011\nTime for a sorted array: 0.000418\nObserve that time taken for processing a sorted array is less as compared to an unsorted array. The reason for this optimization for a sorted array is branch prediction.\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27570/"
] |
Comparing LinkedLists and Arrays while also comparing their differences with sorted and unsorted data
* Adding
* Removing
* Retrieving
* Sorting
* Overall speed
* Overall memory usage
Actual questions
>
> Discuss the feasibility of implementing an unsorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application?
>
>
> Discuss the feasibility of implementing a sorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application?
>
>
> Based on your answers to the previous questions, summarize the costs and benefits of using linked lists in an application.
>
>
>
My answers/input:
>
> LinkedLists have to allocate memory everytime a new Node is added, useful when adding many Nodes and size keeps changing but generally slower when adding few elements
>
>
> Arrays allocated memory at the beggining of the program run, resizing list slow (adding many elements slow if have to resize)
>
>
> Retrieval is faster in array due to indexing
>
>
> Adding/removing faster in LinkedList due to pointers
>
>
>
|
On unsorted vs. sorted. I'll do one, then you really do need to do your homework
Stackoverflow markup really needs tables to do this one. You want to say how "expensive" the operation is for the unsorted/array, sorted/array, unsorted/linked-list, sorted/linked-list
One final point: "speed of the application" is a hint to consider more than just the speed of the individual operations.
```
* Adding
```
Unsorted: Array adding is O(1) unless resizing needed - just add it to the end. You might want to discuss a resizing strategy that minimises the overhead (hint: don't just increase the size by one)
Sorted: Array adding is O(n) - finding the place to add it is O(log(n)), but you need to move half the elements up (on average) to make romm for the new one
Unsorted: Linked list is O(1) - add it to the start or end of the list.
Sorted: Linked list is O(n) - although you can again add the element in O(1), you need to scan through half the list on average to find the place to put it.
So, over to you for the rest. Post an answer, and we'll critique it, but to get the most from your (presumably) expensive educatiom, you really need to do some work on this :)
```
* Removing
* Retrieving
* Sorting
* Overall speed
* Overall memory usage
```
|
276,281 |
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p>
<p>Scenario:
My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p>
<p>Target platform is *nix, however I would like to do it on a Win host also.</p>
|
[
{
"answer_id": 276289,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>resource</code> module provides <a href=\"http://www.python.org/doc/2.5.2/lib/node522.html\" rel=\"nofollow noreferrer\"><code>getrusage</code></a> which can give you the information you need, at least for Unix-like platforms.</p>\n\n<p>Note that CPU usage as a percentage is always measured over a time interval. Essentially, it is the amount of time taken by your program doing something divided by the interval time.</p>\n\n<p>For example, if your application takes 2 seconds of CPU time over a 5 second period, then it can be said to be using 40% of the CPU.</p>\n\n<p>Note that this calculation, as simple as it seems, can get tricky when using a multiprocessor system. If your application uses 7 seconds of CPU time in 5 seconds of wall clock time on a two-processor system, do you say it is uses 140% or 70% CPU?</p>\n\n<p>Update: As <a href=\"https://stackoverflow.com/questions/276281/cpu-usage-per-process-in-python#276295\">gimel</a> mentions, the <code>os.times</code> function also provides this information in a platform-independent way. The above calculation notes still apply, of course.</p>\n"
},
{
"answer_id": 276295,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 6,
"selected": true,
"text": "<pre><code>>>> import os\n>>> os.times()\n(1.296875, 0.765625, 0.0, 0.0, 0.0)\n>>> print os.times.__doc__\ntimes() -> (utime, stime, cutime, cstime, elapsed_time)\n\nReturn a tuple of floating point numbers indicating process times.\n</code></pre>\n<p>From the (2.5) manual:</p>\n<blockquote>\n<p>times( )</p>\n<p>Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows.</p>\n</blockquote>\n"
},
{
"answer_id": 4815145,
"author": "Ramchandra Apte",
"author_id": 443348,
"author_profile": "https://Stackoverflow.com/users/443348",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>time.clock()</code> to get the CPU time.\nTo get the percentage of CPU usage do CPU time elapsed/time elapsed</p>\n\n<p>For example, if CPU time elapsed is 0.2 and time elapsed is 1 then the cpu usage is 20%.</p>\n\n<p>Note:You have to divide by by number of processers you have. If you have 2 i.e. a dual core:</p>\n\n<pre><code>import decimal,timeit\ndecimal.getcontext().prec=1000\ndef torture():\n decimal.Decimal(2).sqrt()\n time.sleep(0.1)\nimport time\nclock=time.clock()\nwhile 1:\n clock=timeit.timeit(torture,number=10)\n tclock=time.clock()\n print((tclock-clock)*p)\n clock=tclock\n</code></pre>\n"
},
{
"answer_id": 6265475,
"author": "Giampaolo Rodolà",
"author_id": 376587,
"author_profile": "https://Stackoverflow.com/users/376587",
"pm_score": 4,
"selected": false,
"text": "<p>By using <a href=\"http://code.google.com/p/psutil\" rel=\"nofollow noreferrer\">psutil</a>:</p>\n\n<pre><code>>>> import psutil\n>>> p = psutil.Process()\n>>> p.cpu_times()\ncputimes(user=0.06, system=0.03)\n>>> p.cpu_percent(interval=1)\n0.0\n>>> \n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?
Scenario:
My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?
Target platform is \*nix, however I would like to do it on a Win host also.
|
```
>>> import os
>>> os.times()
(1.296875, 0.765625, 0.0, 0.0, 0.0)
>>> print os.times.__doc__
times() -> (utime, stime, cutime, cstime, elapsed_time)
Return a tuple of floating point numbers indicating process times.
```
From the (2.5) manual:
>
> times( )
>
>
> Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows.
>
>
>
|
276,286 |
<p>When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in <a href="http://djangoproject.com/" rel="nofollow noreferrer">Django</a>?</p>
|
[
{
"answer_id": 276323,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 2,
"selected": false,
"text": "<p>You can't.</p>\n\n<p>301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page <em>must</em> have a 200 code.</p>\n\n<p>One small variant is to detect search engine spiders (by IP and/or user agent) and give <em>them</em> the 301. That way the search results point to your new page.</p>\n"
},
{
"answer_id": 276326,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<pre><code> from django import http\n\n return http.HttpResponsePermanentRedirect('/yournewpage.html')\n</code></pre>\n\n<p>the browser will get the 301, and go to <code>/yournewpage.html</code> as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:</p>\n\n<pre><code>Browser Python HTTP\n -------------------> GET /youroldpage.html HTTP/1.1\n\n <------------------- HTTP/1.1 301 Moved Permanently\n Location: /yournewpage.html\n -------------------> GET /yournewpage.html HTTP/1.1\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11452/"
] |
When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in [Django](http://djangoproject.com/)?
|
```
from django import http
return http.HttpResponsePermanentRedirect('/yournewpage.html')
```
the browser will get the 301, and go to `/yournewpage.html` as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:
```
Browser Python HTTP
-------------------> GET /youroldpage.html HTTP/1.1
<------------------- HTTP/1.1 301 Moved Permanently
Location: /yournewpage.html
-------------------> GET /yournewpage.html HTTP/1.1
```
|
276,292 |
<p>How can I continuously capture images from a webcam?</p>
<p>I want to experiment with object recognition (by maybe using java media framework). </p>
<p>I was thinking of creating two threads</p>
<p>one thread:</p>
<ul>
<li>Node 1: capture live image</li>
<li>Node 2: save image as "1.jpg"</li>
<li>Node 3: wait 5 seconds</li>
<li>Node 4: repeat...</li>
</ul>
<p>other thread:</p>
<ul>
<li>Node 1: wait until image is captured</li>
<li>Node 2: using the "1.jpg" get colors
from every pixle</li>
<li>Node 3: save data in arrays</li>
<li>Node 4: repeat...</li>
</ul>
|
[
{
"answer_id": 276775,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the web-cam application software which comes along with the web-cam, or you native windows webcam software can be run in a batch script(windows/dos script) after turning the web cam on(i.e. if it needs an external power supply). In the bacth script , u can add appropriate delay to capture after certain time period. And keep executing the capture command in loop.</p>\n\n<p>I guess this should be possible</p>\n\n<p>-AD</p>\n"
},
{
"answer_id": 278636,
"author": "Karl",
"author_id": 36093,
"author_profile": "https://Stackoverflow.com/users/36093",
"pm_score": 1,
"selected": false,
"text": "<p>Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.</p>\n\n<p>Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it. </p>\n\n<p>Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?</p>\n"
},
{
"answer_id": 278691,
"author": "ArnauVP",
"author_id": 36256,
"author_profile": "https://Stackoverflow.com/users/36256",
"pm_score": 2,
"selected": false,
"text": "<p>I have used JMF on a videoconference application and it worked well on two laptops: one with integrated webcam and another with an old USB webcam. It requires JMF being installed and configured before-hand, but once you're done you can access the hardware via Java code fairly easily.</p>\n"
},
{
"answer_id": 278752,
"author": "Dan Monego",
"author_id": 32771,
"author_profile": "https://Stackoverflow.com/users/32771",
"pm_score": 0,
"selected": false,
"text": "<p>There's a pretty nice interface for this in <a href=\"http://processing.org\" rel=\"nofollow noreferrer\">processing</a>, which is kind of a <a href=\"http://www.flight404.com/_videos/pigeonCam.mov\" rel=\"nofollow noreferrer\">pidgin</a> java designed for graphics. It gets used in some image recognition work, such as that link.</p>\n\n<p>Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.</p>\n"
},
{
"answer_id": 292424,
"author": "rics",
"author_id": 21047,
"author_profile": "https://Stackoverflow.com/users/21047",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/115835/what-is-the-best-method-to-capture-images-from-a-live-video-device-for-use-by-a\">Here</a> is a similar question with some - yet unaccepted - answers. One of them mentions <a href=\"http://fmj-sf.net/\" rel=\"nofollow noreferrer\">FMJ</a> as a java alternative to JMF.</p>\n"
},
{
"answer_id": 395059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>FMJ can do this, as can the supporting library it uses, LTI-CIVIL. Both are on sourceforge.</p>\n"
},
{
"answer_id": 971686,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://grack.com/downloads/school/enel619.10/report/java_media_framework.html\" rel=\"nofollow noreferrer\">http://grack.com/downloads/school/enel619.10/report/java_media_framework.html</a></p>\n\n<p>Using the Player with Swing</p>\n\n<p>The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:</p>\n\n<pre><code>import javax.media.*;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.net.*;\nimport java.awt.event.*;\nimport javax.swing.event.*;\n\npublic class JMFTest extends JFrame {\n Player _player;\n JMFTest() {\n addWindowListener( new WindowAdapter() {\n public void windowClosing( WindowEvent e ) {\n _player.stop();\n _player.deallocate();\n _player.close();\n System.exit( 0 );\n }\n });\n setExtent( 0, 0, 320, 260 );\n JPanel panel = (JPanel)getContentPane();\n panel.setLayout( new BorderLayout() );\n String mediaFile = \"vfw://1\";\n try {\n MediaLocator mlr = new MediaLocator( mediaFile );\n _player = Manager.createRealizedPlayer( mlr );\n if (_player.getVisualComponent() != null)\n panel.add(\"Center\", _player.getVisualComponent());\n if (_player.getControlPanelComponent() != null)\n panel.add(\"South\", _player.getControlPanelComponent());\n }\n catch (Exception e) {\n System.err.println( \"Got exception \" + e );\n }\n }\n\n public static void main(String[] args) {\n JMFTest jmfTest = new JMFTest();\n jmfTest.show();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1520206,
"author": "Rose",
"author_id": 138684,
"author_profile": "https://Stackoverflow.com/users/138684",
"pm_score": 0,
"selected": false,
"text": "<p>Recommand using FMJ for multimedia relatived java app.</p>\n"
},
{
"answer_id": 4383406,
"author": "Nile",
"author_id": 243667,
"author_profile": "https://Stackoverflow.com/users/243667",
"pm_score": 3,
"selected": false,
"text": "<p>JMyron is very simple for use.\n<a href=\"http://webcamxtra.sourceforge.net/\" rel=\"noreferrer\">http://webcamxtra.sourceforge.net/</a></p>\n\n<pre><code>myron = new JMyron();\nmyron.start(imgw, imgh);\nmyron.update();\nint[] img = myron.image();\n</code></pre>\n"
},
{
"answer_id": 8185050,
"author": "Hugo",
"author_id": 1054135,
"author_profile": "https://Stackoverflow.com/users/1054135",
"pm_score": 2,
"selected": false,
"text": "<p>You can try <a href=\"http://marvinproject.sourceforge.net\" rel=\"nofollow noreferrer\">Marvin Framework</a>. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.</p>\n\n<p>Take a look!</p>\n\n<p>Real-time Video Processing Demo:<br/>\n<a href=\"http://www.youtube.com/watch?v=D5mBt0kRYvk\" rel=\"nofollow noreferrer\">http://www.youtube.com/watch?v=D5mBt0kRYvk</a></p>\n\n<p>You can use the source below. Just save a frame using <strong>MarvinImageIO.saveImage()</strong> every 5 second.</p>\n\n<p><strong>Webcam video demo:</strong></p>\n\n<pre><code>public class SimpleVideoTest extends JFrame implements Runnable{\n\n private MarvinVideoInterface videoAdapter;\n private MarvinImage image;\n private MarvinImagePanel videoPanel;\n\n public SimpleVideoTest(){\n super(\"Simple Video Test\");\n videoAdapter = new MarvinJavaCVAdapter();\n videoAdapter.connect(0);\n videoPanel = new MarvinImagePanel();\n add(videoPanel);\n new Thread(this).start();\n setSize(800,600);\n setVisible(true);\n }\n @Override\n public void run() {\n while(true){\n // Request a video frame and set into the VideoPanel\n image = videoAdapter.getFrame();\n videoPanel.setImage(image);\n }\n }\n public static void main(String[] args) {\n SimpleVideoTest t = new SimpleVideoTest();\n t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n}\n</code></pre>\n\n<p>For those who just want to take a single picture:</p>\n\n<p><strong>WebcamPicture.java</strong></p>\n\n<pre><code>public class WebcamPicture {\n public static void main(String[] args) {\n try{\n MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();\n videoAdapter.connect(0);\n MarvinImage image = videoAdapter.getFrame();\n MarvinImageIO.saveImage(image, \"./res/webcam_picture.jpg\");\n } catch(MarvinVideoInterfaceException e){\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9046345,
"author": "gtiwari333",
"author_id": 607637,
"author_profile": "https://Stackoverflow.com/users/607637",
"pm_score": 6,
"selected": false,
"text": "<p>This JavaCV implementation works fine.</p>\n<p>Code:</p>\n<pre><code>import org.bytedeco.javacv.*;\nimport org.bytedeco.opencv.opencv_core.IplImage;\n\nimport java.io.File;\n\nimport static org.bytedeco.opencv.global.opencv_core.cvFlip;\nimport static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;\n\npublic class Test implements Runnable {\n final int INTERVAL = 100;///you may use interval\n CanvasFrame canvas = new CanvasFrame("Web Cam");\n\n public Test() {\n canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);\n }\n\n public void run() {\n\n new File("images").mkdir();\n\n FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera\n OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();\n IplImage img;\n int i = 0;\n try {\n grabber.start();\n\n while (true) {\n Frame frame = grabber.grab();\n\n img = converter.convert(frame);\n\n //the grabbed frame will be flipped, re-flip to make it right\n cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise\n\n //save\n cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);\n\n canvas.showImage(converter.convert(img));\n\n Thread.sleep(INTERVAL);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n Test gs = new Test();\n Thread th = new Thread(gs);\n th.start();\n }\n}\n</code></pre>\n<p>There is also <a href=\"http://ganeshtiwaridotcomdotnp.blogspot.com/2017/01/javacv-configuration-in-windows.html\" rel=\"nofollow noreferrer\">post on configuration for JavaCV</a></p>\n<p>You can modify the codes and be able to save the images in regular interval and do rest of the processing you want.</p>\n"
},
{
"answer_id": 9160057,
"author": "Andrei ",
"author_id": 30612,
"author_profile": "https://Stackoverflow.com/users/30612",
"pm_score": 2,
"selected": false,
"text": "<p>You can try <a href=\"http://www.smaxe.com/product.jsf?id=juv-webcam-sdk\" rel=\"nofollow\">Java Webcam SDK</a> library also.\nSDK demo applet is available at <a href=\"http://demo.smaxe.com/juv-na-demo-webcam.html\" rel=\"nofollow\">link</a>.</p>\n"
},
{
"answer_id": 10509410,
"author": "extjstutorial.info",
"author_id": 1383569,
"author_profile": "https://Stackoverflow.com/users/1383569",
"pm_score": 0,
"selected": false,
"text": "<p>Try using JMyron <a href=\"http://howto-java.blogspot.com/2012/05/how-to-use-webcam-using-java.html\" rel=\"nofollow\">How To Use Webcam Using Java</a>. I think using JMyron is the easiest way to access a webcam using java. I tried to use it with a 64-bit processor, but it gave me an error. It worked just fine on a 32-bit processor, though.</p>\n"
},
{
"answer_id": 13347845,
"author": "Bartosz Firyn",
"author_id": 626311,
"author_profile": "https://Stackoverflow.com/users/626311",
"pm_score": 5,
"selected": false,
"text": "<p>Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.</p>\n\n<p>Link to the project is <a href=\"https://github.com/sarxos/webcam-capture\" rel=\"noreferrer\">https://github.com/sarxos/webcam-capture</a></p>\n\n<p>Example code (take picture and save in test.jpg):</p>\n\n<pre><code>Webcam webcam = Webcam.getDefault();\nwebcam.open();\nBufferedImage image = webcam.getImage();\nImageIO.write(image, \"JPG\", new File(\"test.jpg\"));\n</code></pre>\n\n<p>It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.</p>\n"
},
{
"answer_id": 15982047,
"author": "syb0rg",
"author_id": 1937270,
"author_profile": "https://Stackoverflow.com/users/1937270",
"pm_score": 3,
"selected": false,
"text": "<p>This kind of goes off of gt_ebuddy's answer using JavaCV, but my video output is at a much higher quality then his answer. I've also added some other random improvements (such as closing down the program when <kbd>ESC</kbd> and <kbd>CTRL+C</kbd> are pressed, and making sure to close down the resources the program uses properly).</p>\n\n<pre><code>import java.awt.event.ActionEvent;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.image.BufferedImage;\n\nimport javax.swing.AbstractAction;\nimport javax.swing.ActionMap;\nimport javax.swing.InputMap;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\nimport javax.swing.KeyStroke;\n\nimport com.googlecode.javacv.CanvasFrame;\nimport com.googlecode.javacv.OpenCVFrameGrabber;\nimport com.googlecode.javacv.cpp.opencv_core.IplImage;\n\npublic class HighRes extends JComponent implements Runnable {\n private static final long serialVersionUID = 1L;\n\n private static CanvasFrame frame = new CanvasFrame(\"Web Cam\");\n private static boolean running = false;\n private static int frameWidth = 800;\n private static int frameHeight = 600;\n private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);\n private static BufferedImage bufImg;\n\n public HighRes()\n {\n // setup key bindings\n ActionMap actionMap = frame.getRootPane().getActionMap();\n InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);\n\n for (Keys direction : Keys.values())\n {\n actionMap.put(direction.getText(), new KeyBinding(direction.getText()));\n inputMap.put(direction.getKeyStroke(), direction.getText());\n }\n\n frame.getRootPane().setActionMap(actionMap);\n frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);\n\n // setup window listener for close action\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.addWindowListener(new WindowAdapter()\n {\n public void windowClosing(WindowEvent e)\n {\n stop();\n }\n });\n }\n\n public static void main(String... args)\n {\n HighRes webcam = new HighRes();\n webcam.start();\n }\n\n @Override\n public void run()\n {\n try\n {\n\n grabber.setImageWidth(frameWidth);\n grabber.setImageHeight(frameHeight);\n grabber.start();\n while (running)\n {\n\n final IplImage cvimg = grabber.grab();\n if (cvimg != null)\n {\n\n // cvFlip(cvimg, cvimg, 1); // mirror\n\n // show image on window\n bufImg = cvimg.getBufferedImage();\n frame.showImage(bufImg);\n }\n }\n grabber.stop();\n grabber.release();\n frame.dispose();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n public void start()\n {\n new Thread(this).start();\n running = true;\n }\n\n public void stop()\n {\n running = false;\n }\n\n private class KeyBinding extends AbstractAction {\n\n private static final long serialVersionUID = 1L;\n\n public KeyBinding(String text)\n {\n super(text);\n putValue(ACTION_COMMAND_KEY, text);\n }\n\n @Override\n public void actionPerformed(ActionEvent e)\n {\n String action = e.getActionCommand();\n if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();\n else System.out.println(\"Key Binding: \" + action);\n }\n }\n}\n\nenum Keys\n{\n ESCAPE(\"Escape\", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),\n CTRLC(\"Control-C\", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),\n UP(\"Up\", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),\n DOWN(\"Down\", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),\n LEFT(\"Left\", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),\n RIGHT(\"Right\", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));\n\n private String text;\n private KeyStroke keyStroke;\n\n Keys(String text, KeyStroke keyStroke)\n {\n this.text = text;\n this.keyStroke = keyStroke;\n }\n\n public String getText()\n {\n return text;\n }\n\n public KeyStroke getKeyStroke()\n {\n return keyStroke;\n }\n\n @Override\n public String toString()\n {\n return text;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46145364,
"author": "Uddika Dilshan",
"author_id": 7368579,
"author_profile": "https://Stackoverflow.com/users/7368579",
"pm_score": 2,
"selected": false,
"text": "<p>I used Webcam Capture API. You can download it from <a href=\"http://webcam-capture.sarxos.pl/\" rel=\"nofollow noreferrer\">here</a></p>\n<pre><code>webcam = Webcam.getDefault();\nwebcam.open();\n\nif (webcam.isOpen()) { //if web cam open \n BufferedImage image = webcam.getImage();\n JLabel imageLbl = new JLabel();\n imageLbl.setSize(640, 480); //show captured image\n imageLbl.setIcon(new ImageIcon(image));\n\n int showConfirmDialog = JOptionPane.showConfirmDialog(null, imageLbl, "Image Viewer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(""));\n\n if (showConfirmDialog == JOptionPane.YES_OPTION) {\n JFileChooser chooser = new JFileChooser();\n chooser.setDialogTitle("Save Image");\n chooser.setFileFilter(new FileNameExtensionFilter("IMAGES ONLY", "png", "jpeg", "jpg")); //this file extentions are shown\n int showSaveDialog = chooser.showSaveDialog(this);\n if (showSaveDialog == 0) { //if pressed 'Save' button\n String filePath = chooser.getCurrentDirectory().toString().replace("\\\\", "/");\n String fileName = chooser.getSelectedFile().getName(); //get user entered file name to save\n ImageIO.write(image, "PNG", new File(filePath + "/" + fileName + ".png"));\n\n }\n }\n}\n\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35962/"
] |
How can I continuously capture images from a webcam?
I want to experiment with object recognition (by maybe using java media framework).
I was thinking of creating two threads
one thread:
* Node 1: capture live image
* Node 2: save image as "1.jpg"
* Node 3: wait 5 seconds
* Node 4: repeat...
other thread:
* Node 1: wait until image is captured
* Node 2: using the "1.jpg" get colors
from every pixle
* Node 3: save data in arrays
* Node 4: repeat...
|
This JavaCV implementation works fine.
Code:
```
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.io.File;
import static org.bytedeco.opencv.global.opencv_core.cvFlip;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class Test implements Runnable {
final int INTERVAL = 100;///you may use interval
CanvasFrame canvas = new CanvasFrame("Web Cam");
public Test() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public void run() {
new File("images").mkdir();
FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
IplImage img;
int i = 0;
try {
grabber.start();
while (true) {
Frame frame = grabber.grab();
img = converter.convert(frame);
//the grabbed frame will be flipped, re-flip to make it right
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
//save
cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);
canvas.showImage(converter.convert(img));
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Test gs = new Test();
Thread th = new Thread(gs);
th.start();
}
}
```
There is also [post on configuration for JavaCV](http://ganeshtiwaridotcomdotnp.blogspot.com/2017/01/javacv-configuration-in-windows.html)
You can modify the codes and be able to save the images in regular interval and do rest of the processing you want.
|
276,319 |
<p>Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.</p>
<p>It would be nice to be able to do this using SharpZipLib.</p>
|
[
{
"answer_id": 276330,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can use SharpZipLib to do this - when you need to supply a stream to write to, use a <code>MemoryStream</code>.</p>\n"
},
{
"answer_id": 276335,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": -1,
"selected": false,
"text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/system.io.stringreader.aspx\" rel=\"nofollow noreferrer\">StringReader</a> to read from your string objects and expose them as Stream s.</p>\n\n<p>That should make it easy to feed them to your zip-building code.</p>\n"
},
{
"answer_id": 276347,
"author": "Cory",
"author_id": 8207,
"author_profile": "https://Stackoverflow.com/users/8207",
"pm_score": 6,
"selected": true,
"text": "<p>Use <code>ZipEntry</code> and <code>PutNextEntry()</code> for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream</p>\n\n<pre><code>FileStream fZip = File.Create(compressedOutputFile);\nZipOutputStream zipOStream = new ZipOutputStream(fZip);\nforeach (FileInfo fi in allfiles)\n{\n ZipEntry entry = new ZipEntry((fi.Name));\n zipOStream.PutNextEntry(entry);\n FileStream fs = File.OpenRead(fi.FullName);\n try\n {\n byte[] transferBuffer[1024];\n do\n {\n bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);\n zipOStream.Write(transferBuffer, 0, bytesRead);\n }\n while (bytesRead > 0);\n }\n finally\n {\n fs.Close();\n }\n}\nzipOStream.Finish();\nzipOStream.Close();\n</code></pre>\n"
},
{
"answer_id": 276399,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "<p><em>Note this answer is outdated; since .Net 4.5, the <code>ZipArchive</code> class allows zipping files in-memory. See <a href=\"https://stackoverflow.com/a/45067125/9536\">johnny 5's answer below</a> for how to use it.</em></p>\n\n<hr>\n\n<p>You could also do it a bit differently, using a Serializable object to store all strings</p>\n\n<pre><code>[Serializable]\npublic class MyStrings {\n public string Foo { get; set; }\n public string Bar { get; set; }\n}\n</code></pre>\n\n<p>Then, you could serialize it into a stream to save it.<br>\nTo save on space you could use GZipStream (From System.IO.Compression) to compress it. (note: GZip is stream compression, not an archive of multiple files).</p>\n\n<p>That is, of course if what you need is actually to save data, and not zip a few files in a specific format for other software.\nAlso, this would allow you to save many more types of data except strings.</p>\n"
},
{
"answer_id": 384068,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 4,
"selected": false,
"text": "<p>Using SharpZipLib for this seems pretty complicated. This is so much easier in <a href=\"http://www.codeplex.com/DotNetZip\" rel=\"noreferrer\">DotNetZip</a>. In v1.9, the code looks like this: </p>\n\n<pre><code>using (ZipFile zip = new ZipFile())\n{\n zip.AddEntry(\"Readme.txt\", stringContent1);\n zip.AddEntry(\"readings/Data.csv\", stringContent2);\n zip.AddEntry(\"readings/Index.xml\", stringContent3);\n zip.Save(\"Archive1.zip\"); \n}\n</code></pre>\n\n<p>The code above assumes stringContent{1,2,3} contains the data to be stored in the files (or entries) in the zip archive. The first entry is \"Readme.txt\" and it is stored in the top level \"Directory\" in the zip archive. The next two entries are stored in the \"readings\" directory in the zip archive.</p>\n\n<p>The strings are encoded in the default encoding. There is an overload of AddEntry(), not shown here, that allows you to explicitly specify the encoding to use. </p>\n\n<p>If you have the content in a stream or byte array, not a string, there are overloads for AddEntry() that accept those types. There are also overloads that accept a Write delegate, a method of yours that is invoked to write data into the zip. This works for easily saving a DataSet into a zip file, for example. </p>\n\n<p>DotNetZip is free and open source.</p>\n"
},
{
"answer_id": 7689375,
"author": "Ashleigh",
"author_id": 984230,
"author_profile": "https://Stackoverflow.com/users/984230",
"pm_score": 3,
"selected": false,
"text": "<p>I come across this problem, using the MSDN example I created this class:</p>\n\n<pre><code>using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.IO.Packaging; \nusing System.IO; \n\npublic class ZipSticle \n{ \n Package package; \n\n public ZipSticle(Stream s) \n { \n package = ZipPackage.Open(s, FileMode.Create); \n } \n\n public void Add(Stream stream, string Name) \n { \n Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Name, UriKind.Relative)); \n PackagePart packagePartDocument = package.CreatePart(partUriDocument, \"\"); \n\n CopyStream(stream, packagePartDocument.GetStream()); \n stream.Close(); \n } \n\n private static void CopyStream(Stream source, Stream target) \n { \n const int bufSize = 0x1000; \n byte[] buf = new byte[bufSize]; \n int bytesRead = 0; \n while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) \n target.Write(buf, 0, bytesRead); \n } \n\n public void Close() \n { \n package.Close(); \n } \n}\n</code></pre>\n\n<p>You can then use it like this:</p>\n\n<pre><code>FileStream str = File.Open(\"MyAwesomeZip.zip\", FileMode.Create); \nZipSticle zip = new ZipSticle(str); \n\nzip.Add(File.OpenRead(\"C:/Users/C0BRA/SimpleFile.txt\"), \"Some directory/SimpleFile.txt\"); \nzip.Add(File.OpenRead(\"C:/Users/C0BRA/Hurp.derp\"), \"hurp.Derp\"); \n\nzip.Close();\nstr.Close();\n</code></pre>\n\n<p>You can pass a <code>MemoryStream</code> (or any <code>Stream</code>) to <code>ZipSticle.Add</code> such as:</p>\n\n<pre><code>FileStream str = File.Open(\"MyAwesomeZip.zip\", FileMode.Create); \nZipSticle zip = new ZipSticle(str); \n\nbyte[] fileinmem = new byte[1000];\n// Do stuff to FileInMemory\nMemoryStream memstr = new MemoryStream(fileinmem);\nzip.Add(memstr, \"Some directory/SimpleFile.txt\");\n\nmemstr.Close();\nzip.Close();\nstr.Close();\n</code></pre>\n"
},
{
"answer_id": 45067125,
"author": "johnny 5",
"author_id": 1938988,
"author_profile": "https://Stackoverflow.com/users/1938988",
"pm_score": 3,
"selected": false,
"text": "<p>This function should create a byte array from a stream of data: I've created a simple interface for handling files for simplicity</p>\n<pre><code>public interface IHasDocumentProperties\n{\n byte[] Content { get; set; }\n string Name { get; set; }\n}\n\npublic void CreateZipFileContent(string filePath, IEnumerable<IHasDocumentProperties> fileInfos)\n{ \n using (var memoryStream = new MemoryStream())\n {\n using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))\n {\n foreach(var fileInfo in fileInfos)\n {\n var entry = zipArchive.CreateEntry(fileInfo.Name);\n\n using (var entryStream = entry.Open())\n {\n entryStream.Write(fileInfo.Content, 0, fileInfo.Content.Length);\n } \n }\n }\n \n using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, System.IO.FileAccess.Write))\n {\n memoryStream.Position = 0;\n memoryStream.CopyTo(fileStream);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46324856,
"author": "krillgar",
"author_id": 1195056,
"author_profile": "https://Stackoverflow.com/users/1195056",
"pm_score": 2,
"selected": false,
"text": "<p>I was utilizing <a href=\"https://stackoverflow.com/a/384068/1195056\">Cheeso's answer</a> by adding <code>MemoryStream</code>s as the source of the different Excel files. When I downloaded the zip, the files had nothing in them. This could be the way we were getting around trying to create and download a file over AJAX.</p>\n\n<p>To get the contents of the different Excel files to be included in the Zip, I had to add each of the files as a <code>byte[]</code>.</p>\n\n<pre><code>using (var memoryStream = new MemoryStream())\nusing (var zip = new ZipFile())\n{\n zip.AddEntry(\"Excel File 1.xlsx\", excelFileStream1.ToArray());\n zip.AddEntry(\"Excel File 2.xlsx\", excelFileStream2.ToArray());\n\n // Keep the file off of disk, and in memory.\n zip.Save(memoryStream);\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.
It would be nice to be able to do this using SharpZipLib.
|
Use `ZipEntry` and `PutNextEntry()` for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream
```
FileStream fZip = File.Create(compressedOutputFile);
ZipOutputStream zipOStream = new ZipOutputStream(fZip);
foreach (FileInfo fi in allfiles)
{
ZipEntry entry = new ZipEntry((fi.Name));
zipOStream.PutNextEntry(entry);
FileStream fs = File.OpenRead(fi.FullName);
try
{
byte[] transferBuffer[1024];
do
{
bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);
zipOStream.Write(transferBuffer, 0, bytesRead);
}
while (bytesRead > 0);
}
finally
{
fs.Close();
}
}
zipOStream.Finish();
zipOStream.Close();
```
|
276,324 |
<p>I'm trying to create a horizontal navigation bar in css with 5 evenly spaced links. The html hopefully will remain like this:</p>
<pre><code><div id="footer">
<ul>
<li><a href="one.html">One</a></li>
<li><a href="two.html">Two</a></li>
<li><a href="three.html">Three</a></li>
<li><a href="four.html">Four</a></li>
<li><a href="five.html">Five</a></li>
</ul>
</div>
</code></pre>
<p>So with CSS, I want to space them evenly within the footer div. So far I'm using this:</p>
<pre><code>div#footer{
height:1.5em;
background-color:green;
clear:both;
padding-top:.5em;
font-size:1.5em;
width:800px;
}
div#footer ul{
margin:0;
padding:0;
list-style:none;
}
div#footer li{
width:155px;
display:inline-block;
text-align:center;
}
</code></pre>
<p>This works pretty well, but there is spacing between the li's that I do not want. That is why I've used the 155px instead of 160px for their width, there is about 5px of space being put in between each li. Where is that spacing coming from? How can I get rid of it? If I increase the fontsize, the spacing increases as well. </p>
|
[
{
"answer_id": 276333,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 4,
"selected": false,
"text": "<p>If you use this:</p>\n\n<pre><code>div#footer li{\n width:160px;\n display:block;\n float: left;\n text-align:center;\n}\n</code></pre>\n\n<p>It all looks lovely :D</p>\n"
},
{
"answer_id": 276340,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 6,
"selected": true,
"text": "<p>I've had this happen to me. Unfortunately it is caused by the browser taking the line breaks between the list items and rendering them as spaces. To fix, change your HTML to:</p>\n\n<pre><code><div id=\"footer\">\n <ul>\n <li><a href=\"one.html\">One</a></li><li><a href=\"two.html\">Two</a></li><li><a href=\"three.html\">Three</a></li><li><a href=\"four.html\">Four</a></li><li><a href=\"five.html\">Five</a></li>\n </ul>\n</div>\n</code></pre>\n"
},
{
"answer_id": 276352,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>The spaces between your <code><li></code> elements are due to the whitespaces and carriage returns between them, due to the inline style. If you write :</p>\n\n<pre><code><li><a href=\"one.html\">One</a></li><li><a href=\"two.html\">Two</a></li><li><a href=\"three.html\">Three</a></li><li><a href=\"four.html\">Four</a></li><li><a href=\"five.html\">Five</a></li>\n</code></pre>\n\n<p>You'll see no more space between them.</p>\n\n<p>I'm not sure if inline-block's will display nicely on IE6, so you may want to try the float approach. </p>\n"
},
{
"answer_id": 289890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>div#footer ul{\n margin:0;\n padding:0;\n list-style:none;\n}\n\ndiv#footer li{\n width:155px;\n float:left;\n display:block; \n}\n</code></pre>\n\n<p>This code positioned li horizontally while the spaces between them. If you want to adding space between li elements: </p>\n\n<pre><code>div#footer li{\n width:155px;\n margin-right: 5px; //5px Space between li elements \n float:left;\n display:block; \n}\n</code></pre>\n"
},
{
"answer_id": 30617166,
"author": "JeremyTM",
"author_id": 3122800,
"author_profile": "https://Stackoverflow.com/users/3122800",
"pm_score": 1,
"selected": false,
"text": "<p>This has been completely solved by CSS flexbox.</p>\n\n<p>CSS-Tricks have an excellent writeup <a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow\">here</a>, and a Codepen example using <code><ul></code> <a href=\"http://codepen.io/HugoGiraudel/pen/LklCv\" rel=\"nofollow\">here</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.flex-container {\r\n padding: 0;\r\n margin: 0;\r\n list-style: none;\r\n \r\n display: -webkit-box;\r\n display: -moz-box;\r\n display: -ms-flexbox;\r\n display: -webkit-flex;\r\n display: flex;\r\n \r\n -webkit-flex-flow: row nowrap;\r\n justify-content: space-around;\r\n}\r\n\r\n.flex-item {\r\n background: tomato;\r\n padding: 5px;\r\n margin: 0px;\r\n \r\n line-height: 40px;\r\n color: white;\r\n font-weight: bold;\r\n font-size: 2em;\r\n text-align: center;\r\n flex: 1 1 auto;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ul class=\"flex-container\">\r\n <li class=\"flex-item\">1</li>\r\n <li class=\"flex-item\">2</li>\r\n <li class=\"flex-item\">3</li>\r\n <li class=\"flex-item\">4</li>\r\n <li class=\"flex-item\">5</li>\r\n <li class=\"flex-item\">6</li>\r\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I realise this is quite old, but I encountered this issue 7 years later in 2015 so this might help someone else too.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to create a horizontal navigation bar in css with 5 evenly spaced links. The html hopefully will remain like this:
```
<div id="footer">
<ul>
<li><a href="one.html">One</a></li>
<li><a href="two.html">Two</a></li>
<li><a href="three.html">Three</a></li>
<li><a href="four.html">Four</a></li>
<li><a href="five.html">Five</a></li>
</ul>
</div>
```
So with CSS, I want to space them evenly within the footer div. So far I'm using this:
```
div#footer{
height:1.5em;
background-color:green;
clear:both;
padding-top:.5em;
font-size:1.5em;
width:800px;
}
div#footer ul{
margin:0;
padding:0;
list-style:none;
}
div#footer li{
width:155px;
display:inline-block;
text-align:center;
}
```
This works pretty well, but there is spacing between the li's that I do not want. That is why I've used the 155px instead of 160px for their width, there is about 5px of space being put in between each li. Where is that spacing coming from? How can I get rid of it? If I increase the fontsize, the spacing increases as well.
|
I've had this happen to me. Unfortunately it is caused by the browser taking the line breaks between the list items and rendering them as spaces. To fix, change your HTML to:
```
<div id="footer">
<ul>
<li><a href="one.html">One</a></li><li><a href="two.html">Two</a></li><li><a href="three.html">Three</a></li><li><a href="four.html">Four</a></li><li><a href="five.html">Five</a></li>
</ul>
</div>
```
|
276,336 |
<p>This is what I am working with to get back to the web dev world</p>
<p>ASP.Net with VS2008</p>
<p>Subsonic as Data Access Layer</p>
<p>SqlServer DB</p>
<p>Home Project description:
I have a student registration system. I have a web page which should display the student records. </p>
<p>At present I have a gridview control which shows the records</p>
<p>The user logs on and gets to the view students page. The gridview shows the students in the system, where one of the columns is the registration status of open, pending, complete.</p>
<p>I want the user to be able to apply dynamic sorting or filters on the result returned so as to obtain a more refined result they wish to see. I envisioned allowing user to filter the results by applying where clause or like clause on the result returned, via a dataset interface by a subsonic method. I do not want to query the databse again to apply the filter</p>
<p>example: initial query </p>
<pre><code>Select * from studentrecords where date = convert(varchar(32,getdate(),101)
</code></pre>
<p>The user then should be able to applly filter on the resultset returned so that they can do a last name like '%Souza%'</p>
<p>Is this even possible and is binding a datasource to a gridview control the best approach or should i create a custom collection inheriting from collectionbase and then binding that to the gridview control?</p>
<p>PS: Sorry about the typo's. My machine is under the influence of tea spill on my laptop </p>
|
[
{
"answer_id": 276369,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>I use LINQ-to-SQL, not Subsonic, so YMMV, but my approach to filtering has been to supply an OnSelecting handler to the data source. In LINQ-to-SQL, I'm able to replace the result with a reference to a DataContext method that returns a the result of applying a table-valued function. You might want to investigate something similar with Subsonic.</p>\n"
},
{
"answer_id": 276405,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>As tvanfosson said, LINQ is very well suited to making composable queries; you can do this either with fully dunamic TSQL that the base library generates, or via a UDF that you mark with [FunctionAttribute(..., IsComposable=true)] in the data-context.</p>\n\n<p>I'm not familiar with Subsonic, so I can't advise there; but one other thought: in your \"date = \" code, you might consider declaring a datetime variable and assigning it first... that way the optimiser can usually do a better job of optimising it (the query is simpler, and there is no question whether it is converting the datetime (per row) to a varchar, or the varchar to a datetime). The most efficient way of getting just the date portion of something is to cast/floor/cast:</p>\n\n<pre><code>SET @today = GETDATE()\nSET @today = CAST(FLOOR(CAST(@today as float)) as datetime)\n</code></pre>\n\n<p>[update re comment]</p>\n\n<p>Re composable - I mean that this allows you to build up a query such that only the <em>final</em> query is executed at the database. For example:</p>\n\n<pre><code>var query = from row in ctx.SomeComplexUdf(someArg)\n where row.IsOpen && row.Value > 0\n select row;\n</code></pre>\n\n<p>might go down the the server via the TSQL:</p>\n\n<pre><code>SELECT u1.*\nFROM dbo.SomeComplexUdf(@p1) u1\nWHERE u1.IsOpen = 1 -- might end up parameterized\nAND u1.Value > 0 -- might end up parameterized\n</code></pre>\n\n<p>The point here being that only the suitable data is returned from the server, rather than lots of data being returned, then thrown away. LINQ-to-SQL can do all sorts of things via compsable queries, including paging, sorting etc. By minimising the amount of data you load from the database you can make significant improvements in performance.</p>\n\n<p>The alternative without composability is that it simply does:</p>\n\n<pre><code>SELECT u1.*\nFROM dbo.SomeComplexUdf(@p1) u1\n</code></pre>\n\n<p>And then throws away the other rows in your web app... obviously, if you are expecting 20 open records and 10000 closed records, this is a huge difference.</p>\n"
},
{
"answer_id": 278515,
"author": "Rostov",
"author_id": 2108310,
"author_profile": "https://Stackoverflow.com/users/2108310",
"pm_score": 0,
"selected": false,
"text": "<p>How about something like this?</p>\n\n<p>Rather than assigning a data source / table to your grid control, instead attach a 'DataView' to it.</p>\n\n<p>Here's sort of a pseudocode example:</p>\n\n<pre><code>DataTable myDataTable = GetDataTableFromSomewhere(); \nDataGridView dgv = new DataGridView();\nDataView dv = new DataView(myDataTable);\n\n//Then you can specify things like:\ndv.Sort = \"StudentStatus DESC\";\ndv.Filter = \"StudentName LIKE '\" + searchName + '\";\ndgv.DataSource = dv;\n</code></pre>\n\n<p>...and so on.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This is what I am working with to get back to the web dev world
ASP.Net with VS2008
Subsonic as Data Access Layer
SqlServer DB
Home Project description:
I have a student registration system. I have a web page which should display the student records.
At present I have a gridview control which shows the records
The user logs on and gets to the view students page. The gridview shows the students in the system, where one of the columns is the registration status of open, pending, complete.
I want the user to be able to apply dynamic sorting or filters on the result returned so as to obtain a more refined result they wish to see. I envisioned allowing user to filter the results by applying where clause or like clause on the result returned, via a dataset interface by a subsonic method. I do not want to query the databse again to apply the filter
example: initial query
```
Select * from studentrecords where date = convert(varchar(32,getdate(),101)
```
The user then should be able to applly filter on the resultset returned so that they can do a last name like '%Souza%'
Is this even possible and is binding a datasource to a gridview control the best approach or should i create a custom collection inheriting from collectionbase and then binding that to the gridview control?
PS: Sorry about the typo's. My machine is under the influence of tea spill on my laptop
|
I use LINQ-to-SQL, not Subsonic, so YMMV, but my approach to filtering has been to supply an OnSelecting handler to the data source. In LINQ-to-SQL, I'm able to replace the result with a reference to a DataContext method that returns a the result of applying a table-valued function. You might want to investigate something similar with Subsonic.
|
276,345 |
<p>I'm trying to do the following in my Django template:</p>
<pre><code> {% for embed in embeds %}
{% embed2 = embed.replace("&lt;", "<") %}
{{embed2}}<br />
{% endfor %}
</code></pre>
<p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p>
<p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p>
<p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p>
<pre><code>embed_list = []
for embed in embeds:
embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35
return render_to_response("scanvideos.html", {
"embed_list" :embed_list
})
</code></pre>
<p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
|
[
{
"answer_id": 276372,
"author": "Hannes Ovrén",
"author_id": 13565,
"author_profile": "https://Stackoverflow.com/users/13565",
"pm_score": 3,
"selected": false,
"text": "<p>I am quite sure that Django templates does not support that.\nFor your replace operation I would look into different filters.</p>\n\n<p>You really should try to keep as much logic as you can in your views and not in the templates.</p>\n"
},
{
"answer_id": 276387,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>Django templates use their own syntax, not like <a href=\"http://en.wikipedia.org/wiki/Kid_%28templating_language%29\" rel=\"nofollow noreferrer\">Kid</a> or <a href=\"http://en.wikipedia.org/wiki/Genshi_%28templating_language%29\" rel=\"nofollow noreferrer\">Genshi</a>.</p>\n\n<p>You have to roll your own <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/\" rel=\"nofollow noreferrer\">Custom Template Tag</a>.</p>\n\n<p>I guess the main reason is enforcing good practice. In my case, I've already a hard time explaining those special templates tags to the designer on our team. If it was plain Python I'm pretty sure we wouldn't have chosen Django at all. I think there's also a performance issue, Django templates benchmarks are fast, while last time I checked genshi was much slower. I don't know if it's due to freely embedded Python, though.</p>\n\n<p>You either need to review your approach and write your own custom templates (more or less synonyms to \"helpers\" in Ruby on Rails), or try another template engine.</p>\n\n<p>For your edit, there's a better syntax in Python:</p>\n\n<pre><code>embed_list.append(embed.replace(\"&lt;\", \"<\"))\n</code></pre>\n\n<p>I don't know if it'll fix your error, but at least it's less JavaScriptesque ;-)</p>\n\n<p>Edit 2: Django automatically escapes all variables. You can enforce raw HTML with |safe filter : <code>{{embed|safe}}</code>.</p>\n\n<p>You'd better take some time reading the documentation, which is really great and useful.</p>\n"
},
{
"answer_id": 276394,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of using a slice assignment to grow a list</p>\n\n<p><code>embed_list[len(embed_list):] = [foo]</code></p>\n\n<p>you should probably just do</p>\n\n<p><code>embed_list.append(foo)</code></p>\n\n<p>But really you should try unescaping html with a library function rather than doing it yourself.</p>\n\n<p>That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.</p>\n"
},
{
"answer_id": 276395,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see why you'd get \"NoneType object is not callable\". That should mean that somewhere on the line is an expression like \"foo(...)\", and it means foo is None.</p>\n\n<p>BTW: You are trying to extend the embed_list, and it's easier to do it like this:</p>\n\n<pre><code>embed_list = []\nfor embed in embeds:\n embed_list.append(embed.replace(\"&lt;\", \"<\")) #this is line 35\nreturn render_to_response(\"scanvideos.html\", {\"embed_list\":embed_list})\n</code></pre>\n\n<p>and even easier to use a list comprehension:</p>\n\n<pre><code>embed_list = [embed.replace(\"&lt;\", \"<\") for embed in embeds]\n</code></pre>\n"
},
{
"answer_id": 276838,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 3,
"selected": false,
"text": "<p>Django's template language is deliberately hobbled. When used by non-programming designers, this is definitely a Good Thing, but there are times when you <em>need</em> to do a little programming. (No, I don't want to argue about that. This has come up several times on django-users and django-dev.)</p>\n\n<p>Two ways to accomplish what you were trying:</p>\n\n<ul>\n<li>Use a different template engine. See <a href=\"http://jinja.pocoo.org/2/\" rel=\"noreferrer\">Jinja2</a> for a good example that is fully explained for integrating with Django.</li>\n<li>Use a template tag that permits you to do Python expressions. See <a href=\"http://www.djangosnippets.org/snippets/9/\" rel=\"noreferrer\">limodou's Expr tag</a>.</li>\n</ul>\n\n<p>I have used the expr tag in several places and it has made life <em>much</em> easier. My next major Django site will use jinja2.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I'm trying to do the following in my Django template:
```
{% for embed in embeds %}
{% embed2 = embed.replace("<", "<") %}
{{embed2}}<br />
{% endfor %}
```
However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?
Edit: the exact error is: `Invalid block tag: 'embed2'`
Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:
```
embed_list = []
for embed in embeds:
embed_list[len(embed_list):] = [embed.replace("<", "<")] #this is line 35
return render_to_response("scanvideos.html", {
"embed_list" :embed_list
})
```
However, I now get an error: `'NoneType' object is not callable" on line 35`.
|
Instead of using a slice assignment to grow a list
`embed_list[len(embed_list):] = [foo]`
you should probably just do
`embed_list.append(foo)`
But really you should try unescaping html with a library function rather than doing it yourself.
That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.
|
276,355 |
<p>I could really do with updating a user's session variables from within my HTTPModule, but from what I can see, it isn't possible.</p>
<p><em>UPDATE:</em> My code is currently running inside the <code>OnBeginRequest ()</code> event handler.</p>
<p><em>UPDATE:</em> Following advice received so far, I tried adding this to the <code>Init ()</code> routine in my HTTPModule:</p>
<p><code>AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute</code></p>
<p>But in my <code>OnPreRequestHandlerExecute</code> routine, the session state is still unavailable!</p>
<p>Thanks, and apologies if I'm missing something!</p>
|
[
{
"answer_id": 276364,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpcontext.session.aspx\" rel=\"noreferrer\">HttpContext.Current.Session</a> should Just Work, assuming your HTTP Module isn't handling any <a href=\"http://msdn.microsoft.com/en-us/library/ms178473.aspx\" rel=\"noreferrer\">pipeline events</a> that occur prior to the session state being initialized...</p>\n\n<p>EDIT, after clarification in comments: when handling the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpapplication.beginrequest.aspx\" rel=\"noreferrer\">BeginRequest event</a>, the Session object will indeed still be null/Nothing, as it hasn't been initialized by the ASP.NET runtime yet. To work around this, move your handling code to an event that occurs after <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpapplication.postacquirerequeststate.aspx\" rel=\"noreferrer\">PostAcquireRequestState</a> -- I like <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpapplication.prerequesthandlerexecute.aspx\" rel=\"noreferrer\">PreRequestHandlerExecute</a> for that myself, as all low-level work is pretty much done at this stage, but you still pre-empt any normal processing.</p>\n"
},
{
"answer_id": 276373,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 7,
"selected": true,
"text": "<p>Found this over on the <a href=\"http://forums.asp.net/p/1098574/1665773.aspx\" rel=\"nofollow noreferrer\">ASP.NET forums</a>:</p>\n<pre><code>using System;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.SessionState;\nusing System.Diagnostics;\n\n// This code demonstrates how to make session state available in HttpModule,\n// regardless of requested resource.\n// author: Tomasz Jastrzebski\n\npublic class MyHttpModule : IHttpModule\n{\n public void Init(HttpApplication application)\n {\n application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);\n application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);\n }\n\n void Application_PostMapRequestHandler(object source, EventArgs e)\n {\n HttpApplication app = (HttpApplication)source;\n\n if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState) {\n // no need to replace the current handler\n return;\n }\n\n // swap the current handler\n app.Context.Handler = new MyHttpHandler(app.Context.Handler);\n }\n\n void Application_PostAcquireRequestState(object source, EventArgs e)\n {\n HttpApplication app = (HttpApplication)source;\n\n MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;\n\n if (resourceHttpHandler != null) {\n // set the original handler back\n HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;\n }\n\n // -> at this point session state should be available\n\n Debug.Assert(app.Session != null, "it did not work :(");\n }\n\n public void Dispose()\n {\n\n }\n\n // a temp handler used to force the SessionStateModule to load session state\n public class MyHttpHandler : IHttpHandler, IRequiresSessionState\n {\n internal readonly IHttpHandler OriginalHandler;\n\n public MyHttpHandler(IHttpHandler originalHandler)\n {\n OriginalHandler = originalHandler;\n }\n\n public void ProcessRequest(HttpContext context)\n {\n // do not worry, ProcessRequest() will not be called, but let's be safe\n throw new InvalidOperationException("MyHttpHandler cannot process requests.");\n }\n\n public bool IsReusable\n {\n // IsReusable must be set to false since class has a member!\n get { return false; }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 941958,
"author": "Rob",
"author_id": 84768,
"author_profile": "https://Stackoverflow.com/users/84768",
"pm_score": 4,
"selected": false,
"text": "<p>If you're writing a normal, basic HttpModule in a managed application that you want to apply to asp.net requests through pages or handlers, you just have to make sure you're using an event in the lifecycle after session creation. PreRequestHandlerExecute instead of Begin_Request is usually where I go. mdb has it right in his edit.</p>\n\n<p>The longer code snippet originally listed as answering the question works, but is complicated and broader than the initial question. It will handle the case when the content is coming from something that doesn't have an ASP.net handler available where you can implement the IRequiresSessionState interface, thus triggering the session mechanism to make it available. (Like a static gif file on disk). It's basically setting a dummy handler that then just implements that interface to make the session available.</p>\n\n<p>If you just want the session for your code, just pick the right event to handle in your module.</p>\n"
},
{
"answer_id": 7400727,
"author": "Bert Persyn",
"author_id": 638016,
"author_profile": "https://Stackoverflow.com/users/638016",
"pm_score": 4,
"selected": false,
"text": "<p>Accessing the <code>HttpContext.Current.Session</code> in a <code>IHttpModule</code> can be done in the <code>PreRequestHandlerExecute</code> handler. </p>\n\n<p><strong>PreRequestHandlerExecute</strong>: \"Occurs just before ASP.NET starts executing an event handler (for example, a page or an XML Web service).\" This means that before an 'aspx' page is served this event gets executed. The 'session state' is available so you can knock yourself out.</p>\n\n<p>Example:</p>\n\n<pre><code>public class SessionModule : IHttpModule \n {\n public void Init(HttpApplication context)\n {\n context.BeginRequest += BeginTransaction;\n context.EndRequest += CommitAndCloseSession;\n context.PreRequestHandlerExecute += PreRequestHandlerExecute;\n }\n\n\n\n public void Dispose() { }\n\n public void PreRequestHandlerExecute(object sender, EventArgs e)\n {\n var context = ((HttpApplication)sender).Context;\n context.Session[\"some_sesion\"] = new SomeObject();\n }\n...\n}\n</code></pre>\n"
},
{
"answer_id": 30310208,
"author": "aTest",
"author_id": 4913278,
"author_profile": "https://Stackoverflow.com/users/4913278",
"pm_score": 0,
"selected": false,
"text": "<p>Try it: in class MyHttpModule declare:</p>\n\n<pre><code>private HttpApplication contextapp;\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>public void Init(HttpApplication application)\n{\n //Must be after AcquireRequestState - the session exist after RequestState\n application.PostAcquireRequestState += new EventHandler(MyNewEvent);\n this.contextapp=application;\n} \n</code></pre>\n\n<p>And so, in another method (the event) in the same class:</p>\n\n<pre><code>public void MyNewEvent(object sender, EventArgs e)\n{\n //A example...\n if(contextoapp.Context.Session != null)\n {\n this.contextapp.Context.Session.Timeout=30;\n System.Diagnostics.Debug.WriteLine(\"Timeout changed\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67877994,
"author": "Antonio Bakula",
"author_id": 351383,
"author_profile": "https://Stackoverflow.com/users/351383",
"pm_score": 1,
"selected": false,
"text": "<p>Since .NET 4.0 there is no need for this hack with IHttpHandler to load Session state (like one in most upvoted answer). There is a method <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontext.setsessionstatebehavior\" rel=\"nofollow noreferrer\">HttpContext.SetSessionStateBehavior</a> to define needed session behaviour.\nIf Session is needed on all requests set <code>runAllManagedModulesForAllRequests</code> to true in web.config HttpModule declaration, but be aware that there is a significant performance cost running all modules for all requests, so be sure to use <code>preCondition="managedHandler"</code> if you don't need Session for all requests.\nFor future readers here is a complete example:</p>\n<p>web.config declaration - invoking HttpModule for all requests:</p>\n<pre><code><system.webServer>\n <modules runAllManagedModulesForAllRequests="true">\n <add name="ModuleWithSessionAccess" type="HttpModuleWithSessionAccess.ModuleWithSessionAccess, HttpModuleWithSessionAccess"/>\n </modules>\n</system.webServer>\n</code></pre>\n<p>web.config declaration - invoking HttpModule only for managed requests:</p>\n<pre><code><system.webServer>\n <modules>\n <add name="ModuleWithSessionAccess" type="HttpModuleWithSessionAccess.ModuleWithSessionAccess, HttpModuleWithSessionAccess" preCondition="managedHandler"/>\n </modules>\n</system.webServer>\n</code></pre>\n<p>IHttpModule implementation:</p>\n<pre><code>namespace HttpModuleWithSessionAccess\n{\n public class ModuleWithSessionAccess : IHttpModule\n {\n public void Init(HttpApplication context)\n {\n context.BeginRequest += Context_BeginRequest;\n context.PreRequestHandlerExecute += Context_PreRequestHandlerExecute;\n }\n\n private void Context_BeginRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n app.Context.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);\n }\n \n private void Context_PreRequestHandlerExecute(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n if (app.Context.Session != null)\n {\n app.Context.Session["Random"] = $"Random value: {new Random().Next()}";\n }\n }\n\n public void Dispose()\n {\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
] |
I could really do with updating a user's session variables from within my HTTPModule, but from what I can see, it isn't possible.
*UPDATE:* My code is currently running inside the `OnBeginRequest ()` event handler.
*UPDATE:* Following advice received so far, I tried adding this to the `Init ()` routine in my HTTPModule:
`AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute`
But in my `OnPreRequestHandlerExecute` routine, the session state is still unavailable!
Thanks, and apologies if I'm missing something!
|
Found this over on the [ASP.NET forums](http://forums.asp.net/p/1098574/1665773.aspx):
```
using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Diagnostics;
// This code demonstrates how to make session state available in HttpModule,
// regardless of requested resource.
// author: Tomasz Jastrzebski
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);
}
void Application_PostMapRequestHandler(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState) {
// no need to replace the current handler
return;
}
// swap the current handler
app.Context.Handler = new MyHttpHandler(app.Context.Handler);
}
void Application_PostAcquireRequestState(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;
if (resourceHttpHandler != null) {
// set the original handler back
HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
}
// -> at this point session state should be available
Debug.Assert(app.Session != null, "it did not work :(");
}
public void Dispose()
{
}
// a temp handler used to force the SessionStateModule to load session state
public class MyHttpHandler : IHttpHandler, IRequiresSessionState
{
internal readonly IHttpHandler OriginalHandler;
public MyHttpHandler(IHttpHandler originalHandler)
{
OriginalHandler = originalHandler;
}
public void ProcessRequest(HttpContext context)
{
// do not worry, ProcessRequest() will not be called, but let's be safe
throw new InvalidOperationException("MyHttpHandler cannot process requests.");
}
public bool IsReusable
{
// IsReusable must be set to false since class has a member!
get { return false; }
}
}
}
```
|
276,360 |
<p>Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage.</p>
<p>What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code-tree-building time. My reasoning is that while it's easy to just include() every class that you <strong>might</strong> need for every page that you have on a site, the CPU overhead can't be "free". I'd like to know how "expensive" parse time really is.</p>
<p>I am assuming that an opcode cache such as APC is <strong>not</strong> part of the scenario.</p>
<p>Would I be correct that measurement of parse time in PHP is something that would have to take place in mod_php?</p>
<p><strong>EDIT</strong>: If possible, taking into account <code>$_SERVER['DOCUMENT_ROOT']</code> usage in code would be helpful. Command solutions might take a bit of tinkering to do this (but still be valuable answers).</p>
|
[
{
"answer_id": 276366,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": false,
"text": "<p>One method could be timing the execution of the script from the command line.</p>\n\n<p>In Linux for example:</p>\n\n<pre><code>$ time php5 -r 'echo \"Hello world\";'\nHello world\nreal 0m1.565s\nuser 0m0.036s\nsys 0m0.024s\n</code></pre>\n\n<p>Does that help at all? Perhaps it is helpful for discovering relative times between different scripts, but it may not be indicative of time taken through the Apache module</p>\n"
},
{
"answer_id": 276367,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": true,
"text": "<p>Yes. There is.</p>\n\n<pre><code><?php return; rest of the code ?>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><?php whole code; $%^parse erorr!@! ?>\n</code></pre>\n\n<p>and then compare time of running empty script</p>\n\n<pre><code>time php empty.php\n</code></pre>\n\n<p>with time it takes to run (or fail) regular script with the additions I've mentioned above:</p>\n\n<pre><code>time php test.php\n</code></pre>\n\n<p>I've used this method on large files and PHP5.3 on Core2Duo 2.4Ghz can parse between 1.5 and 4.5MB of PHP code per second (it depends very much on complexity of the code of course).</p>\n"
},
{
"answer_id": 276424,
"author": "Eric Caron",
"author_id": 34340,
"author_profile": "https://Stackoverflow.com/users/34340",
"pm_score": 2,
"selected": false,
"text": "<p>For the detailed level of analysis you're seeking, it seems that implementing Xdebug (<a href=\"http://xdebug.org/\" rel=\"nofollow noreferrer\">http://xdebug.org/</a>) would give you the greatest information w/o having to chop your code into segmented pieces.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12694/"
] |
Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage.
What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code-tree-building time. My reasoning is that while it's easy to just include() every class that you **might** need for every page that you have on a site, the CPU overhead can't be "free". I'd like to know how "expensive" parse time really is.
I am assuming that an opcode cache such as APC is **not** part of the scenario.
Would I be correct that measurement of parse time in PHP is something that would have to take place in mod\_php?
**EDIT**: If possible, taking into account `$_SERVER['DOCUMENT_ROOT']` usage in code would be helpful. Command solutions might take a bit of tinkering to do this (but still be valuable answers).
|
Yes. There is.
```
<?php return; rest of the code ?>
```
or
```
<?php whole code; $%^parse erorr!@! ?>
```
and then compare time of running empty script
```
time php empty.php
```
with time it takes to run (or fail) regular script with the additions I've mentioned above:
```
time php test.php
```
I've used this method on large files and PHP5.3 on Core2Duo 2.4Ghz can parse between 1.5 and 4.5MB of PHP code per second (it depends very much on complexity of the code of course).
|
276,362 |
<p>I'm working on a project for OSX where the user can pick a collection of documents (from any application) which I need to generate PDF's from. The standard Macintosh Print dialog has a PDF button which has a number of PDF-related commands including "Save as PDF...". However, I need to generate the PDF file without requiring user interactions. I ideally want this to work with any type of document.</p>
<p>Here's the options I've explored so far:</p>
<ul>
<li>Automator actions. There's a PDF library for Automator but it provides actions for working with PDF files, not generating them. There's a Finder action for printing any file but only to a real printer.</li>
<li>AppleScript. Some applications have the ability to generate PDF files (for instance, if you send 'save doc in "test.pdf"' to Pages it will generate a PDF (but this only works for Pages - I need support for any type of document).</li>
<li>Custom Printer. I could create a virtual printer driver and then use the automator action but I don't like the idea of confusing the user with an extra printer in the print list.</li>
</ul>
<p>My hope is that there's some way to interact with the active application as if the user was carrying out the following steps:</p>
<ol>
<li>Do Cmd-P (opens the print dialog)</li>
<li>Click the "PDF" button</li>
<li>Select "Save as PDF..." (second item in menu)</li>
<li>Type in filename in save dialog</li>
<li>Click "Save"</li>
</ol>
<p>If that's the best approach (is it?) then the real problem is: how do I send UI Events to an external application (keystrokes, mouse events, menu selections) ?</p>
<p><strong>Update:</strong> Just to clarify one point: the documents I need to convert to PDF are documents that are created by <em>other applications</em>. For example, the user might pick a Word document or a Numbers spreadsheet or an OmniGraffle drawing or a Web Page. The common denominator is that each of these documents has an associated application and that application knows how to print it (and OSX knows how to render print output to a PDF file).</p>
<p>So, the samples at Cocoa Dev Central don't help because they're about generating a PDF from <em>my application</em>.</p>
|
[
{
"answer_id": 277015,
"author": "Timour",
"author_id": 21105,
"author_profile": "https://Stackoverflow.com/users/21105",
"pm_score": 4,
"selected": true,
"text": "<p>I think you could use applescript to open a document and then use <a href=\"https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AutomatetheUserInterface.html\" rel=\"nofollow noreferrer\">applescript UI scripting</a> to invoke print menu. </p>\n\n<p>For example : </p>\n\n<pre><code>tell application \"System Events\"\n tell window of process \"Safari\"\n set foremost to true\n keystroke \"p\" using {command down}\n delay 3\n click menu button \"PDF\" of sheet 2\n click menu item \"Save as PDF…\" of menu 1 of menu button \"PDF\" of sheet 2\n keystroke \"my_test.file\"\n keystroke return\n delay 10\n end tell\n\n end tell\n</code></pre>\n"
},
{
"answer_id": 2907895,
"author": "Sebastian Gallese",
"author_id": 254573,
"author_profile": "https://Stackoverflow.com/users/254573",
"pm_score": 0,
"selected": false,
"text": "<p>I typed up the code below with the assistance of Automator (recording an action, and then dragging the specific action out of the \"Watch Me Do\" window in order to get the Applescript). If you want to print a PDF from an application other than Safari, you might have to run through the same process and tweak this Applescript around the Print dialogue, since each program might have a different Print GUI.</p>\n\n<pre><code># Convert the current Safari window to a PDF\n# by Sebastain Gallese\n\n# props to the following for helping me get frontmost window\n# http://stackoverflow.com/questions/480866/get-the-title-of-the-current-active-window- document-in-mac-os-x\n\nglobal window_name\n\n# This script works with Safari, you might have\n# to tweak it to work with other applications \nset myApplication to \"Safari\"\n\n# You can name the PDF whatever you want\n# Just make sure to delete it or move it or rename it\n# Before running the script again\nset myPDFName to \"mynewpdfile\"\n\ntell application myApplication\n activate\n if the (count of windows) is not 0 then\n set window_name to name of front window\n end if\nend tell\n\nset timeoutSeconds to 2.0\nset uiScript to \"keystroke \\\"p\\\" using command down\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"click menu button \\\"PDF\\\" of sheet 1 of window \\\"\" & window_name & \"\\\" of application process \\\"\" & myApplication & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"click menu item 2 of menu 1 of menu button \\\"PDF\\\" of sheet 1 of window \\\"\" & window_name & \"\\\" of application process \\\"\" & myApplication & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"keystroke \\\"\" & myPDFName & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"keystroke return\"\nmy doWithTimeout(uiScript, timeoutSeconds)\n\non doWithTimeout(uiScript, timeoutSeconds)\n set endDate to (current date) + timeoutSeconds\n repeat\n try\n run script \"tell application \\\"System Events\\\"\n\" & uiScript & \"\nend tell\"\n exit repeat\n on error errorMessage\n if ((current date) > endDate) then\n error \"Can not \" & uiScript\n end if\n end try\n end repeat\nend doWithTimeout\n</code></pre>\n"
},
{
"answer_id": 4297984,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at a program called <a href=\"http://bitbucket.org/codepoet/cups-pdf-for-mac-os-x/wiki/Home\" rel=\"nofollow\">CUPS-PDF</a> </p>\n\n<p>It is a virtual printer for OS X which does what the \"Save As PDF\" method does when print through your normal printer except every print job passed through it results in a pdf output.</p>\n\n<p>Once you install it then you could create shell or AppleScripts using the <strong>lp</strong> command. </p>\n\n<p>For example, once the virtual printer is setup you could print test.txt and have it automatically save as a pdf. To do this using an AppleScript you would use the following code:</p>\n\n<pre><code>do shell script \"lp -d CUPS_PDF test.txt\"\n</code></pre>\n\n<p>The CUPS-PDF app saves all output to /Users/Shared/CUPS-PDF. I am not sure if you can change that path but you could retrieve the file in your script and move it.</p>\n\n<p>There are a few caveats though. </p>\n\n<p>First, the <strong>lp</strong> command cannot print .doc files. I think there are some other third party apps which will allow you to do this though. </p>\n\n<p>Second, the CUPS-PDF app shows in the Printer pane of System Preferences as having the hyphen in its name but CUPS shows the queue name as having an underscore. So, on the command line you need to refer to the CUPS queue name which is CUPS_PDF with an underscore.</p>\n\n<p>Even if you don't find it very useful to build a script via the <strong>lp</strong> command\nand still want to involve GUI scripting then having a virtual printer should save you some steps.</p>\n"
},
{
"answer_id": 4430008,
"author": "mcgrailm",
"author_id": 234670,
"author_profile": "https://Stackoverflow.com/users/234670",
"pm_score": 1,
"selected": false,
"text": "<p>you could use cups like this</p>\n\n<pre><code> on open afile\n set filename to name of (info for afile)\n tell application \"Finder\"\n set filepath to (container of (afile as alias)) as alias\n end tell\n set filepath to quoted form of POSIX path of filepath\n set tid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to \".\"\n set filename to text item 1 of filename\n set AppleScript's text item delimiters to tid\n set afile to quoted form of POSIX path of afile\n do shell script \"cupsfilter \" & afile & \" > \" & filepath & filename & \".pdf\"\n end open\n</code></pre>\n"
},
{
"answer_id": 11575976,
"author": "PH.",
"author_id": 825624,
"author_profile": "https://Stackoverflow.com/users/825624",
"pm_score": 1,
"selected": false,
"text": "<p>I have created an alias in bash for this:</p>\n\n<pre><code>convert2pdf() {\n /System/Library/Printers/Libraries/convert -f \"$1\" -o \"$2\" -j \"application/pdf\"\n}\n</code></pre>\n"
},
{
"answer_id": 71097317,
"author": "Daryl Hansen",
"author_id": 4466755,
"author_profile": "https://Stackoverflow.com/users/4466755",
"pm_score": 0,
"selected": false,
"text": "<p><code>"/System/Library/Printers/Libraries/./convert" </code>\nhas been removed in later version of MacOS.</p>\n<p>You can use sips now. AppleScript example:\ndo shell script: <code>sips -s format pdf Filename.jpg --out Filename.pdf</code></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35958/"
] |
I'm working on a project for OSX where the user can pick a collection of documents (from any application) which I need to generate PDF's from. The standard Macintosh Print dialog has a PDF button which has a number of PDF-related commands including "Save as PDF...". However, I need to generate the PDF file without requiring user interactions. I ideally want this to work with any type of document.
Here's the options I've explored so far:
* Automator actions. There's a PDF library for Automator but it provides actions for working with PDF files, not generating them. There's a Finder action for printing any file but only to a real printer.
* AppleScript. Some applications have the ability to generate PDF files (for instance, if you send 'save doc in "test.pdf"' to Pages it will generate a PDF (but this only works for Pages - I need support for any type of document).
* Custom Printer. I could create a virtual printer driver and then use the automator action but I don't like the idea of confusing the user with an extra printer in the print list.
My hope is that there's some way to interact with the active application as if the user was carrying out the following steps:
1. Do Cmd-P (opens the print dialog)
2. Click the "PDF" button
3. Select "Save as PDF..." (second item in menu)
4. Type in filename in save dialog
5. Click "Save"
If that's the best approach (is it?) then the real problem is: how do I send UI Events to an external application (keystrokes, mouse events, menu selections) ?
**Update:** Just to clarify one point: the documents I need to convert to PDF are documents that are created by *other applications*. For example, the user might pick a Word document or a Numbers spreadsheet or an OmniGraffle drawing or a Web Page. The common denominator is that each of these documents has an associated application and that application knows how to print it (and OSX knows how to render print output to a PDF file).
So, the samples at Cocoa Dev Central don't help because they're about generating a PDF from *my application*.
|
I think you could use applescript to open a document and then use [applescript UI scripting](https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AutomatetheUserInterface.html) to invoke print menu.
For example :
```
tell application "System Events"
tell window of process "Safari"
set foremost to true
keystroke "p" using {command down}
delay 3
click menu button "PDF" of sheet 2
click menu item "Save as PDF…" of menu 1 of menu button "PDF" of sheet 2
keystroke "my_test.file"
keystroke return
delay 10
end tell
end tell
```
|
276,382 |
<p>In my app users need to be able to enter numeric values with decimal places. The iPhone doesn't provides a keyboard that's specific for this purpose - only a number pad and a keyboard with numbers and symbols.</p>
<p>Is there an easy way to use the latter and prevent any non-numeric input from being entered without having to regex the final result?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 276437,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on the specific application, providing a slider that the user can select a position from might be a better choice on the iphone. Then no digits need to be entered at all.</p>\n"
},
{
"answer_id": 278076,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to use a slider (as suggested by Martin v. Löwis) or a UIPickerView with a separate wheel for each of the digits.</p>\n"
},
{
"answer_id": 279242,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted to do exactly the same thing, except with currencies rather than straight decimal values. </p>\n\n<p>I ended up creating a custom view which contains a UITextField and a UILabel. The label covers the text field, but the text field still receives touches. I use the UITextFieldTextDidChange notification to observe changes in the text field (and I used a NSNumberFormatter to turn the resulting number into a formatted currency value) to update the label.</p>\n\n<p>To disable the loupe that allows the user to reposition the insertion point, you'll need to use a custom UITextField subclass and override touchesBegan:withEvent: and set it to do nothing.</p>\n\n<p>My solution might be different from what you need because the decimal point is always fixed -- I use the system's currency setting to determine how many there digits ought to be after the decimal point. However, the numeric keypad doesn't have a decimal point on it. And you can't add any buttons to the keyboard (which is especially aggravating because there's a blank button in the lower-left corner of the keyboard that would be perfect for a decimal point!) So I don't have a solution for that, unfortunately.</p>\n"
},
{
"answer_id": 321605,
"author": "shek",
"author_id": 40618,
"author_profile": "https://Stackoverflow.com/users/40618",
"pm_score": 7,
"selected": true,
"text": "<p>A more elegant solution happens to also be the simplest.</p>\n\n<p><em>You don't need a decimal separator key</em></p>\n\n<p>Why? Because you can simply infer it from the user's input. For instance, in the US locale when you what to enter in $1.23, you start by entering the numbers 1-2-3 (in that order). In the system, as each character is entered, this would be recognized as:</p>\n\n<ul>\n<li>user enters 1: $0.01</li>\n<li>user enters 2: $0.12</li>\n<li>user enters 3: $1.23</li>\n</ul>\n\n<p>Notice how we inferred the decimal separator based on the user's input. Now, if the user wants to enter in $1.00, they would simply enter the numbers 1-0-0.</p>\n\n<p>In order for your code to handle currencies of a different locale, you need to get the maximum fraction digits of the currency. This can be done with the following code snippet:</p>\n\n<pre><code>NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];\n[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\nint currencyScale = [currencyFormatter maximumFractionDigits];\n</code></pre>\n\n<p>For example, the Japanese yen has a maximum fraction digit of 0. So, when dealing with yen input, there is no decimal separator and thus no need to even worry about fractional amounts.</p>\n\n<p>This approach to the problem allows you to use the stock numeric input keypad provided by Apple without the headaches of custom keypads, regex validation, etc.</p>\n"
},
{
"answer_id": 2636699,
"author": "Mike Weller",
"author_id": 49658,
"author_profile": "https://Stackoverflow.com/users/49658",
"pm_score": 4,
"selected": false,
"text": "<p>Here is an example for the solution suggested in the accepted answer. This doesn't handle other currencies or anything - in my case I only needed support for dollars, no matter what the locale/currency so this was OK for me:</p>\n\n<pre><code>-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range\n replacementString:(NSString *)string {\n\n double currentValue = [textField.text doubleValue];\n //Replace line above with this\n //double currentValue = [[textField text] substringFromIndex:1] doubleValue];\n double cents = round(currentValue * 100.0f);\n\n if ([string length]) {\n for (size_t i = 0; i < [string length]; i++) {\n unichar c = [string characterAtIndex:i];\n if (isnumber(c)) {\n cents *= 10;\n cents += c - '0'; \n } \n }\n } else {\n // back Space\n cents = floor(cents / 10);\n }\n\n textField.text = [NSString stringWithFormat:@\"%.2f\", cents / 100.0f];\n //Add this line\n //[textField setText:[NSString stringWithFormat:@\"$%@\",[textField text]]];\n return NO;\n}\n</code></pre>\n\n<p>The rounds and floors are important a) because of the floating-point representation sometimes losing .00001 or whatever and b) the format string rounding up any precision we deleted in the backspace part.</p>\n"
},
{
"answer_id": 2809774,
"author": "Richard",
"author_id": 338140,
"author_profile": "https://Stackoverflow.com/users/338140",
"pm_score": 2,
"selected": false,
"text": "<p>I built a custom Number pad view controller with decimal point... check it out:</p>\n\n<p><a href=\"http://sites.google.com/site/psychopupnet/iphone-sdk/tenkeypadcustom10-keypadwithdecimal\" rel=\"nofollow noreferrer\">http://sites.google.com/site/psychopupnet/iphone-sdk/tenkeypadcustom10-keypadwithdecimal</a></p>\n"
},
{
"answer_id": 4143469,
"author": "Screwtape",
"author_id": 503061,
"author_profile": "https://Stackoverflow.com/users/503061",
"pm_score": 1,
"selected": false,
"text": "<p>As of iOS4.1, there is a new keyboard type UIKeyboardTypeNumberPad, but unfortunately, as of yet it doesn't seem to appear in the Interface Builder pick list.</p>\n"
},
{
"answer_id": 4924522,
"author": "Daniel Thorpe",
"author_id": 197626,
"author_profile": "https://Stackoverflow.com/users/197626",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how to do it without using floats, round() or ceil() in a currency agnostic manner.</p>\n\n<p>In you view controller, set up the following instance variables (with associated @property statements if that's your bag):</p>\n\n<pre><code>@interface MyViewController : UIViewController <UITextFieldDelegate> {\n@private\n UITextField *firstResponder;\n NSNumberFormatter *formatter;\n NSInteger currencyScale;\n NSString *enteredDigits;\n}\n\n@property (nonatomic, readwrite, assign) UITextField *firstResponder;\n@property (nonatomic, readwrite, retain) NSNumberFormatter *formatter;\n@property (nonatomic, readwrite, retain) NSString *enteredDigits;\n\n@end\n</code></pre>\n\n<p>and your viewDidLoad method should contain the following:</p>\n\n<pre><code>- (void)viewDidLoad {\n [super viewDidLoad];\n\n NSNumberFormatter *aFormatter = [[NSNumberFormatter alloc] init];\n [aFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\n currencyScale = -1 * [aFormatter maximumFractionDigits];\n self.formatter = aFormatter;\n [aFormatter release];\n}\n</code></pre>\n\n<p>Then implement your UITextFieldDelegate methods as follows:</p>\n\n<pre><code>#pragma mark -\n#pragma mark UITextFieldDelegate methods\n\n- (void)textFieldDidBeginEditing:(UITextField *)textField {\n // Keep a pointer to the field, so we can resign it from a toolbar\n self.firstResponder = textField;\n self.enteredDigits = @\"\";\n}\n\n- (void)textFieldDidEndEditing:(UITextField *)textField {\n if ([self.enteredDigits length] > 0) {\n // Get the amount\n NSDecimalNumber *result = [[NSDecimalNumber decimalNumberWithString:self.enteredDigits] decimalNumberByMultiplyingByPowerOf10:currencyScale];\n NSLog(@\"result: %@\", result);\n }\n}\n\n- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {\n\n // Check the length of the string\n if ([string length]) {\n self.enteredDigits = [self.enteredDigits stringByAppendingFormat:@\"%d\", [string integerValue]];\n } else {\n // This is a backspace\n NSUInteger len = [self.enteredDigits length];\n if (len > 1) {\n self.enteredDigits = [self.enteredDigits substringWithRange:NSMakeRange(0, len - 1)];\n } else {\n self.enteredDigits = @\"\";\n }\n }\n\n NSDecimalNumber *decimal = nil;\n\n if ( ![self.enteredDigits isEqualToString:@\"\"]) {\n decimal = [[NSDecimalNumber decimalNumberWithString:self.enteredDigits] decimalNumberByMultiplyingByPowerOf10:currencyScale];\n } else {\n decimal = [NSDecimalNumber zero];\n }\n\n // Replace the text with the localized decimal number\n textField.text = [self.formatter stringFromNumber:decimal];\n\n return NO; \n}\n</code></pre>\n\n<p>Only tested this with pounds and pence, but it should work with Japanese Yen too. If you want to format decimals for non-currency purposes, then just read the documentation on <a href=\"http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html\" rel=\"nofollow\" title=\"NSNumberFormatter\">NSNumberFormatter</a> and set whatever format/maximumFractionDigits you want.</p>\n"
},
{
"answer_id": 4983084,
"author": "Zebs",
"author_id": 382489,
"author_profile": "https://Stackoverflow.com/users/382489",
"pm_score": 6,
"selected": false,
"text": "<p>I think it would be good to point out that as of iOS 4.1 you can use the new <code>UIKeyboardTypeDecimalPad</code>.</p>\n\n<p>So now you just have to:</p>\n\n<pre><code>myTextField.keyboardType=UIKeyboardTypeDecimalPad;\n</code></pre>\n"
},
{
"answer_id": 32772338,
"author": "ccwasden",
"author_id": 431271,
"author_profile": "https://Stackoverflow.com/users/431271",
"pm_score": 0,
"selected": false,
"text": "<p>A Swift 2 implementation of Mike Weller's post, also only USD:</p>\n\n<pre><code> func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {\n guard let str = textField.text else {\n textField.text = \"0.00\"\n return false\n }\n\n let value = (str as NSString).doubleValue\n\n var cents = round(value * 100)\n if string.characters.count > 0 {\n for c in string.characters {\n if let num = Int(String(c)) {\n cents *= 10\n cents += Double(num)\n }\n }\n }\n else {\n cents = floor(cents / 10)\n }\n\n textField.text = NSString(format: \"%.2f\", cents/100) as String\n\n return false\n}\n</code></pre>\n"
},
{
"answer_id": 35424397,
"author": "Stunner",
"author_id": 347339,
"author_profile": "https://Stackoverflow.com/users/347339",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://github.com/Stunner/STAControls/blob/master/STAControls/STAControls/TextField/STATextField.h\" rel=\"nofollow\">STATextField</a> and set currencyRepresentation to YES which:</p>\n\n<blockquote>\n <p>Ensures no more than one decimal point is entered and that no more than 2 digits are entered to the right of said decimal point.</p>\n</blockquote>\n\n<p>There's also <a href=\"https://github.com/Stunner/STAControls/blob/master/STAControls/STAControls/TextField/STAATMTextField.h\" rel=\"nofollow\">STAATMTextField</a> which supports currency mode <em>and</em> ATM text entry by default:</p>\n\n<blockquote>\n <p>Provides a text field that mimics ATM machine input behavior.</p>\n</blockquote>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] |
In my app users need to be able to enter numeric values with decimal places. The iPhone doesn't provides a keyboard that's specific for this purpose - only a number pad and a keyboard with numbers and symbols.
Is there an easy way to use the latter and prevent any non-numeric input from being entered without having to regex the final result?
Thanks!
|
A more elegant solution happens to also be the simplest.
*You don't need a decimal separator key*
Why? Because you can simply infer it from the user's input. For instance, in the US locale when you what to enter in $1.23, you start by entering the numbers 1-2-3 (in that order). In the system, as each character is entered, this would be recognized as:
* user enters 1: $0.01
* user enters 2: $0.12
* user enters 3: $1.23
Notice how we inferred the decimal separator based on the user's input. Now, if the user wants to enter in $1.00, they would simply enter the numbers 1-0-0.
In order for your code to handle currencies of a different locale, you need to get the maximum fraction digits of the currency. This can be done with the following code snippet:
```
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
int currencyScale = [currencyFormatter maximumFractionDigits];
```
For example, the Japanese yen has a maximum fraction digit of 0. So, when dealing with yen input, there is no decimal separator and thus no need to even worry about fractional amounts.
This approach to the problem allows you to use the stock numeric input keypad provided by Apple without the headaches of custom keypads, regex validation, etc.
|
276,383 |
<p>I have a Dictionary that when I add multiple values to it, the items that were entered before take the values of the item added. I am using the .Net 3.5 Here is the code:</p>
<pre><code>public static Dictionary<string, Neighborhoods> Families()
{
if (File.Exists(calculatePath() + "Family.txt")){}
else {File.Create(calculatePath() + "Family.txt").Close();}
string[] inp = File.ReadAllLines(calculatePath() + "Family.txt");
Neighborhoods temp = new Neighborhoods();
Dictionary<string, Neighborhoods> All_Families = new Dictionary<string, Neighborhoods>();
string currentphase = null;
foreach (string s in inp)
{
switch (s)
{
case "!<Start Family>!": temp = new Neighborhoods();
break;
case "<Family Name>": currentphase = "<Family Name>";
break;
case "<End Family Name>": currentphase = null;
break;
case "<Neighbour Enabled>True": temp.Neighbourhood_Enabled1 = true;
currentphase = "<Neighbour Enabled>True";
break;
case "<Neighbour Enabled>False": temp.Neighbourhood_Enabled1 = false;
temp.Neighbourhood_Input1 = null;
break;
case "<University Enabled>True": temp.University_Enabled1 = true;
currentphase = "<University Enabled>True";
break;
case "<University Enabled>False": temp.University_Enabled1 = false;
temp.University_Input1 = null;
currentphase = null;
break;
case "<Downtown Enabled>True": temp.Downtown_Enabled1 = true;
currentphase = "<Downtown Enabled>True";
break;
case "<Downtown Enabled>False": temp.Downtown_Enabled1 = false;
temp.Downtown_Input1 = null;
currentphase = null;
break;
case "!<End Family>!": All_Families.Add(temp.Name, temp);
break;
default: if (currentphase == "<Family Name>") temp.Name = s;
if (currentphase == "<Neighbour Enabled>True") temp.Neighbourhood_Input1 = s;
if (currentphase == "<University Enabled>True") temp.University_Input1 = s;
if (currentphase == "<Downtown Enabled>True") temp.Downtown_Input1 = s;
break;
}
}
return All_Families;
}
</code></pre>
<p>How can I make it so that when I add new keys and values, the old keys keep their original value</p>
<hr>
<p>Sample data:</p>
<pre><code>!<Start Family>!
Family Name>
qwe
<End Family Name>
<Neighbour Enabled>True
qwe
<University Enabled>True
we
<Downtown Enabled>True
qwe
!<End Family>!
!<Start Family>!
<Family Name>
123
<End Family Name>
<Neighbour Enabled>True
123
<University Enabled>True
123
<Downtown Enabled>True
123
!<End Family>!
</code></pre>
<hr>
<p>Here is the nieghbourhoods class for reference. I will try the xml methods but it wont be finished quickly, I'm still learning this stuff.</p>
<pre><code>class Neighborhoods
{
public Neighborhoods()
{
name = "";
Neighbourhood_Enabled = false;
Neighbourhood_Input = "";
University_Enabled = false;
University_Input = "";
Downtown_Enabled = false;
Downtown_Input = "";
}
static string name;
public string Name
{
get { return Neighborhoods.name; }
set { Neighborhoods.name = value; }
}
static bool Neighbourhood_Enabled;
public bool Neighbourhood_Enabled1
{
get { return Neighborhoods.Neighbourhood_Enabled; }
set { Neighborhoods.Neighbourhood_Enabled = value; }
}
static string Neighbourhood_Input;
public string Neighbourhood_Input1
{
get { return Neighborhoods.Neighbourhood_Input; }
set { Neighborhoods.Neighbourhood_Input = value; }
}
static bool University_Enabled;
public bool University_Enabled1
{
get { return Neighborhoods.University_Enabled; }
set { Neighborhoods.University_Enabled = value; }
}
static string University_Input;
public string University_Input1
{
get { return Neighborhoods.University_Input; }
set { Neighborhoods.University_Input = value; }
}
static bool Downtown_Enabled;
public bool Downtown_Enabled1
{
get { return Neighborhoods.Downtown_Enabled; }
set { Neighborhoods.Downtown_Enabled = value; }
}
static string Downtown_Input;
public string Downtown_Input1
{
get { return Neighborhoods.Downtown_Input; }
set { Neighborhoods.Downtown_Input = value; }
}
}
</code></pre>
|
[
{
"answer_id": 276411,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>From the looks of it, you want to parse a file, and load it into a Dictionary collection.</p>\n\n<p>A couple critiques...Use XML for one, and get rid of the insane parser:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<families>\n <family>\n <name>Smith</name>\n <neighborhood>true</neighborhood>\n <university>false</university>\n <downtown>false</downtown>\n </family>\n <family>\n <name>Jones</name>\n <neighborhood>false</neighborhood>\n <university>true</university>\n <downtown>false</downtown>\n </family>\n</families>\n</code></pre>\n\n<p>Now, we can use the built in System.XML namespace to parse this far easier.</p>\n\n<p>For example, I just rewrote your code as:</p>\n\n<pre><code> Dictionary<String, Neighborhood> families = new Dictionary<string, Neighborhood>();\n\n XmlDocument doc = new XmlDocument();\n doc.Load(\"family.xml\");\n\n foreach (XmlNode familyNode in doc.SelectNodes(\"//family\"))\n {\n Neighborhood n = new Neighborhood();\n n.Name = familyNode.SelectSingleNode(\"name\").InnerText;\n n.InNeighborhood = Boolean.Parse(familyNode.SelectSingleNode(\"neighborhood\").InnerText);\n n.InDowntown = Boolean.Parse(familyNode.SelectSingleNode(\"downtown\").InnerText);\n n.InUniversity = Boolean.Parse(familyNode.SelectSingleNode(\"university\").InnerText);\n\n families.Add(n.Name,n);\n }\n</code></pre>\n\n<p>And it works just fine, though I didn't add any error handling to my code to keep it brief.</p>\n"
},
{
"answer_id": 276455,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>With the sample data you've given and the code you've given, it works okay using a <code>Neighborhoods</code> class like this:</p>\n\n<pre><code>public class Neighborhoods\n{\n public string Name { get; set; }\n public string Neighbourhood_Input1 { get; set; }\n public string University_Input1 { get; set; }\n public string Downtown_Input1 { get; set; }\n public bool Neighbourhood_Enabled1 { get; set; }\n public bool University_Enabled1 { get; set; }\n public bool Downtown_Enabled1 { get; set; }\n}\n</code></pre>\n\n<p>My test is to run this code:</p>\n\n<pre><code>static void Main()\n{\n var families = Families();\n\n foreach (var family in x.Values)\n {\n Console.WriteLine(y.Name);\n }\n}\n</code></pre>\n\n<p>That prints out \"qwe\" and \"123\" - showing that there are two different objects involved.</p>\n\n<p>However, we haven't seen the real <code>Neighborhoods</code> class yet. I don't suppose it's using static fields (but still instance properties) is it? That would certainly explain the behaviour you're seeing.</p>\n\n<p>EDIT: Yup, now you've shown us the Neighborhoods code it makes sense. Those fields are meant to be relevant for each <em>instance</em>, not just the type itself - so they shouldn't be static.</p>\n\n<p>To show this is nothing to do with the parser, try this:</p>\n\n<pre><code>Neighborhoods first = new Neighborhoods();\nNeighborhoods second = new Neighborhoods();\n\nfirst.Name = \"First\";\nConsole.WriteLine(second.Name);\n</code></pre>\n\n<p>You'll see it prints out \"First\" - which is clearly not what you want!</p>\n\n<p>Unfortunately I don't have a good page about what \"static\" means, but I suggest you look it up in whatever C# books you have.</p>\n"
},
{
"answer_id": 276461,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Like Jon Skeet noted, you can't use static like that.</p>\n\n<p>replace static with private and all should be well.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35984/"
] |
I have a Dictionary that when I add multiple values to it, the items that were entered before take the values of the item added. I am using the .Net 3.5 Here is the code:
```
public static Dictionary<string, Neighborhoods> Families()
{
if (File.Exists(calculatePath() + "Family.txt")){}
else {File.Create(calculatePath() + "Family.txt").Close();}
string[] inp = File.ReadAllLines(calculatePath() + "Family.txt");
Neighborhoods temp = new Neighborhoods();
Dictionary<string, Neighborhoods> All_Families = new Dictionary<string, Neighborhoods>();
string currentphase = null;
foreach (string s in inp)
{
switch (s)
{
case "!<Start Family>!": temp = new Neighborhoods();
break;
case "<Family Name>": currentphase = "<Family Name>";
break;
case "<End Family Name>": currentphase = null;
break;
case "<Neighbour Enabled>True": temp.Neighbourhood_Enabled1 = true;
currentphase = "<Neighbour Enabled>True";
break;
case "<Neighbour Enabled>False": temp.Neighbourhood_Enabled1 = false;
temp.Neighbourhood_Input1 = null;
break;
case "<University Enabled>True": temp.University_Enabled1 = true;
currentphase = "<University Enabled>True";
break;
case "<University Enabled>False": temp.University_Enabled1 = false;
temp.University_Input1 = null;
currentphase = null;
break;
case "<Downtown Enabled>True": temp.Downtown_Enabled1 = true;
currentphase = "<Downtown Enabled>True";
break;
case "<Downtown Enabled>False": temp.Downtown_Enabled1 = false;
temp.Downtown_Input1 = null;
currentphase = null;
break;
case "!<End Family>!": All_Families.Add(temp.Name, temp);
break;
default: if (currentphase == "<Family Name>") temp.Name = s;
if (currentphase == "<Neighbour Enabled>True") temp.Neighbourhood_Input1 = s;
if (currentphase == "<University Enabled>True") temp.University_Input1 = s;
if (currentphase == "<Downtown Enabled>True") temp.Downtown_Input1 = s;
break;
}
}
return All_Families;
}
```
How can I make it so that when I add new keys and values, the old keys keep their original value
---
Sample data:
```
!<Start Family>!
Family Name>
qwe
<End Family Name>
<Neighbour Enabled>True
qwe
<University Enabled>True
we
<Downtown Enabled>True
qwe
!<End Family>!
!<Start Family>!
<Family Name>
123
<End Family Name>
<Neighbour Enabled>True
123
<University Enabled>True
123
<Downtown Enabled>True
123
!<End Family>!
```
---
Here is the nieghbourhoods class for reference. I will try the xml methods but it wont be finished quickly, I'm still learning this stuff.
```
class Neighborhoods
{
public Neighborhoods()
{
name = "";
Neighbourhood_Enabled = false;
Neighbourhood_Input = "";
University_Enabled = false;
University_Input = "";
Downtown_Enabled = false;
Downtown_Input = "";
}
static string name;
public string Name
{
get { return Neighborhoods.name; }
set { Neighborhoods.name = value; }
}
static bool Neighbourhood_Enabled;
public bool Neighbourhood_Enabled1
{
get { return Neighborhoods.Neighbourhood_Enabled; }
set { Neighborhoods.Neighbourhood_Enabled = value; }
}
static string Neighbourhood_Input;
public string Neighbourhood_Input1
{
get { return Neighborhoods.Neighbourhood_Input; }
set { Neighborhoods.Neighbourhood_Input = value; }
}
static bool University_Enabled;
public bool University_Enabled1
{
get { return Neighborhoods.University_Enabled; }
set { Neighborhoods.University_Enabled = value; }
}
static string University_Input;
public string University_Input1
{
get { return Neighborhoods.University_Input; }
set { Neighborhoods.University_Input = value; }
}
static bool Downtown_Enabled;
public bool Downtown_Enabled1
{
get { return Neighborhoods.Downtown_Enabled; }
set { Neighborhoods.Downtown_Enabled = value; }
}
static string Downtown_Input;
public string Downtown_Input1
{
get { return Neighborhoods.Downtown_Input; }
set { Neighborhoods.Downtown_Input = value; }
}
}
```
|
With the sample data you've given and the code you've given, it works okay using a `Neighborhoods` class like this:
```
public class Neighborhoods
{
public string Name { get; set; }
public string Neighbourhood_Input1 { get; set; }
public string University_Input1 { get; set; }
public string Downtown_Input1 { get; set; }
public bool Neighbourhood_Enabled1 { get; set; }
public bool University_Enabled1 { get; set; }
public bool Downtown_Enabled1 { get; set; }
}
```
My test is to run this code:
```
static void Main()
{
var families = Families();
foreach (var family in x.Values)
{
Console.WriteLine(y.Name);
}
}
```
That prints out "qwe" and "123" - showing that there are two different objects involved.
However, we haven't seen the real `Neighborhoods` class yet. I don't suppose it's using static fields (but still instance properties) is it? That would certainly explain the behaviour you're seeing.
EDIT: Yup, now you've shown us the Neighborhoods code it makes sense. Those fields are meant to be relevant for each *instance*, not just the type itself - so they shouldn't be static.
To show this is nothing to do with the parser, try this:
```
Neighborhoods first = new Neighborhoods();
Neighborhoods second = new Neighborhoods();
first.Name = "First";
Console.WriteLine(second.Name);
```
You'll see it prints out "First" - which is clearly not what you want!
Unfortunately I don't have a good page about what "static" means, but I suggest you look it up in whatever C# books you have.
|
276,443 |
<p>I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from <a href="http://site.example.com/" rel="noreferrer">http://site.example.com/</a> to <a href="http://example.com/site/" rel="noreferrer">http://example.com/site/</a> without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, like css files, images and so on. </p>
<p>For example, let's assume that the view for the action <code>index</code> of the controller <code>welcome</code> contains the image <code>img/banner.jpg</code>. If the page is requested with the url <a href="http://site.example.com/welcome" rel="noreferrer">http://site.example.com/welcome</a>, the browser will request the image as <a href="http://site.example.com/img/banner.jpg" rel="noreferrer">http://site.example.com/img/banner.jpg</a>, which is perfectly fine. But if the page is requested with the url <a href="http://site.example.com/welcome/index" rel="noreferrer">http://site.example.com/welcome/index</a>, the browser will think that <code>welcome</code> is a directory and will try to fetch the image as <a href="http://site.example.com/welcome/img/banner.jpg" rel="noreferrer">http://site.example.com/welcome/img/banner.jpg</a>, which is obviously wrong.</p>
<p>I've already considered some options, but they all seem imperfect to me:</p>
<ul>
<li><p>Use url rewriting to redirect requests from (<strong>*.css</strong>|<strong>*.js</strong>|...) or (<strong>css/*</strong>|<strong>js/*</strong>|...) to the right path. </p>
<p><em>Problems</em>: Every extension would have to be named in the rewrite rules. If someone would add a new filetype (e.g. an mp3 file), it wouldn't be rewritten.</p></li>
<li><p>Prepend the base path to each relative path with a php function. For example:<br>
<code><img src="<?php echo url::base(); ?>img/banner.jpg" /></code> </p>
<p><em>Problems</em>: Looks messy; <strong>css</strong>- and <strong>js</strong>-files containing paths would have to be processed by PHP.</p></li>
</ul>
<p>So, how do you keep a website directory independent? Is there a better/cleaner way than the ones I came up with?</p>
|
[
{
"answer_id": 276444,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 4,
"selected": true,
"text": "<p>You could put in the head</p>\n\n<pre><code><base href=\"<?php echo url::base(); ?>\" /> \n</code></pre>\n\n<p>This will mean the browser will request any non-absolute URLs relative to that path. <strike>However I am not sure how this would affect URLs embedded in CSS files etc.</strike> This does not affect paths defined in CSS files. (thanks mooware)</p>\n"
},
{
"answer_id": 276502,
"author": "Anton Babushkin",
"author_id": 35720,
"author_profile": "https://Stackoverflow.com/users/35720",
"pm_score": 1,
"selected": false,
"text": "<p>tomhaigh has a good point, and would be worthwhile to investigate it further.</p>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-au/library/ms535191(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a>, the <a href=\"http://msdn.microsoft.com/en-au/library/ms535191(VS.85).aspx\" rel=\"nofollow noreferrer\">base</a> tag works for all external sources, including style sheets, images, etc.</p>\n"
},
{
"answer_id": 276583,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps I'm missing something, but can't you just do what I (and I thought everybody else) do/es? Namely put all your images, css, javascripts, etc in a common directory i.e.:</p>\n\n<pre><code>/inc/images/\n/inc/css/\n/inc/javascript/\netc\n</code></pre>\n\n<p>And then reference them with base-relative URLs, i.e.:</p>\n\n<pre><code><img src=\"/inc/images/foo.jpg\" />\netc\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 277860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The <code><base></code> thing will work but you need to remember it's going to affect your <code><a></code> tags too. Consider this example.:</p>\n\n<pre><code><!-- this page is http://oursite.com/index.html -->\n<html>\n <head>\n <base href=\"http://static.oursite.com/\" />\n </head>\n <body>\n <img src=\"logo.gif\" alt=\"this is http://static.oursite.com/logo.gif\" />\n <a href=\"/login\">this links to http://static.oursite.com/login which is not what we wanted. we wanted http://oursite.com/login</a>\n </body>\n</html>\n</code></pre>\n\n<p>If you use a PHP function call for creating your links, that won't be a problem as you can just make sure it spits out absolute URL. But if you (or your designers) hand-code the <code><a></code> tags then you're stuck with the same problem again, just now with <code><a></code> instead of <code><img></code>.</p>\n\n<p>EDIT: I should add the above paragraph is assuming you serve images from a different host name like we do. If you don't then obviously that won't be a problem.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35951/"
] |
I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from <http://site.example.com/> to <http://example.com/site/> without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, like css files, images and so on.
For example, let's assume that the view for the action `index` of the controller `welcome` contains the image `img/banner.jpg`. If the page is requested with the url <http://site.example.com/welcome>, the browser will request the image as <http://site.example.com/img/banner.jpg>, which is perfectly fine. But if the page is requested with the url <http://site.example.com/welcome/index>, the browser will think that `welcome` is a directory and will try to fetch the image as <http://site.example.com/welcome/img/banner.jpg>, which is obviously wrong.
I've already considered some options, but they all seem imperfect to me:
* Use url rewriting to redirect requests from (**\*.css**|**\*.js**|...) or (**css/\***|**js/\***|...) to the right path.
*Problems*: Every extension would have to be named in the rewrite rules. If someone would add a new filetype (e.g. an mp3 file), it wouldn't be rewritten.
* Prepend the base path to each relative path with a php function. For example:
`<img src="<?php echo url::base(); ?>img/banner.jpg" />`
*Problems*: Looks messy; **css**- and **js**-files containing paths would have to be processed by PHP.
So, how do you keep a website directory independent? Is there a better/cleaner way than the ones I came up with?
|
You could put in the head
```
<base href="<?php echo url::base(); ?>" />
```
This will mean the browser will request any non-absolute URLs relative to that path. However I am not sure how this would affect URLs embedded in CSS files etc. This does not affect paths defined in CSS files. (thanks mooware)
|
276,479 |
<p>I saw a potential answer here but that was for YYYY-MM-DD: <a href="http://paulschreiber.com/blog/2007/03/02/javascript-date-validation/" rel="noreferrer">JavaScript date validation</a></p>
<p>I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:</p>
<pre><code>String.prototype.isValidDate = function()
{
var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
return ((composedDate.getMonth() == (matches[1] - 1)) &&
(composedDate.getDate() == matches[2]) &&
(composedDate.getFullYear() == matches[3]));
}
</code></pre>
<p>How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 276488,
"author": "Kevin Gorski",
"author_id": 35806,
"author_profile": "https://Stackoverflow.com/users/35806",
"pm_score": 1,
"selected": false,
"text": "<p>You can simplify it somewhat by changing the first two lines of the function to this:</p>\n\n<pre><code>var matches = this.match(/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/);\n</code></pre>\n\n<p>Or, just change the parameter to the RegExp constructor to be </p>\n\n<pre><code>^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$\n</code></pre>\n"
},
{
"answer_id": 276497,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p>what isn't working about it? here's a tested version:</p>\n<pre><code>String.prototype.isValidDate = function() {\n\n const match = this.match(/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/);\n if (!match || match.length !== 4) {\n return false\n }\n\n const test = new Date(match[3], match[1] - 1, match[2]);\n\n return (\n (test.getMonth() == match[1] - 1) &&\n (test.getDate() == match[2]) &&\n (test.getFullYear() == match[3])\n );\n}\n\nvar date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'\nalert(date.isValidDate() ); // true\n</code></pre>\n"
},
{
"answer_id": 276511,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "<p>I use this regex for validating MM-DD-YYYY:</p>\n\n<pre><code>function isValidDate(subject){\n if (subject.match(/^(?:(0[1-9]|1[012])[\\- \\/.](0[1-9]|[12][0-9]|3[01])[\\- \\/.](19|20)[0-9]{2})$/)){\n return true;\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>It will match only valid months and you can use / - or . as separators.</p>\n"
},
{
"answer_id": 276622,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": false,
"text": "<pre><code>function isValidDate(date)\n{\n var matches = /^(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{4})$/.exec(date);\n if (matches == null) return false;\n var d = matches[2];\n var m = matches[1] - 1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n}\nconsole.log(isValidDate('10-12-1961'));\nconsole.log(isValidDate('12/11/1961'));\nconsole.log(isValidDate('02-11-1961'));\nconsole.log(isValidDate('12/01/1961'));\nconsole.log(isValidDate('13-11-1961'));\nconsole.log(isValidDate('11-31-1961'));\nconsole.log(isValidDate('11-31-1061'));\n</code></pre>\n\n<p>It works. (Tested with Firebug, hence the console.log().)</p>\n"
},
{
"answer_id": 5553207,
"author": "James Moberg",
"author_id": 693068,
"author_profile": "https://Stackoverflow.com/users/693068",
"pm_score": 3,
"selected": false,
"text": "<p>How about validating dates in \"ANY\" date format? I've been using the DateJS library and adding it to existing forms to ensure that I get valid dates & times formatted the way that I want. The user can even enter things like \"now\" and \"tomorrow\" and it will be converted into a valid date.</p>\n\n<p>Here's the dateJS library:\n<a href=\"http://www.datejs.com/\" rel=\"noreferrer\">http://www.datejs.com/</a></p>\n\n<p>and here's a jQuery tip that I wrote:\n<a href=\"http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm\" rel=\"noreferrer\">http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm</a></p>\n"
},
{
"answer_id": 8390325,
"author": "Matthew Carroll",
"author_id": 227070,
"author_profile": "https://Stackoverflow.com/users/227070",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function isValidDate(date) {\n var valid = true;\n\n date = date.replace('/-/g', '');\n\n var month = parseInt(date.substring(0, 2),10);\n var day = parseInt(date.substring(2, 4),10);\n var year = parseInt(date.substring(4, 8),10);\n\n if(isNaN(month) || isNaN(day) || isNaN(year)) return false;\n\n if((month < 1) || (month > 12)) valid = false;\n else if((day < 1) || (day > 31)) valid = false;\n else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;\n else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;\n else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;\n else if((month == 2) && (day > 28)) valid = false;\n\n return valid;\n}\n</code></pre>\n\n<p>This checks for valid days in each month and for valid leap year days.</p>\n"
},
{
"answer_id": 10582772,
"author": "Jawad",
"author_id": 1393651,
"author_profile": "https://Stackoverflow.com/users/1393651",
"pm_score": 0,
"selected": false,
"text": "<p>pass this function to date with format //10-10-2012 and id of object.</p>\n\n<pre><code>function isValidDateFormat(date, id)\n{\n var todayDate = new Date();\n var matches = /^(\\d{2})[-\\/](\\d{2})[-\\/](\\d{4})$/.exec(date);\n\n if (matches == null)\n {\n if(date != '__-__-____')\n {\n alert('Please enter valid date');\n }\n }\n else\n {\n var day = 31;\n var month = 12;\n var b_date = date.split(\"-\");\n if(b_date[0] <= day)\n {\n if(b_date[1] <= month)\n {\n if(b_date[2] >= 1900 && b_date[2] <= todayDate.getFullYear())\n {\n return true;\n }\n else\n {\n $(\"#\"+id).val('');\n alert('Please enter valid Year'); \n } \n }\n else\n {\n $(\"#\"+id).val('');\n alert('Please enter valid Month'); \n } \n }\n else\n {\n alert('Please enter valid Day');\n $(\"#\"+id).val(''); \n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12570083,
"author": "Srimitha",
"author_id": 1695191,
"author_profile": "https://Stackoverflow.com/users/1695191",
"pm_score": 1,
"selected": false,
"text": "<p>Simple way to solve</p>\n\n<pre><code>var day = document.getElementById(\"DayTextBox\").value;\n\nvar regExp = /^([1-9]|[1][012])\\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;\n\nreturn regExp.test(day);\n</code></pre>\n"
},
{
"answer_id": 13971620,
"author": "Jyotish",
"author_id": 1918694,
"author_profile": "https://Stackoverflow.com/users/1918694",
"pm_score": 0,
"selected": false,
"text": "<p>This is for validating the date string in formate dd.mm.yyyy It is easy to customize it. You just need to adjust the pos1 and pos2 in isValidDate(). </p>\n\n<p>var dtCh= \".\";\n var minYear=1900;</p>\n\n<pre><code>function isInteger(s){\n var i;\n for (i = 0; i < s.length; i++){ \n // Check that current character is number.\n var c = s.charAt(i);\n if (((c < \"0\") || (c > \"9\"))) return false;\n }\n // All characters are numbers.\n return true;\n}\n\nfunction stripCharsInBag(s, bag){\n var i;\n var returnString = \"\";\n // Search through string's characters one by one.\n // If character is not in bag, append to returnString.\n for (i = 0; i < s.length; i++){ \n var c = s.charAt(i);\n if (bag.indexOf(c) == -1) returnString += c;\n }\n return returnString;\n}\n\nfunction daysInFebruary (year){\n // February has 29 days in any year evenly divisible by four,\n // EXCEPT for centurial years which are not also divisible by 400.\n return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );\n}\nfunction DaysArray(n) {\n for (var i = 1; i <= n; i++) {\n this[i] = 31;\n if (i==4 || i==6 || i==9 || i==11) {\n this[i] = 30;\n }\n if (i==2) {\n this[i] = 29;\n }\n } \n return this;\n}\n\nfunction isValidDate(dtStr){\n var daysInMonth = DaysArray(12);\n var pos1=dtStr.indexOf(dtCh);\n var pos2=dtStr.indexOf(dtCh,pos1+1);\n var strDay=dtStr.substring(0,pos1);\n var strMonth=dtStr.substring(pos1+1,pos2);\n var strYear=dtStr.substring(pos2+1);\n strYr=strYear;\n if (strDay.charAt(0)==\"0\" && strDay.length>1) \n strDay=strDay.substring(1);\n if (strMonth.charAt(0)==\"0\" && strMonth.length>1) \n strMonth=strMonth.substring(1);\n for (var i = 1; i <= 3; i++) {\n if (strYr.charAt(0)==\"0\" && strYr.length>1) \n strYr=strYr.substring(1);\n }\n month=parseInt(strMonth);\n day=parseInt(strDay);\n year=parseInt(strYr);\n if (pos1==-1 || pos2==-1){\n alert(\"The date format should be : dd.mm.yyyy\");\n return false;\n }\n if (strMonth.length<1 || month<1 || month>12){\n alert(\"Please enter a valid month\");\n return false;\n }\n if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){\n alert(\"Please enter a valid day\");\n return false;\n }\n if (strYear.length != 4 || year==0 || year<minYear){\n alert(\"Please enter a valid 4 digit year after \"+minYear);\n return false;\n }\n if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){\n alert(\"Please enter a valid date\");\n return false;\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 16033681,
"author": "niraj Verma",
"author_id": 2285845,
"author_profile": "https://Stackoverflow.com/users/2285845",
"pm_score": -1,
"selected": false,
"text": "<pre><code><script language = \"Javascript\">\n// Declaring valid date character, minimum year and maximum year\nvar dtCh= \"/\";\nvar minYear=1900;\nvar maxYear=2100;\n\nfunction isInteger(s){\n var i;\n for (i = 0; i < s.length; i++){ \n // Check that current character is number.\n var c = s.charAt(i);\n if (((c < \"0\") || (c > \"9\"))) return false;\n }\n // All characters are numbers.\n return true;\n}\n\nfunction stripCharsInBag(s, bag){\n var i;\n var returnString = \"\";\n // Search through string's characters one by one.\n // If character is not in bag, append to returnString.\n for (i = 0; i < s.length; i++){ \n var c = s.charAt(i);\n if (bag.indexOf(c) == -1) returnString += c;\n }\n return returnString;\n}\n\nfunction daysInFebruary (year){\n // February has 29 days in any year evenly divisible by four,\n // EXCEPT for centurial years which are not also divisible by 400.\n return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );\n}\nfunction DaysArray(n) {\n for (var i = 1; i <= n; i++) {\n this[i] = 31\n if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}\n if (i==2) {this[i] = 29}\n } \n return this\n}\n\nfunction isDate(dtStr){\n var daysInMonth = DaysArray(12)\n var pos1=dtStr.indexOf(dtCh)\n var pos2=dtStr.indexOf(dtCh,pos1+1)\n var strDay=dtStr.substring(0,pos1)\n var strMonth=dtStr.substring(pos1+1,pos2)\n var strYear=dtStr.substring(pos2+1)\n strYr=strYear\n if (strDay.charAt(0)==\"0\" && strDay.length>1) strDay=strDay.substring(1)\n if (strMonth.charAt(0)==\"0\" && strMonth.length>1) strMonth=strMonth.substring(1)\n for (var i = 1; i <= 3; i++) {\n if (strYr.charAt(0)==\"0\" && strYr.length>1) strYr=strYr.substring(1)\n }\n month=parseInt(strMonth)\n day=parseInt(strDay)\n year=parseInt(strYr)\n if (pos1==-1 || pos2==-1){\n alert(\"The date format should be : dd/mm/yyyy\")\n return false\n }\n if (strMonth.length<1 || month<1 || month>12){\n alert(\"Please enter a valid month\")\n return false\n }\n if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){\n alert(\"Please enter a valid day\")\n return false\n }\n if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){\n alert(\"Please enter a valid 4 digit year between \"+minYear+\" and \"+maxYear)\n return false\n }\n if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){\n alert(\"Please enter a valid date\")\n return false\n }\nreturn true\n}\n\nfunction ValidateForm(){\n var dt=document.frmSample.txtDateenter code here\n if (isDate(dt.value)==false){\n dt.focus()\n return false\n }\n return true\n }\n\n</script>\n</code></pre>\n"
},
{
"answer_id": 19364439,
"author": "José Gabriel González",
"author_id": 2019906,
"author_profile": "https://Stackoverflow.com/users/2019906",
"pm_score": 2,
"selected": false,
"text": "<p>This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.</p>\n\n<pre><code>function isValidDate(date)\n{\n var matches = /^(\\d{2})[-\\/](\\d{2})[-\\/](\\d{4})$/.exec(date);\n if (matches == null) return false;\n var d = matches[1];\n var m = matches[2]-1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n}\nconsole.log(isValidDate('10-12-1961'));\nconsole.log(isValidDate('12/11/1961'));\nconsole.log(isValidDate('02-11-1961'));\nconsole.log(isValidDate('12/01/1961'));\nconsole.log(isValidDate('13-11-1961'));\nconsole.log(isValidDate('11-31-1961'));\nconsole.log(isValidDate('11-31-1061'));\n</code></pre>\n"
},
{
"answer_id": 19775735,
"author": "user2864740",
"author_id": 2864740,
"author_profile": "https://Stackoverflow.com/users/2864740",
"pm_score": 2,
"selected": false,
"text": "<p>I would use <a href=\"http://momentjs.com/\" rel=\"nofollow\">Moment.js</a> for this task. It makes it <em>very easy</em> to parse dates and it also provides support to detect a an invalid date<sup>1</sup> in the correct format. For instance, consider <a href=\"http://jsfiddle.net/ygqgz/\" rel=\"nofollow\">this example</a>:</p>\n\n<pre><code>var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']\n\nmoment('11/28/1981', formats).isValid() // true\nmoment('2-29-2003', formats).isValid() // false (not leap year)\nmoment('2-29-2004', formats).isValid() // true (leap year)\n</code></pre>\n\n<p>First <code>moment(.., formats)</code> is used to parse the input according to the localized format supplied. Then the <code>isValid</code> function is called on the resulting moment object so that we can actually tell if it is a <em>valid</em> date.</p>\n\n<p>This can be used to trivially derive the isValidDate method:</p>\n\n<pre><code>String.prototype.isValidDate = function() {\n var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];\n return moment(\"\" + this, formats).isValid();\n}\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> As I can find scarce little commentary on the matter, I would only use moment.js for dates covered by the <a href=\"http://en.wikipedia.org/wiki/Gregorian_calendar\" rel=\"nofollow\">Gregorian calendar</a>. There may be plugins for other (including historical or scientific) calendars.</p>\n"
},
{
"answer_id": 21839943,
"author": "Adam",
"author_id": 3320907,
"author_profile": "https://Stackoverflow.com/users/3320907",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (document.getElementById('expiryDay').value != test(match(\"/^([0-9]{2})\\/([0-9]{2})$/\"))){\n alert(\"Enter the date in two digit month flowed by two digits year \\n\");\n}\n</code></pre>\n"
},
{
"answer_id": 32240782,
"author": "Mayur Narula",
"author_id": 5268385,
"author_profile": "https://Stackoverflow.com/users/5268385",
"pm_score": 0,
"selected": false,
"text": "<pre><code><!DOCTYPE html> \n<html> \n<head> \n\n<title></title> \n <script>\n function dateCheck(inputText) {\n debugger;\n\n var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$/;\n\n var flag = 1;\n\n if (inputText.value.match(dateFormat)) {\n document.myForm.dateInput.focus();\n\n var inputFormat1 = inputText.value.split('/');\n var inputFormat2 = inputText.value.split('-');\n linputFormat1 = inputFormat1.length;\n linputFormat2 = inputFormat2.length;\n\n if (linputFormat1 > 1) {\n var pdate = inputText.value.split('/');\n }\n else if (linputFormat2 > 1) {\n var pdate = inputText.value.split('-');\n }\n var date = parseInt(pdate[0]);\n var month = parseInt(pdate[1]);\n var year = parseInt(pdate[2]);\n\n var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n if (month == 1 || month > 2) {\n if (date > ListofDays[month - 1]) {\n alert(\"Invalid date format!\");\n return false;\n }\n }\n\n if (month == 2) {\n var leapYear = false;\n\n if ((!(year % 4) && year % 100) || !(year % 400)) {\n leapYear = true;\n\n }\n if ((leapYear == false) && (date >= 29)) {\n alert(\"Invalid date format!\");\n return false;\n }\n if ((leapYear == true) && (date > 29)) {\n alert(\"Invalid date format!\");\n return false;\n }\n }\n if (flag == 1) {\n alert(\"Valid Date\");\n }\n }\n else {\n alert(\"Invalid date format!\");\n document.myForm.dateInput.focus();\n return false;\n }\n }\n function restrictCharacters(evt) {\n\n evt = (evt) ? evt : window.event;\n var charCode = (evt.which) ? evt.which : evt.keyCode;\n if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {\n return true;\n }\n else {\n return false;\n }\n }\n\n\n </script> \n</head>\n\n\n\n<body> \n <div> \n <form name=\"myForm\" action=\"#\"> \n <table>\n <tr>\n <td>Enter Date</td>\n <td><input type=\"text\" onkeypress=\"return restrictCharacters(event);\" name=\"dateInput\"/></td>\n <td></td>\n <td><span id=\"span2\"></span></td>\n </tr>\n\n <tr>\n <td></td>\n <td><input type=\"button\" name=\"submit\" value=\"Submit\" onclick=\"dateCheck(document.myForm.dateInput)\" /></td>\n </tr>\n </table>\n </form> \n </div> \n</body> \n</html> \n</code></pre>\n"
},
{
"answer_id": 36956722,
"author": "Dinesh Lomte",
"author_id": 2436314,
"author_profile": "https://Stackoverflow.com/users/2436314",
"pm_score": 0,
"selected": false,
"text": "<p>Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy. </p>\n\n<p><strong>Note supplied date format and date string go hand in hand.</strong></p>\n\n<pre><code><script type=\"text/javascript\">\nfunction validate(format) {\n\n if(isAfterCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is after the current date.');\n } else {\n alert('Date is not after the current date.');\n }\n if(isBeforeCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is before current date.');\n } else {\n alert('Date is not before current date.');\n }\n if(isCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is current date.');\n } else {\n alert('Date is not a current date.');\n }\n if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('Start/Effective Date cannot be greater than End/Expiration Date');\n } else {\n alert('Valid dates...');\n }\n if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('End/Expiration Date cannot be less than Start/Effective Date');\n } else {\n alert('Valid dates...');\n }\n if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('Dates are equals...');\n } else {\n alert('Dates are not equals...');\n }\n if (isDate(document.getElementById('start').value, format)) {\n alert('Is valid date...');\n } else {\n alert('Is invalid date...');\n }\n}\n\n/**\n * This method gets the year index from the supplied format\n */\nfunction getYearIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'YYYY'\n || tokens[0] === 'yyyy') {\n return 0;\n } else if (tokens[1]=== 'YYYY'\n || tokens[1] === 'yyyy') {\n return 1;\n } else if (tokens[2] === 'YYYY'\n || tokens[2] === 'yyyy') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the year string located at the supplied index\n */\nfunction getYear(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method gets the month index from the supplied format\n */\nfunction getMonthIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'MM'\n || tokens[0] === 'mm') {\n return 0;\n } else if (tokens[1] === 'MM'\n || tokens[1] === 'mm') {\n return 1;\n } else if (tokens[2] === 'MM'\n || tokens[2] === 'mm') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the month string located at the supplied index\n */\nfunction getMonth(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method gets the date index from the supplied format\n */\nfunction getDateIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'DD'\n || tokens[0] === 'dd') {\n return 0;\n } else if (tokens[1] === 'DD'\n || tokens[1] === 'dd') {\n return 1;\n } else if (tokens[2] === 'DD'\n || tokens[2] === 'dd') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the date string located at the supplied index\n */\nfunction getDate(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method returns true if date1 is before date2 else return false\n */\nfunction isBefore(date1, date2, format) {\n // Validating if date1 date is greater than the date2 date\n if (new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n > new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method returns true if date1 is after date2 else return false\n */\nfunction isAfter(date1, date2, format) {\n // Validating if date2 date is less than the date1 date\n if (new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()\n < new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n ) {\n return true;\n } \n return false; \n}\n\n/**\n * This method returns true if date1 is equals to date2 else return false\n */\nfunction isEquals(date1, date2, format) {\n // Validating if date1 date is equals to the date2 date\n if (new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n === new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()) {\n return true;\n } \n return false;\n}\n\n/**\n * This method validates and returns true if the supplied date is \n * equals to the current date.\n */\nfunction isCurrentDate(date, format) {\n // Validating if the supplied date is the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n === new Date(new Date().getFullYear(), \n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method validates and returns true if the supplied date value \n * is before the current date.\n */\nfunction isBeforeCurrentDate(date, format) {\n // Validating if the supplied date is before the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n < new Date(new Date().getFullYear(), \n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method validates and returns true if the supplied date value \n * is after the current date.\n */\nfunction isAfterCurrentDate(date, format) {\n // Validating if the supplied date is before the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n > new Date(new Date().getFullYear(),\n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method splits the supplied date OR format based \n * on non alpha numeric characters in the supplied string.\n */\nfunction splitDateFormat(dateFormat) {\n // Spliting the supplied string based on non characters\n return dateFormat.split(/\\W/);\n}\n\n/*\n * This method validates if the supplied value is a valid date.\n */\nfunction isDate(date, format) { \n // Validating if the supplied date string is valid and not a NaN (Not a Number)\n if (!isNaN(new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))))) { \n return true;\n } \n return false; \n}\n</code></pre>\n\n<p></p>\n\n<blockquote>\n <p>Below is the HTML snippet</p>\n</blockquote>\n\n<pre><code> <input type=\"text\" name=\"start\" id=\"start\" size=\"10\" value=\"05/31/2016\" />\n<br/> \n<input type=\"text\" name=\"end\" id=\"end\" size=\"10\" value=\"04/28/2016\" />\n<br/>\n<input type=\"button\" value=\"Submit\" onclick=\"javascript:validate('MM/dd/yyyy');\" />\n</code></pre>\n"
},
{
"answer_id": 39654657,
"author": "Dominik Baran",
"author_id": 6503328,
"author_profile": "https://Stackoverflow.com/users/6503328",
"pm_score": 0,
"selected": false,
"text": "<p>If your date needs to match DD.MM.YYYY and use AngularJS, use the following code:</p>\n\n<pre><code>$scope.validDate = function(value){\n var matches = /^(\\d{1,2})[.](\\d{1,2})[.](\\d{4})$/.exec(value);\n if (matches == null) return false;\n var d = matches[1];\n var m = matches[2] - 1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n };\n console.log($scope.validDate('22.04.2001'));\n console.log($scope.validDate('03.10.2001'));\n console.log($scope.validDate('30.02.2001'));\n console.log($scope.validDate('23.09.2016'));\n console.log($scope.validDate('29.02.2016'));\n console.log($scope.validDate('31.02.2016'));\n</code></pre>\n\n<p>More about the scope object can be found <a href=\"https://docs.angularjs.org/guide/scope\" rel=\"nofollow\">here</a>. Without AngularJS, simply change the first line to:</p>\n\n<pre><code>ValidDate = new function(value) {\n</code></pre>\n\n<p>And call it using:</p>\n\n<pre><code>var MyDate= ValidDate('29.09.2016');\n</code></pre>\n"
},
{
"answer_id": 42264474,
"author": "Fox",
"author_id": 7572533,
"author_profile": "https://Stackoverflow.com/users/7572533",
"pm_score": 0,
"selected": false,
"text": "<p>DateFormat = DD.MM.YYYY or D.M.YYYY</p>\n\n<pre><code>function dateValidate(val){ \nvar dateStr = val.split('.'); \n var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]); \n if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])\n { return date; }\n else{ return 'NotValid';} \n}\n</code></pre>\n"
},
{
"answer_id": 43465071,
"author": "Harish Gupta",
"author_id": 5227100,
"author_profile": "https://Stackoverflow.com/users/5227100",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code>function validateDate(dates){\n re = /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/; \n var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);\n\n if(regs = dates.match(re)) {\n // day value between 1 and 31\n if(regs[1] < 1 || regs[1] > 31) { \n return false;\n }\n // month value between 1 and 12\n if(regs[2] < 1 || regs[2] > 12) { \n return false;\n }\n\n var maxday=days[regs[2]-1];\n\n if(regs[2]==2){\n if(regs[3]%4==0){\n maxday=maxday+1; \n }\n }\n\n if(regs[1]>maxday){\n return false;\n }\n\n return true;\n }else{\n return false;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 54227074,
"author": "Adam Leggett",
"author_id": 4735342,
"author_profile": "https://Stackoverflow.com/users/4735342",
"pm_score": 0,
"selected": false,
"text": "<p>Short and fast.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function dateValid(date) {\r\n var match = date.match(/^(\\d\\d)-(\\d\\d)-(\\d{4})$/) || [];\r\n var m = (match[1] | 0) - 1;\r\n var d = match[2] | 0;\r\n var y = match[3] | 0;\r\n return !(\r\n m < 0 || // Before January\r\n m > 11 || // After December\r\n d < 1 || // Before the 1st of the month\r\n d - 30 > (2773 >> m & 1) || // After the 30th or 31st of the month using bitmap\r\n m == 1 && d - 28 > // After the 28th or 29th of February depending on leap year\r\n (!(y % 4) && y % 100 || !(y % 400)));\r\n}\r\n\r\nconsole.log('02-29-2000', dateValid('02-29-2000'));\r\nconsole.log('02-29-2001', dateValid('02-29-2001'));\r\nconsole.log('12-31-1970', dateValid('12-31-1970'));\r\nconsole.log('Hello', dateValid('Hello'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 54945688,
"author": "Michael Janssen",
"author_id": 11089162,
"author_profile": "https://Stackoverflow.com/users/11089162",
"pm_score": 0,
"selected": false,
"text": "<p>German Variant, but could be adapted to Iso</p>\n\n<pre><code>export function isLeapYear(year) {\n return (\n year % 4 === 0 && (year % 100 != 0 || year % 1000 === 0 || year % 400 === 0)\n )\n}\n\nexport function isValidGermanDate(germanDate) {\n if (\n !germanDate ||\n germanDate.length < 5 ||\n germanDate.split('.').length < 3\n ) {\n return false\n }\n\n const day = parseInt(germanDate.split('.')[0])\n const month = parseInt(germanDate.split('.')[1])\n const year = parseInt(germanDate.split('.')[2])\n\n if (isNaN(month) || isNaN(day) || isNaN(year)) {\n return false\n }\n\n if (month < 1 || month > 12) {\n return false\n }\n\n if (day < 1 || day > 31) {\n return false\n }\n\n if ((month === 4 || month === 6 || month === 9 || month === 11) && day > 30) {\n return false\n }\n\n if (isLeapYear(year)) {\n if (month === 2 && day > 29) {\n return false\n }\n } else {\n if (month === 2 && day > 28) {\n return false\n }\n }\n\n return true\n}\n</code></pre>\n"
},
{
"answer_id": 64623472,
"author": "Patrick_B",
"author_id": 9745415,
"author_profile": "https://Stackoverflow.com/users/9745415",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding on "Short and Fast" above by @Adam Leggett, as cases like "02/30/2020" return <code>true</code> when it should be <code>false</code>. I really dig the bitmap though...</p>\n<p>For a MM/DD/YYYY date format validation:</p>\n<pre><code>const dateValid = (date) => {\n const isLeapYear = (yearNum) => {\n return ((yearNum % 100 === 0) ? (yearNum % 400 === 0) : (yearNum % 4 === 0))?\n 1:\n 0;\n }\n const match = date.match(/^(\\d\\d)\\/(\\d\\d)\\/(\\d{4})$/) || [];\n const month = (match[1] | 0) - 1;\n const day = match[2] | 0;\n const year = match[3] | 0;\n\nconst dateEval=!( month < 0 || // Before January\n month > 11 || // After December\n day < 1 || // Before the 1st of the month\n day - 30 > (2773 >> month & 1) ||\n month === 1 && day - 28 > isLeapYear(year) \n // Day is 28 or 29, month is 02, year is leap year ==> true\n );\n\nreturn `\\nDate: ${date}\\n\\n \n Valid Date?: ${dateEval}\\n\n =======================================`\n}\n\nconsole.log(dateValid('02/28/2020')) // true\nconsole.log(dateValid('02/29/2020')) // true\nconsole.log(dateValid('02/30/2020')) // false\nconsole.log(dateValid('01/31/2020')) // true\nconsole.log(dateValid('01/31/2000')) // true\nconsole.log(dateValid('04/31/2020')) // false\nconsole.log(dateValid('04/31/2000')) // false\nconsole.log(dateValid('04/30/2020')) // true\nconsole.log(dateValid('01/32/2020')) // false\nconsole.log(dateValid('02/28/2021')) // true\nconsole.log(dateValid('02/29/2021')) // false\nconsole.log(dateValid('02/30/2021')) // false\nconsole.log(dateValid('02/28/2000')) // true\nconsole.log(dateValid('02/29/2000')) // true\nconsole.log(dateValid('02/30/2000')) // false\nconsole.log(dateValid('02/28/2001')) // true\nconsole.log(dateValid('02/29/2001')) // false\nconsole.log(dateValid('02/30/2001')) // false\n</code></pre>\n<p>For a MM-DD-YYYY date format validation: Replace <code>\\/</code> in the pattern for <code>match</code> by <code>-</code>.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3401/"
] |
I saw a potential answer here but that was for YYYY-MM-DD: [JavaScript date validation](http://paulschreiber.com/blog/2007/03/02/javascript-date-validation/)
I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:
```
String.prototype.isValidDate = function()
{
var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
return ((composedDate.getMonth() == (matches[1] - 1)) &&
(composedDate.getDate() == matches[2]) &&
(composedDate.getFullYear() == matches[3]));
}
```
How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?
Thanks.
|
```
function isValidDate(date)
{
var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
```
It works. (Tested with Firebug, hence the console.log().)
|
276,489 |
<p>We'll soon be embarking on the development of a new mobile application. This particular app will be used for heavy searching of text based fields. Any suggestions from the group at large for what sort of database engine is best suited to allowing these types of searches on a mobile platform?</p>
<p>Specifics include Windows Mobile 6 and we'll be using the .Net CF. Also some of the text based fields will be anywhere between 35 and 500 characters. The device will operate in two different methods, batch and WiFi. Of course for WiFi we can just submit requests to a full blown DB engine and just fetch results back. This question centres around the "batch" version which will house a database loaded with information on the devices flash/removable storage card.</p>
<p>At any rate, I know SQLCE has some basic indexing but you don't get into the real fancy "full text" style indexes until you've got the full blown version which of course isn't available on a mobile platform.</p>
<p>An example of what the data would look like:</p>
<p><em>"apron carpenter adjustable leather container pocket waist hardware belt"</em> etc. etc.</p>
<p>I haven't gotten into the evaluation of any other specific options yet as I figure I'd leverage the experience of this group in order to first point me down some specific avenues.</p>
<p>Any suggestions/tips?</p>
|
[
{
"answer_id": 276541,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 2,
"selected": false,
"text": "<p>You could try Lucene.Net. I'm not sure how well it's suited to mobile devices, but it is billed as a \"high-performance, full-featured text search engine library\".</p>\n\n<p><a href=\"http://incubator.apache.org/lucene.net/\" rel=\"nofollow noreferrer\">http://incubator.apache.org/lucene.net/</a>\n<a href=\"http://lucene.apache.org/java/docs/\" rel=\"nofollow noreferrer\">http://lucene.apache.org/java/docs/</a></p>\n"
},
{
"answer_id": 451671,
"author": "Jason Down",
"author_id": 9732,
"author_profile": "https://Stackoverflow.com/users/9732",
"pm_score": 4,
"selected": true,
"text": "<p>Just recently I had the same issue. Here is what I did:</p>\n\n<p>I created a class to hold just an id and the text for each object (in my case I called it a sku (item number) and a description). This creates a smaller object that uses less memory since it is only used for searching. I'll still grab the full-blown objects from the database after I find matches.</p>\n\n<pre><code>public class SmallItem\n{\n private int _sku;\n public int Sku\n {\n get { return _sku; }\n set { _sku = value; }\n }\n\n // Size of max description size + 1 for null terminator.\n private char[] _description = new char[36];\n public char[] Description\n {\n get { return _description; }\n set { _description = value; }\n }\n\n public SmallItem()\n {\n }\n}\n</code></pre>\n\n<p>After this class is created, you can then create an array (I actually used a List in my case) of these objects and use it for searching throughout your application. The initialization of this list takes a bit of time, but you only need to worry about this at start up. Basically just run a query on your database and grab the data you need to create this list.</p>\n\n<p>Once you have a list, you can quickly go through it searching for any words you want. Since it's a contains, it must also find words within words (e.g. drill would return drill, drillbit, drills etc.). To do this, we wrote a home-grown, unmanaged c# contains function. It takes in a string array of words (so you can search for more than one word... we use it for \"AND\" searches... the description must contain all words passed in... \"OR\" is not currently supported in this example). As it searches through the list of words it builds a list of IDs, which are then passed back to the calling function. Once you have a list of IDs, you can easily run a fast query in your database to return the full-blown objects based on a fast indexed ID number. I should mention that we also limit the maximum number of results returned. This could be taken out. It's just handy if someone types in something like \"e\" as their search term. That's going to return a lot of results.</p>\n\n<p>Here's the example of custom Contains function:</p>\n\n<pre><code>public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)\n{\n // Don't allow more than the maximum allowable results constant. \n int[] matchingSkus = new int[maxResults];\n\n // Indexes and counters.\n int matchNumber = 0;\n int currentWord = 0;\n int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes\n\n bool matchedWord;\n\n try\n { \n /* Character array of character arrays. Each array is a word we want to match.\n * We need the + 1 because totalWords had - 1 (We are setting a size/length here,\n * so it is not 0 based... we used - 1 on totalWords because it is used for 0\n * based index referencing.)\n * */\n char[][] allWordsToMatch = new char[totalWords + 1][];\n\n // Character array to hold the current word to match. \n char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.\n\n // Loop through the original string array or words to match and create the character arrays. \n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n char[] desc = new char[descriptionTerms[currentWord].Length + 1];\n Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);\n allWordsToMatch[currentWord] = desc;\n }\n\n // Offsets for description and filter(word to match) pointers.\n int descriptionOffset = 0, filterOffset = 0;\n\n // Loop through the list of items trying to find matching words.\n foreach (SmallItem i in itemList)\n {\n // If we have reached our maximum allowable matches, we should stop searching and just return the results.\n if (matchNumber == maxResults)\n break;\n\n // Loop through the \"words to match\" filter list.\n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n // Reset our match flag and current word to match.\n matchedWord = false;\n wordToMatch = allWordsToMatch[currentWord];\n\n // Delving into unmanaged code for SCREAMING performance ;)\n unsafe\n {\n // Pointer to the description of the current item on the list (starting at first char).\n fixed (char* pdesc = &i.Description[0])\n {\n // Pointer to the current word we are trying to match (starting at first char).\n fixed (char* pfilter = &wordToMatch[0])\n {\n // Reset the description offset.\n descriptionOffset = 0;\n\n // Continue our search on the current word until we hit a null terminator for the char array.\n while (*(pdesc + descriptionOffset) != '\\0')\n {\n // We've matched the first character of the word we're trying to match.\n if (*(pdesc + descriptionOffset) == *pfilter)\n {\n // Reset the filter offset.\n filterOffset = 0;\n\n /* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match\n * or a null terminator, we need to jump out of this loop.\n * */\n while (*(pfilter + filterOffset) != '\\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))\n {\n // Increase the offsets together to the next character.\n ++filterOffset;\n ++descriptionOffset;\n }\n\n // We hit matches all the way to the null terminator. The entire word was a match.\n if (*(pfilter + filterOffset) == '\\0')\n {\n // If our current word matched is the last word on the match list, we have matched all words.\n if (currentWord == totalWords)\n {\n // Add the sku as a match.\n matchingSkus[matchNumber] = i.Sku.ToString();\n matchNumber++;\n\n /* Break out of this item description. We have matched all needed words and can move to\n * the next item.\n * */\n break;\n }\n\n /* We've matched a word, but still have more words left in our list of words to match.\n * Set our match flag to true, which will mean we continue continue to search for the\n * next word on the list.\n * */\n matchedWord = true;\n }\n }\n\n // No match on the current character. Move to next one.\n descriptionOffset++;\n }\n\n /* The current word had no match, so no sense in looking for the rest of the words. Break to the\n * next item description.\n * */\n if (!matchedWord)\n break;\n }\n }\n }\n }\n };\n\n // We have our list of matching skus. We'll resize the array and pass it back.\n Array.Resize(ref matchingSkus, matchNumber);\n return matchingSkus;\n }\n catch (Exception ex)\n {\n // Handle the exception\n }\n}\n</code></pre>\n\n<p>Once you have the list of matching skus, you can iterate through the array and build a query command that only returns the matching skus.</p>\n\n<p>For an idea of performance, here's what we have found (doing the following steps):</p>\n\n<ul>\n<li>Search ~171,000 items</li>\n<li>Create list of all matching items</li>\n<li>Query the database, returning only the matching items</li>\n<li>Build full-blown items (similar to SmallItem class, but a lot more fields)</li>\n<li>Populate a datagrid with the full-blow item objects.</li>\n</ul>\n\n<p>On our mobile units, the entire process takes 2-4 seconds (takes 2 if we hit our match limit before we have searched all items... takes 4 seconds if we have to scan every item).</p>\n\n<p>I've also tried doing this without unmanaged code and using String.IndexOf (and tried String.Contains... had same performance as IndexOf as it should). That way was much slower... about 25 seconds.</p>\n\n<p>I've also tried using a StreamReader and a file containing lines of [Sku Number]|[Description]. The code was similar to the unmanaged code example. This way took about 15 seconds for an entire scan. Not too bad for speed, but not great. The file and StreamReader method has one advantage over the way I showed you though. The file can be created ahead of time. The way I showed you requires the memory and the initial time to load the List when the application starts up. For our 171,000 items, this takes about 2 minutes. If you can afford to wait for that initial load each time the app starts up (which can be done on a separate thread of course), then searching this way is the fastest way (that I've found at least).</p>\n\n<p>Hope that helps.</p>\n\n<p>PS - Thanks to Dolch for helping with some of the unmanaged code.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26853/"
] |
We'll soon be embarking on the development of a new mobile application. This particular app will be used for heavy searching of text based fields. Any suggestions from the group at large for what sort of database engine is best suited to allowing these types of searches on a mobile platform?
Specifics include Windows Mobile 6 and we'll be using the .Net CF. Also some of the text based fields will be anywhere between 35 and 500 characters. The device will operate in two different methods, batch and WiFi. Of course for WiFi we can just submit requests to a full blown DB engine and just fetch results back. This question centres around the "batch" version which will house a database loaded with information on the devices flash/removable storage card.
At any rate, I know SQLCE has some basic indexing but you don't get into the real fancy "full text" style indexes until you've got the full blown version which of course isn't available on a mobile platform.
An example of what the data would look like:
*"apron carpenter adjustable leather container pocket waist hardware belt"* etc. etc.
I haven't gotten into the evaluation of any other specific options yet as I figure I'd leverage the experience of this group in order to first point me down some specific avenues.
Any suggestions/tips?
|
Just recently I had the same issue. Here is what I did:
I created a class to hold just an id and the text for each object (in my case I called it a sku (item number) and a description). This creates a smaller object that uses less memory since it is only used for searching. I'll still grab the full-blown objects from the database after I find matches.
```
public class SmallItem
{
private int _sku;
public int Sku
{
get { return _sku; }
set { _sku = value; }
}
// Size of max description size + 1 for null terminator.
private char[] _description = new char[36];
public char[] Description
{
get { return _description; }
set { _description = value; }
}
public SmallItem()
{
}
}
```
After this class is created, you can then create an array (I actually used a List in my case) of these objects and use it for searching throughout your application. The initialization of this list takes a bit of time, but you only need to worry about this at start up. Basically just run a query on your database and grab the data you need to create this list.
Once you have a list, you can quickly go through it searching for any words you want. Since it's a contains, it must also find words within words (e.g. drill would return drill, drillbit, drills etc.). To do this, we wrote a home-grown, unmanaged c# contains function. It takes in a string array of words (so you can search for more than one word... we use it for "AND" searches... the description must contain all words passed in... "OR" is not currently supported in this example). As it searches through the list of words it builds a list of IDs, which are then passed back to the calling function. Once you have a list of IDs, you can easily run a fast query in your database to return the full-blown objects based on a fast indexed ID number. I should mention that we also limit the maximum number of results returned. This could be taken out. It's just handy if someone types in something like "e" as their search term. That's going to return a lot of results.
Here's the example of custom Contains function:
```
public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)
{
// Don't allow more than the maximum allowable results constant.
int[] matchingSkus = new int[maxResults];
// Indexes and counters.
int matchNumber = 0;
int currentWord = 0;
int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes
bool matchedWord;
try
{
/* Character array of character arrays. Each array is a word we want to match.
* We need the + 1 because totalWords had - 1 (We are setting a size/length here,
* so it is not 0 based... we used - 1 on totalWords because it is used for 0
* based index referencing.)
* */
char[][] allWordsToMatch = new char[totalWords + 1][];
// Character array to hold the current word to match.
char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.
// Loop through the original string array or words to match and create the character arrays.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
char[] desc = new char[descriptionTerms[currentWord].Length + 1];
Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);
allWordsToMatch[currentWord] = desc;
}
// Offsets for description and filter(word to match) pointers.
int descriptionOffset = 0, filterOffset = 0;
// Loop through the list of items trying to find matching words.
foreach (SmallItem i in itemList)
{
// If we have reached our maximum allowable matches, we should stop searching and just return the results.
if (matchNumber == maxResults)
break;
// Loop through the "words to match" filter list.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
// Reset our match flag and current word to match.
matchedWord = false;
wordToMatch = allWordsToMatch[currentWord];
// Delving into unmanaged code for SCREAMING performance ;)
unsafe
{
// Pointer to the description of the current item on the list (starting at first char).
fixed (char* pdesc = &i.Description[0])
{
// Pointer to the current word we are trying to match (starting at first char).
fixed (char* pfilter = &wordToMatch[0])
{
// Reset the description offset.
descriptionOffset = 0;
// Continue our search on the current word until we hit a null terminator for the char array.
while (*(pdesc + descriptionOffset) != '\0')
{
// We've matched the first character of the word we're trying to match.
if (*(pdesc + descriptionOffset) == *pfilter)
{
// Reset the filter offset.
filterOffset = 0;
/* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match
* or a null terminator, we need to jump out of this loop.
* */
while (*(pfilter + filterOffset) != '\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))
{
// Increase the offsets together to the next character.
++filterOffset;
++descriptionOffset;
}
// We hit matches all the way to the null terminator. The entire word was a match.
if (*(pfilter + filterOffset) == '\0')
{
// If our current word matched is the last word on the match list, we have matched all words.
if (currentWord == totalWords)
{
// Add the sku as a match.
matchingSkus[matchNumber] = i.Sku.ToString();
matchNumber++;
/* Break out of this item description. We have matched all needed words and can move to
* the next item.
* */
break;
}
/* We've matched a word, but still have more words left in our list of words to match.
* Set our match flag to true, which will mean we continue continue to search for the
* next word on the list.
* */
matchedWord = true;
}
}
// No match on the current character. Move to next one.
descriptionOffset++;
}
/* The current word had no match, so no sense in looking for the rest of the words. Break to the
* next item description.
* */
if (!matchedWord)
break;
}
}
}
}
};
// We have our list of matching skus. We'll resize the array and pass it back.
Array.Resize(ref matchingSkus, matchNumber);
return matchingSkus;
}
catch (Exception ex)
{
// Handle the exception
}
}
```
Once you have the list of matching skus, you can iterate through the array and build a query command that only returns the matching skus.
For an idea of performance, here's what we have found (doing the following steps):
* Search ~171,000 items
* Create list of all matching items
* Query the database, returning only the matching items
* Build full-blown items (similar to SmallItem class, but a lot more fields)
* Populate a datagrid with the full-blow item objects.
On our mobile units, the entire process takes 2-4 seconds (takes 2 if we hit our match limit before we have searched all items... takes 4 seconds if we have to scan every item).
I've also tried doing this without unmanaged code and using String.IndexOf (and tried String.Contains... had same performance as IndexOf as it should). That way was much slower... about 25 seconds.
I've also tried using a StreamReader and a file containing lines of [Sku Number]|[Description]. The code was similar to the unmanaged code example. This way took about 15 seconds for an entire scan. Not too bad for speed, but not great. The file and StreamReader method has one advantage over the way I showed you though. The file can be created ahead of time. The way I showed you requires the memory and the initial time to load the List when the application starts up. For our 171,000 items, this takes about 2 minutes. If you can afford to wait for that initial load each time the app starts up (which can be done on a separate thread of course), then searching this way is the fastest way (that I've found at least).
Hope that helps.
PS - Thanks to Dolch for helping with some of the unmanaged code.
|
276,499 |
<p>I have a custom UILabel subclass for displaying currency values. I only want the user to be able to enter digits and let the view format those digits into a currency value -- like a cash register. This makes UITextField an inappropriate choice for this kind of input.</p>
<p>I've already overridden hitTest: so that the UILabel will return itself -- this is apparently a bug. Also, I've overridden both canBecomeFirstResponder and becomeFirstResponder to return YES. Neither of these methods are being called, though.</p>
<p>I only want to let the user type numbers and use the backspace key. I've implemented UITextInputTraits, but the keyboard does not appear. So, can this be done? And does if so, what am I missing?</p>
|
[
{
"answer_id": 276541,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 2,
"selected": false,
"text": "<p>You could try Lucene.Net. I'm not sure how well it's suited to mobile devices, but it is billed as a \"high-performance, full-featured text search engine library\".</p>\n\n<p><a href=\"http://incubator.apache.org/lucene.net/\" rel=\"nofollow noreferrer\">http://incubator.apache.org/lucene.net/</a>\n<a href=\"http://lucene.apache.org/java/docs/\" rel=\"nofollow noreferrer\">http://lucene.apache.org/java/docs/</a></p>\n"
},
{
"answer_id": 451671,
"author": "Jason Down",
"author_id": 9732,
"author_profile": "https://Stackoverflow.com/users/9732",
"pm_score": 4,
"selected": true,
"text": "<p>Just recently I had the same issue. Here is what I did:</p>\n\n<p>I created a class to hold just an id and the text for each object (in my case I called it a sku (item number) and a description). This creates a smaller object that uses less memory since it is only used for searching. I'll still grab the full-blown objects from the database after I find matches.</p>\n\n<pre><code>public class SmallItem\n{\n private int _sku;\n public int Sku\n {\n get { return _sku; }\n set { _sku = value; }\n }\n\n // Size of max description size + 1 for null terminator.\n private char[] _description = new char[36];\n public char[] Description\n {\n get { return _description; }\n set { _description = value; }\n }\n\n public SmallItem()\n {\n }\n}\n</code></pre>\n\n<p>After this class is created, you can then create an array (I actually used a List in my case) of these objects and use it for searching throughout your application. The initialization of this list takes a bit of time, but you only need to worry about this at start up. Basically just run a query on your database and grab the data you need to create this list.</p>\n\n<p>Once you have a list, you can quickly go through it searching for any words you want. Since it's a contains, it must also find words within words (e.g. drill would return drill, drillbit, drills etc.). To do this, we wrote a home-grown, unmanaged c# contains function. It takes in a string array of words (so you can search for more than one word... we use it for \"AND\" searches... the description must contain all words passed in... \"OR\" is not currently supported in this example). As it searches through the list of words it builds a list of IDs, which are then passed back to the calling function. Once you have a list of IDs, you can easily run a fast query in your database to return the full-blown objects based on a fast indexed ID number. I should mention that we also limit the maximum number of results returned. This could be taken out. It's just handy if someone types in something like \"e\" as their search term. That's going to return a lot of results.</p>\n\n<p>Here's the example of custom Contains function:</p>\n\n<pre><code>public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)\n{\n // Don't allow more than the maximum allowable results constant. \n int[] matchingSkus = new int[maxResults];\n\n // Indexes and counters.\n int matchNumber = 0;\n int currentWord = 0;\n int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes\n\n bool matchedWord;\n\n try\n { \n /* Character array of character arrays. Each array is a word we want to match.\n * We need the + 1 because totalWords had - 1 (We are setting a size/length here,\n * so it is not 0 based... we used - 1 on totalWords because it is used for 0\n * based index referencing.)\n * */\n char[][] allWordsToMatch = new char[totalWords + 1][];\n\n // Character array to hold the current word to match. \n char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.\n\n // Loop through the original string array or words to match and create the character arrays. \n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n char[] desc = new char[descriptionTerms[currentWord].Length + 1];\n Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);\n allWordsToMatch[currentWord] = desc;\n }\n\n // Offsets for description and filter(word to match) pointers.\n int descriptionOffset = 0, filterOffset = 0;\n\n // Loop through the list of items trying to find matching words.\n foreach (SmallItem i in itemList)\n {\n // If we have reached our maximum allowable matches, we should stop searching and just return the results.\n if (matchNumber == maxResults)\n break;\n\n // Loop through the \"words to match\" filter list.\n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n // Reset our match flag and current word to match.\n matchedWord = false;\n wordToMatch = allWordsToMatch[currentWord];\n\n // Delving into unmanaged code for SCREAMING performance ;)\n unsafe\n {\n // Pointer to the description of the current item on the list (starting at first char).\n fixed (char* pdesc = &i.Description[0])\n {\n // Pointer to the current word we are trying to match (starting at first char).\n fixed (char* pfilter = &wordToMatch[0])\n {\n // Reset the description offset.\n descriptionOffset = 0;\n\n // Continue our search on the current word until we hit a null terminator for the char array.\n while (*(pdesc + descriptionOffset) != '\\0')\n {\n // We've matched the first character of the word we're trying to match.\n if (*(pdesc + descriptionOffset) == *pfilter)\n {\n // Reset the filter offset.\n filterOffset = 0;\n\n /* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match\n * or a null terminator, we need to jump out of this loop.\n * */\n while (*(pfilter + filterOffset) != '\\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))\n {\n // Increase the offsets together to the next character.\n ++filterOffset;\n ++descriptionOffset;\n }\n\n // We hit matches all the way to the null terminator. The entire word was a match.\n if (*(pfilter + filterOffset) == '\\0')\n {\n // If our current word matched is the last word on the match list, we have matched all words.\n if (currentWord == totalWords)\n {\n // Add the sku as a match.\n matchingSkus[matchNumber] = i.Sku.ToString();\n matchNumber++;\n\n /* Break out of this item description. We have matched all needed words and can move to\n * the next item.\n * */\n break;\n }\n\n /* We've matched a word, but still have more words left in our list of words to match.\n * Set our match flag to true, which will mean we continue continue to search for the\n * next word on the list.\n * */\n matchedWord = true;\n }\n }\n\n // No match on the current character. Move to next one.\n descriptionOffset++;\n }\n\n /* The current word had no match, so no sense in looking for the rest of the words. Break to the\n * next item description.\n * */\n if (!matchedWord)\n break;\n }\n }\n }\n }\n };\n\n // We have our list of matching skus. We'll resize the array and pass it back.\n Array.Resize(ref matchingSkus, matchNumber);\n return matchingSkus;\n }\n catch (Exception ex)\n {\n // Handle the exception\n }\n}\n</code></pre>\n\n<p>Once you have the list of matching skus, you can iterate through the array and build a query command that only returns the matching skus.</p>\n\n<p>For an idea of performance, here's what we have found (doing the following steps):</p>\n\n<ul>\n<li>Search ~171,000 items</li>\n<li>Create list of all matching items</li>\n<li>Query the database, returning only the matching items</li>\n<li>Build full-blown items (similar to SmallItem class, but a lot more fields)</li>\n<li>Populate a datagrid with the full-blow item objects.</li>\n</ul>\n\n<p>On our mobile units, the entire process takes 2-4 seconds (takes 2 if we hit our match limit before we have searched all items... takes 4 seconds if we have to scan every item).</p>\n\n<p>I've also tried doing this without unmanaged code and using String.IndexOf (and tried String.Contains... had same performance as IndexOf as it should). That way was much slower... about 25 seconds.</p>\n\n<p>I've also tried using a StreamReader and a file containing lines of [Sku Number]|[Description]. The code was similar to the unmanaged code example. This way took about 15 seconds for an entire scan. Not too bad for speed, but not great. The file and StreamReader method has one advantage over the way I showed you though. The file can be created ahead of time. The way I showed you requires the memory and the initial time to load the List when the application starts up. For our 171,000 items, this takes about 2 minutes. If you can afford to wait for that initial load each time the app starts up (which can be done on a separate thread of course), then searching this way is the fastest way (that I've found at least).</p>\n\n<p>Hope that helps.</p>\n\n<p>PS - Thanks to Dolch for helping with some of the unmanaged code.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35999/"
] |
I have a custom UILabel subclass for displaying currency values. I only want the user to be able to enter digits and let the view format those digits into a currency value -- like a cash register. This makes UITextField an inappropriate choice for this kind of input.
I've already overridden hitTest: so that the UILabel will return itself -- this is apparently a bug. Also, I've overridden both canBecomeFirstResponder and becomeFirstResponder to return YES. Neither of these methods are being called, though.
I only want to let the user type numbers and use the backspace key. I've implemented UITextInputTraits, but the keyboard does not appear. So, can this be done? And does if so, what am I missing?
|
Just recently I had the same issue. Here is what I did:
I created a class to hold just an id and the text for each object (in my case I called it a sku (item number) and a description). This creates a smaller object that uses less memory since it is only used for searching. I'll still grab the full-blown objects from the database after I find matches.
```
public class SmallItem
{
private int _sku;
public int Sku
{
get { return _sku; }
set { _sku = value; }
}
// Size of max description size + 1 for null terminator.
private char[] _description = new char[36];
public char[] Description
{
get { return _description; }
set { _description = value; }
}
public SmallItem()
{
}
}
```
After this class is created, you can then create an array (I actually used a List in my case) of these objects and use it for searching throughout your application. The initialization of this list takes a bit of time, but you only need to worry about this at start up. Basically just run a query on your database and grab the data you need to create this list.
Once you have a list, you can quickly go through it searching for any words you want. Since it's a contains, it must also find words within words (e.g. drill would return drill, drillbit, drills etc.). To do this, we wrote a home-grown, unmanaged c# contains function. It takes in a string array of words (so you can search for more than one word... we use it for "AND" searches... the description must contain all words passed in... "OR" is not currently supported in this example). As it searches through the list of words it builds a list of IDs, which are then passed back to the calling function. Once you have a list of IDs, you can easily run a fast query in your database to return the full-blown objects based on a fast indexed ID number. I should mention that we also limit the maximum number of results returned. This could be taken out. It's just handy if someone types in something like "e" as their search term. That's going to return a lot of results.
Here's the example of custom Contains function:
```
public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)
{
// Don't allow more than the maximum allowable results constant.
int[] matchingSkus = new int[maxResults];
// Indexes and counters.
int matchNumber = 0;
int currentWord = 0;
int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes
bool matchedWord;
try
{
/* Character array of character arrays. Each array is a word we want to match.
* We need the + 1 because totalWords had - 1 (We are setting a size/length here,
* so it is not 0 based... we used - 1 on totalWords because it is used for 0
* based index referencing.)
* */
char[][] allWordsToMatch = new char[totalWords + 1][];
// Character array to hold the current word to match.
char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.
// Loop through the original string array or words to match and create the character arrays.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
char[] desc = new char[descriptionTerms[currentWord].Length + 1];
Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);
allWordsToMatch[currentWord] = desc;
}
// Offsets for description and filter(word to match) pointers.
int descriptionOffset = 0, filterOffset = 0;
// Loop through the list of items trying to find matching words.
foreach (SmallItem i in itemList)
{
// If we have reached our maximum allowable matches, we should stop searching and just return the results.
if (matchNumber == maxResults)
break;
// Loop through the "words to match" filter list.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
// Reset our match flag and current word to match.
matchedWord = false;
wordToMatch = allWordsToMatch[currentWord];
// Delving into unmanaged code for SCREAMING performance ;)
unsafe
{
// Pointer to the description of the current item on the list (starting at first char).
fixed (char* pdesc = &i.Description[0])
{
// Pointer to the current word we are trying to match (starting at first char).
fixed (char* pfilter = &wordToMatch[0])
{
// Reset the description offset.
descriptionOffset = 0;
// Continue our search on the current word until we hit a null terminator for the char array.
while (*(pdesc + descriptionOffset) != '\0')
{
// We've matched the first character of the word we're trying to match.
if (*(pdesc + descriptionOffset) == *pfilter)
{
// Reset the filter offset.
filterOffset = 0;
/* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match
* or a null terminator, we need to jump out of this loop.
* */
while (*(pfilter + filterOffset) != '\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))
{
// Increase the offsets together to the next character.
++filterOffset;
++descriptionOffset;
}
// We hit matches all the way to the null terminator. The entire word was a match.
if (*(pfilter + filterOffset) == '\0')
{
// If our current word matched is the last word on the match list, we have matched all words.
if (currentWord == totalWords)
{
// Add the sku as a match.
matchingSkus[matchNumber] = i.Sku.ToString();
matchNumber++;
/* Break out of this item description. We have matched all needed words and can move to
* the next item.
* */
break;
}
/* We've matched a word, but still have more words left in our list of words to match.
* Set our match flag to true, which will mean we continue continue to search for the
* next word on the list.
* */
matchedWord = true;
}
}
// No match on the current character. Move to next one.
descriptionOffset++;
}
/* The current word had no match, so no sense in looking for the rest of the words. Break to the
* next item description.
* */
if (!matchedWord)
break;
}
}
}
}
};
// We have our list of matching skus. We'll resize the array and pass it back.
Array.Resize(ref matchingSkus, matchNumber);
return matchingSkus;
}
catch (Exception ex)
{
// Handle the exception
}
}
```
Once you have the list of matching skus, you can iterate through the array and build a query command that only returns the matching skus.
For an idea of performance, here's what we have found (doing the following steps):
* Search ~171,000 items
* Create list of all matching items
* Query the database, returning only the matching items
* Build full-blown items (similar to SmallItem class, but a lot more fields)
* Populate a datagrid with the full-blow item objects.
On our mobile units, the entire process takes 2-4 seconds (takes 2 if we hit our match limit before we have searched all items... takes 4 seconds if we have to scan every item).
I've also tried doing this without unmanaged code and using String.IndexOf (and tried String.Contains... had same performance as IndexOf as it should). That way was much slower... about 25 seconds.
I've also tried using a StreamReader and a file containing lines of [Sku Number]|[Description]. The code was similar to the unmanaged code example. This way took about 15 seconds for an entire scan. Not too bad for speed, but not great. The file and StreamReader method has one advantage over the way I showed you though. The file can be created ahead of time. The way I showed you requires the memory and the initial time to load the List when the application starts up. For our 171,000 items, this takes about 2 minutes. If you can afford to wait for that initial load each time the app starts up (which can be done on a separate thread of course), then searching this way is the fastest way (that I've found at least).
Hope that helps.
PS - Thanks to Dolch for helping with some of the unmanaged code.
|
276,512 |
<p>I have seen some very weird <code>for</code> loops when reading other people's code. I have been trying to search for a full syntax explanation for the <code>for</code> loop in C but it is very hard because the word "for" appears in unrelated sentences making the search almost impossible to Google effectively.</p>
<p>This question came to my mind after reading <a href="https://stackoverflow.com/questions/260511/russian-peasant-multiplication">this thread</a> which made me curious again.</p>
<p>The <code>for</code> here: </p>
<pre><code>for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
</code></pre>
<p>In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both <code>a>>=1</code> and <code>b<<=1</code>. </p>
<p>But within a loop exit condition, what happens? Does it exit when <code>p==0</code>, when <code>a==1</code> or when both happen?</p>
<p>It would be great if anyone could help me understand this and maybe point me in the direction of a full <code>for</code> loop syntax description.</p>
|
[
{
"answer_id": 276518,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>The comma simply separates two expressions and is valid anywhere in C where a normal expression is allowed. These are executed in order from left to right. The value of the rightmost expression is the value of the overall expression.</p>\n\n<p><code>for</code> loops consist of three parts, any of which may also be empty; one (the first) is executed at the beginning, and one (the third) at the end of each iteration. These parts usually initialize and increment a counter, respectively; but they may do anything.</p>\n\n<p>The second part is a <em>test</em> that is executed at the beginning of each execution. If the test yields <code>false</code>, the loop is aborted. That's all there is to it.</p>\n"
},
{
"answer_id": 276519,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 8,
"selected": true,
"text": "<p>The comma is not exclusive of for loops; it is the comma operator.</p>\n\n<pre><code>x = (a, b);\n</code></pre>\n\n<p>will do first a, then b, then set x to the value of b.</p>\n\n<p>The for syntax is:</p>\n\n<pre><code>for (init; condition; increment)\n ...\n</code></pre>\n\n<p>Which is somewhat (ignoring <code>continue</code> and <code>break</code> for now) equivalent to:</p>\n\n<pre><code>init;\nwhile (condition) {\n ...\n increment;\n}\n</code></pre>\n\n<p>So your for loop example is (again ignoring <code>continue</code> and <code>break</code>) equivalent to</p>\n\n<pre><code>p=0;\nwhile (p+=(a&1)*b,a!=1) {\n ...\n a>>=1,b<<=1;\n}\n</code></pre>\n\n<p>Which acts as if it were (again ignoring <code>continue</code> and <code>break</code>):</p>\n\n<pre><code>p=0; \nwhile (true) {\n p+=(a&1)*b;\n if (a == 1) break;\n ...\n a>>=1;\n b<<=1;\n}\n</code></pre>\n\n<p>Two extra details of the for loop which were not in the simplified conversion to a while loop above:</p>\n\n<ul>\n<li>If the condition is omitted, it is always <code>true</code> (resulting in an infinite loop unless a <code>break</code>, <code>goto</code>, or something else breaks the loop).</li>\n<li>A <code>continue</code> acts as if it were a goto to a label just before the increment, unlike a <code>continue</code> in the while loop which would skip the increment.</li>\n</ul>\n\n<p>Also, an important detail about the comma operator: it is a sequence point, like <code>&&</code> and <code>||</code> (which is why I can split it in separate statements and keep its meaning intact).</p>\n\n<hr>\n\n<h3>Changes in C99</h3>\n\n<p>The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).</p>\n\n<p>First, all loops are blocks in their own right. Effectively,</p>\n\n<pre><code>for (...) { ... }\n</code></pre>\n\n<p>is itself wrapped in a pair of braces</p>\n\n<pre><code>{\nfor (...) { ... }\n}\n</code></pre>\n\n<p>The standard sayeth:</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:1999 §6.8.5 Iteration statements</h3>\n \n <p>¶5 An iteration statement is a block whose scope is a strict subset of the scope of its\n enclosing block. The loop body is also a block whose scope is a strict subset of the scope\n of the iteration statement.</p>\n</blockquote>\n\n<p>This is also described in the Rationale in terms of the extra set of braces.</p>\n\n<p>Secondly, the <code>init</code> portion in C99 can be a (single) declaration, as in</p>\n\n<pre><code>for (int i = 0; i < sizeof(something); i++) { ... }\n</code></pre>\n\n<p>Now the 'block wrapped around the loop' comes into its own; it explains why the variable <code>i</code> cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:</p>\n\n<pre><code>for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }\n</code></pre>\n\n<p>The standard sayeth:</p>\n\n<blockquote>\n <h3>ISO/IEC 9899:1999 §6.8.5.3 The for statement</h3>\n \n <p>The statement</p>\n\n<pre><code>for ( clause-1 ; expression-2 ; expression-3 ) statement\n</code></pre>\n \n <p>behaves as follows: The expression expression-2 is the controlling expression that is\n evaluated before each execution of the loop body. The expression expression-3 is\n evaluated as a void expression after each execution of the loop body. If clause-1 is a\n declaration, the scope of any variables it declares is the remainder of the declaration and\n the entire loop, including the other two expressions; it is reached in the order of execution\n before the first evaluation of the controlling expression. If clause-1 is an expression, it is\n evaluated as a void expression before the first evaluation of the controlling expression.<sup>133)</sup></p>\n \n <p>Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a\n nonzero constant.</p>\n \n <p><sup>133)</sup> Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in\n the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration,\n such that execution of the loop continues until the expression compares equal to 0; and expression-3\n specifies an operation (such as incrementing) that is performed after each iteration.</p>\n</blockquote>\n"
},
{
"answer_id": 276540,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>The C style for loop consists of three expressions:</p>\n\n<pre><code>for (initializer; condition; counter) statement_or_statement_block;\n</code></pre>\n\n<ul>\n<li>The initializer runs once, when the loop starts.</li>\n<li>The condition is checked before each iteration. The loop runs as long it evaluates to true.</li>\n<li>The counter runs once after each iteration.</li>\n</ul>\n\n<p>Each of these parts can be an expression valid in the language you write the loop in. That means they can be used more creatively. Anything you want to do beforehand can go into the initializer, anything you want to do in between can go into the condition or the counter, up to the point where the loop has no body anymore.</p>\n\n<p>To achieve that, the comma operator comes in very handy. It allows you to chain expressions together to form a single new expression. Most of the time it is used that way in a for loop, the other implications of the comma operator (e.g. value assignment considerations) play a minor role.</p>\n\n<p>Even though you can do clever things by using syntax creatively - I would stay clear of it until I find a <em>really</em> good reason to do so. Playing code golf with for loops makes code harder to read and understand (and maintain). </p>\n\n<p>The wikipedia has a nice <a href=\"http://en.wikipedia.org/wiki/For_loop\" rel=\"nofollow noreferrer\">article on the for loop</a> as well.</p>\n"
},
{
"answer_id": 626359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Everything is optional in a <code>for</code> loop. We can initialize more than one variable, we can check for more than one condition, we can iterate more than one variable using the comma operator.</p>\n\n<p>The following <code>for</code> loop will take you into an infinite loop. Be careful by checking the condition.</p>\n\n<pre><code>for(;;) \n</code></pre>\n"
},
{
"answer_id": 2631986,
"author": "Bob",
"author_id": 315773,
"author_profile": "https://Stackoverflow.com/users/315773",
"pm_score": 0,
"selected": false,
"text": "<p>Konrad mentioned the key point that I'd like to repeat: The value of the rightmost expression is the value of the overall expression.</p>\n\n<p>A Gnu compiler stated this warning when I put two tests in the \"condition\" section of the for loop</p>\n\n<pre><code>warning: left-hand operand of comma expression has no effect\n</code></pre>\n\n<p>What I really intended for the \"condition\" was two tests with an \"&&\" between. Per Konrad's statement, only the test on to the right of the comma would affect the condition.</p>\n"
},
{
"answer_id": 26359481,
"author": "R.M.VIVEK ARNI",
"author_id": 4140951,
"author_profile": "https://Stackoverflow.com/users/4140951",
"pm_score": -1,
"selected": false,
"text": "<p>the for loop is execution for particular time for(;;)</p>\n\n<p>the syntex for for loop</p>\n\n<p>for(;;)</p>\n\n<p>OR</p>\n\n<p>for (initializer; condition; counter)</p>\n\n<p>e.g (rmv=1;rmv<=15;rmv++)</p>\n\n<p>execution to 15 times in for block</p>\n\n<p>1.first initializ the value because start the value</p>\n\n<p>(e.g)rmv=1 or rmv=2</p>\n\n<p>2.second statement is test the condition is true or false ,the condition true no.of time execution the for loop and the condition is false terminate for block,</p>\n\n<p>e.g i=5;i<=10 the condition is true</p>\n\n<pre><code>i=10;i<10 the condition is false terminate for block,\n</code></pre>\n\n<p>3.third is increment or decrement </p>\n\n<p>(e.g)rmv++ or ++rmv</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
I have seen some very weird `for` loops when reading other people's code. I have been trying to search for a full syntax explanation for the `for` loop in C but it is very hard because the word "for" appears in unrelated sentences making the search almost impossible to Google effectively.
This question came to my mind after reading [this thread](https://stackoverflow.com/questions/260511/russian-peasant-multiplication) which made me curious again.
The `for` here:
```
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
```
In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both `a>>=1` and `b<<=1`.
But within a loop exit condition, what happens? Does it exit when `p==0`, when `a==1` or when both happen?
It would be great if anyone could help me understand this and maybe point me in the direction of a full `for` loop syntax description.
|
The comma is not exclusive of for loops; it is the comma operator.
```
x = (a, b);
```
will do first a, then b, then set x to the value of b.
The for syntax is:
```
for (init; condition; increment)
...
```
Which is somewhat (ignoring `continue` and `break` for now) equivalent to:
```
init;
while (condition) {
...
increment;
}
```
So your for loop example is (again ignoring `continue` and `break`) equivalent to
```
p=0;
while (p+=(a&1)*b,a!=1) {
...
a>>=1,b<<=1;
}
```
Which acts as if it were (again ignoring `continue` and `break`):
```
p=0;
while (true) {
p+=(a&1)*b;
if (a == 1) break;
...
a>>=1;
b<<=1;
}
```
Two extra details of the for loop which were not in the simplified conversion to a while loop above:
* If the condition is omitted, it is always `true` (resulting in an infinite loop unless a `break`, `goto`, or something else breaks the loop).
* A `continue` acts as if it were a goto to a label just before the increment, unlike a `continue` in the while loop which would skip the increment.
Also, an important detail about the comma operator: it is a sequence point, like `&&` and `||` (which is why I can split it in separate statements and keep its meaning intact).
---
### Changes in C99
The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).
First, all loops are blocks in their own right. Effectively,
```
for (...) { ... }
```
is itself wrapped in a pair of braces
```
{
for (...) { ... }
}
```
The standard sayeth:
>
> ### ISO/IEC 9899:1999 §6.8.5 Iteration statements
>
>
> ¶5 An iteration statement is a block whose scope is a strict subset of the scope of its
> enclosing block. The loop body is also a block whose scope is a strict subset of the scope
> of the iteration statement.
>
>
>
This is also described in the Rationale in terms of the extra set of braces.
Secondly, the `init` portion in C99 can be a (single) declaration, as in
```
for (int i = 0; i < sizeof(something); i++) { ... }
```
Now the 'block wrapped around the loop' comes into its own; it explains why the variable `i` cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:
```
for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }
```
The standard sayeth:
>
> ### ISO/IEC 9899:1999 §6.8.5.3 The for statement
>
>
> The statement
>
>
>
> ```
> for ( clause-1 ; expression-2 ; expression-3 ) statement
>
> ```
>
> behaves as follows: The expression expression-2 is the controlling expression that is
> evaluated before each execution of the loop body. The expression expression-3 is
> evaluated as a void expression after each execution of the loop body. If clause-1 is a
> declaration, the scope of any variables it declares is the remainder of the declaration and
> the entire loop, including the other two expressions; it is reached in the order of execution
> before the first evaluation of the controlling expression. If clause-1 is an expression, it is
> evaluated as a void expression before the first evaluation of the controlling expression.133)
>
>
> Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
> nonzero constant.
>
>
> 133) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in
> the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration,
> such that execution of the loop continues until the expression compares equal to 0; and expression-3
> specifies an operation (such as incrementing) that is performed after each iteration.
>
>
>
|
276,516 |
<p>I need to build a function which parses the domain from a URL.</p>
<p>So, with</p>
<pre><code>http://google.com/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>or</p>
<pre><code>http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>it should return <code>google.com</code></p>
<p>with</p>
<pre><code>http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>it should return <code>google.co.uk</code>.</p>
|
[
{
"answer_id": 276525,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 10,
"selected": true,
"text": "<p>Check out <a href=\"http://php.net/parse_url\" rel=\"noreferrer\"><code>parse_url()</code></a>:</p>\n\n<pre><code>$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$parse = parse_url($url);\necho $parse['host']; // prints 'google.com'\n</code></pre>\n\n<p><code>parse_url</code> doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls. </p>\n"
},
{
"answer_id": 1974047,
"author": "philfreo",
"author_id": 137067,
"author_profile": "https://Stackoverflow.com/users/137067",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://us3.php.net/manual/en/function.parse-url.php#93983\" rel=\"noreferrer\">http://us3.php.net/manual/en/function.parse-url.php#93983</a></p>\n\n<blockquote>\n <p>for some odd reason, parse_url\n returns the host (ex. example.com) as\n the path when no scheme is provided in\n the input url. So I've written a quick\n function to get the real host:</p>\n</blockquote>\n\n<pre><code>function getHost($Address) { \n $parseUrl = parse_url(trim($Address)); \n return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); \n} \n\ngetHost(\"example.com\"); // Gives example.com \ngetHost(\"http://example.com\"); // Gives example.com \ngetHost(\"www.example.com\"); // Gives www.example.com \ngetHost(\"http://example.com/xyz\"); // Gives example.com \n</code></pre>\n"
},
{
"answer_id": 1974074,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 7,
"selected": false,
"text": "<pre><code>$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));\n</code></pre>\n\n<p><strong>This would return the <code>google.com</code> for both <a href=\"http://google.com/\" rel=\"noreferrer\">http://google.com/</a>... and <a href=\"http://www.google.com/\" rel=\"noreferrer\">http://www.google.com/</a>...</strong></p>\n"
},
{
"answer_id": 6095829,
"author": "Luka",
"author_id": 744234,
"author_profile": "https://Stackoverflow.com/users/744234",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the code i made that 100% finds only the domain name, since it takes mozilla sub tlds to account. Only thing you have to check is how you make cache of that file, so you dont query mozilla every time. </p>\n\n<p>For some strange reason, domains like co.uk are not in the list, so you have to make some hacking and add them manually. Its not cleanest solution but i hope it helps someone. </p>\n\n<pre><code>//=====================================================\nstatic function domain($url)\n{\n $slds = \"\";\n $url = strtolower($url);\n\n $address = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';\n if(!$subtlds = @kohana::cache('subtlds', null, 60)) \n {\n $content = file($address);\n foreach($content as $num => $line)\n {\n $line = trim($line);\n if($line == '') continue;\n if(@substr($line[0], 0, 2) == '/') continue;\n $line = @preg_replace(\"/[^a-zA-Z0-9\\.]/\", '', $line);\n if($line == '') continue; //$line = '.'.$line;\n if(@$line[0] == '.') $line = substr($line, 1);\n if(!strstr($line, '.')) continue;\n $subtlds[] = $line;\n //echo \"{$num}: '{$line}'\"; echo \"<br>\";\n }\n $subtlds = array_merge(Array(\n 'co.uk', 'me.uk', 'net.uk', 'org.uk', 'sch.uk', 'ac.uk', \n 'gov.uk', 'nhs.uk', 'police.uk', 'mod.uk', 'asn.au', 'com.au',\n 'net.au', 'id.au', 'org.au', 'edu.au', 'gov.au', 'csiro.au',\n ),$subtlds);\n\n $subtlds = array_unique($subtlds);\n //echo var_dump($subtlds);\n @kohana::cache('subtlds', $subtlds);\n }\n\n\n preg_match('/^(http:[\\/]{2,})?([^\\/]+)/i', $url, $matches);\n //preg_match(\"/^(http:\\/\\/|https:\\/\\/|)[a-zA-Z-]([^\\/]+)/i\", $url, $matches);\n $host = @$matches[2];\n //echo var_dump($matches);\n\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n foreach($subtlds as $sub) \n {\n if (preg_match(\"/{$sub}$/\", $host, $xyz))\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n }\n\n return @$matches[0];\n}\n</code></pre>\n"
},
{
"answer_id": 7573307,
"author": "Shaun",
"author_id": 967608,
"author_profile": "https://Stackoverflow.com/users/967608",
"pm_score": 4,
"selected": false,
"text": "<p>The code that was meant to work 100% didn't seem to cut it for me, I did patch the example a little but found code that wasn't helping and problems with it. so I changed it out to a couple of functions (to save asking for the list from Mozilla all the time, and removing the cache system). This has been tested against a set of 1000 URLs and seemed to work.</p>\n\n<pre><code>function domain($url)\n{\n global $subtlds;\n $slds = \"\";\n $url = strtolower($url);\n\n $host = parse_url('http://'.$url,PHP_URL_HOST);\n\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n foreach($subtlds as $sub){\n if (preg_match('/\\.'.preg_quote($sub).'$/', $host, $xyz)){\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n }\n }\n\n return @$matches[0];\n}\n\nfunction get_tlds() {\n $address = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';\n $content = file($address);\n foreach ($content as $num => $line) {\n $line = trim($line);\n if($line == '') continue;\n if(@substr($line[0], 0, 2) == '/') continue;\n $line = @preg_replace(\"/[^a-zA-Z0-9\\.]/\", '', $line);\n if($line == '') continue; //$line = '.'.$line;\n if(@$line[0] == '.') $line = substr($line, 1);\n if(!strstr($line, '.')) continue;\n $subtlds[] = $line;\n //echo \"{$num}: '{$line}'\"; echo \"<br>\";\n }\n\n $subtlds = array_merge(array(\n 'co.uk', 'me.uk', 'net.uk', 'org.uk', 'sch.uk', 'ac.uk', \n 'gov.uk', 'nhs.uk', 'police.uk', 'mod.uk', 'asn.au', 'com.au',\n 'net.au', 'id.au', 'org.au', 'edu.au', 'gov.au', 'csiro.au'\n ), $subtlds);\n\n $subtlds = array_unique($subtlds);\n\n return $subtlds; \n}\n</code></pre>\n\n<p>Then use it like</p>\n\n<pre><code>$subtlds = get_tlds();\necho domain('www.example.com') //outputs: example.com\necho domain('www.example.uk.com') //outputs: example.uk.com\necho domain('www.example.fr') //outputs: example.fr\n</code></pre>\n\n<p>I know I should have turned this into a class, but didn't have time.</p>\n"
},
{
"answer_id": 13617167,
"author": "Will",
"author_id": 514860,
"author_profile": "https://Stackoverflow.com/users/514860",
"pm_score": 1,
"selected": false,
"text": "<p>parse_url didn't work for me. It only returned the path. Switching to basics using php5.3+:</p>\n\n<pre><code>$url = str_replace('http://', '', strtolower( $s->website));\nif (strpos($url, '/')) $url = strstr($url, '/', true);\n</code></pre>\n"
},
{
"answer_id": 22996720,
"author": "T. Brian Jones",
"author_id": 456578,
"author_profile": "https://Stackoverflow.com/users/456578",
"pm_score": 0,
"selected": false,
"text": "<p>This will generally work very well if the input URL is not total junk. It removes the subdomain.</p>\n\n<pre><code>$host = parse_url( $Row->url, PHP_URL_HOST );\n$parts = explode( '.', $host );\n$parts = array_reverse( $parts );\n$domain = $parts[1].'.'.$parts[0];\n</code></pre>\n\n<p><strong>Example</strong></p>\n\n<p>Input: <code>http://www2.website.com:8080/some/file/structure?some=parameters</code></p>\n\n<p>Output: <code>website.com</code></p>\n"
},
{
"answer_id": 24870112,
"author": "Oleg Matei",
"author_id": 2862657,
"author_profile": "https://Stackoverflow.com/users/2862657",
"pm_score": 2,
"selected": false,
"text": "<p>You can pass PHP_URL_HOST into parse_url function as second parameter</p>\n\n<pre><code>$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$host = parse_url($url, PHP_URL_HOST);\nprint $host; // prints 'google.com'\n</code></pre>\n"
},
{
"answer_id": 25348605,
"author": "NotFound Life",
"author_id": 3234197,
"author_profile": "https://Stackoverflow.com/users/3234197",
"pm_score": 1,
"selected": false,
"text": "<p>I have edited for you:</p>\n\n<pre><code>function getHost($Address) { \n $parseUrl = parse_url(trim($Address));\n $host = trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); \n\n $parts = explode( '.', $host );\n $num_parts = count($parts);\n\n if ($parts[0] == \"www\") {\n for ($i=1; $i < $num_parts; $i++) { \n $h .= $parts[$i] . '.';\n }\n }else {\n for ($i=0; $i < $num_parts; $i++) { \n $h .= $parts[$i] . '.';\n }\n }\n return substr($h,0,-1);\n}\n</code></pre>\n\n<p>All type url (www.domain.ltd, sub1.subn.domain.ltd will result to : domain.ltd.</p>\n"
},
{
"answer_id": 26532119,
"author": "Michael",
"author_id": 555343,
"author_profile": "https://Stackoverflow.com/users/555343",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$domain = parse_url($url, PHP_URL_HOST);\necho implode('.', array_slice(explode('.', $domain), -2, 2))\n</code></pre>\n"
},
{
"answer_id": 27129446,
"author": "nikmauro",
"author_id": 2078274,
"author_profile": "https://Stackoverflow.com/users/2078274",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function get_domain($url = SITE_URL)\n{\n preg_match(\"/[a-z0-9\\-]{1,63}\\.[a-z\\.]{2,6}$/\", parse_url($url, PHP_URL_HOST), $_domain_tld);\n return $_domain_tld[0];\n}\n\nget_domain('http://www.cdl.gr'); //cdl.gr\nget_domain('http://cdl.gr'); //cdl.gr\nget_domain('http://www2.cdl.gr'); //cdl.gr\n</code></pre>\n"
},
{
"answer_id": 27675712,
"author": "Md. Maruf Hossain",
"author_id": 1232912,
"author_profile": "https://Stackoverflow.com/users/1232912",
"pm_score": -1,
"selected": false,
"text": "<p>Just use as like following ...</p>\n\n<pre><code><?php\n echo $_SERVER['SERVER_NAME'];\n?>\n</code></pre>\n"
},
{
"answer_id": 37791210,
"author": "Michael Giovanni Pumo",
"author_id": 695749,
"author_profile": "https://Stackoverflow.com/users/695749",
"pm_score": 0,
"selected": false,
"text": "<p>Combining the answers of <strong>worldofjr</strong> and <strong>Alix Axel</strong> into one small function that will handle most use-cases:</p>\n\n<pre><code>function get_url_hostname($url) {\n\n $parse = parse_url($url);\n return str_ireplace('www.', '', $parse['host']);\n\n}\n\nget_url_hostname('http://www.google.com/example/path/file.html'); // google.com\n</code></pre>\n"
},
{
"answer_id": 37987242,
"author": "Oleksandr Fediashov",
"author_id": 6488546,
"author_profile": "https://Stackoverflow.com/users/6488546",
"pm_score": 3,
"selected": false,
"text": "<p>If you want extract host from string <code>http://google.com/dhasjkdas/sadsdds/sdda/sdads.html</code>, usage of parse_url() is acceptable solution for you.</p>\n\n<p>But if you want extract domain or its parts, you need package that using <a href=\"https://publicsuffix.org/\" rel=\"noreferrer\">Public Suffix List</a>. Yes, you can use string functions arround parse_url(), but it will produce incorrect results sometimes.</p>\n\n<p>I recomend <a href=\"https://github.com/layershifter/TLDExtract\" rel=\"noreferrer\">TLDExtract</a> for domain parsing, here is sample code that show diff:</p>\n\n<pre><code>$extract = new LayerShifter\\TLDExtract\\Extract();\n\n# For 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'\n\n$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n\nparse_url($url, PHP_URL_HOST); // will return google.com\n\n$result = $extract->parse($url);\n$result->getFullHost(); // will return 'google.com'\n$result->getRegistrableDomain(); // will return 'google.com'\n$result->getSuffix(); // will return 'com'\n\n# For 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html'\n\n$url = 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n\nparse_url($url, PHP_URL_HOST); // will return 'search.google.com'\n\n$result = $extract->parse($url);\n$result->getFullHost(); // will return 'search.google.com'\n$result->getRegistrableDomain(); // will return 'google.com'\n</code></pre>\n"
},
{
"answer_id": 39401781,
"author": "Andy Jones",
"author_id": 1422512,
"author_profile": "https://Stackoverflow.com/users/1422512",
"pm_score": 2,
"selected": false,
"text": "<p>I'm adding this answer late since this is the answer that pops up most on Google...</p>\n\n<p>You can use PHP to...</p>\n\n<pre><code>$url = \"www.google.co.uk\";\n$host = parse_url($url, PHP_URL_HOST);\n// $host == \"www.google.co.uk\"\n</code></pre>\n\n<p>to grab the <em>host</em> but not the <em>private domain</em> to which the host refers. (Example <code>www.google.co.uk</code> is the host, but <code>google.co.uk</code> is the private domain)</p>\n\n<p>To grab the private domain, you must need know the list of public suffixes to which one <em>can</em> register a private domain. This list happens to be curated by Mozilla at <a href=\"https://publicsuffix.org/\" rel=\"nofollow\">https://publicsuffix.org/</a></p>\n\n<p>The below code works when an array of public suffixes has been created already. Simply call</p>\n\n<pre><code>$domain = get_private_domain(\"www.google.co.uk\");\n</code></pre>\n\n<p>with the remaining code... </p>\n\n<pre><code>// find some way to parse the above list of public suffix\n// then add them to a PHP array\n$suffix = [... all valid public suffix ...];\n\nfunction get_public_suffix($host) {\n $parts = split(\"\\.\", $host);\n while (count($parts) > 0) {\n if (is_public_suffix(join(\".\", $parts)))\n return join(\".\", $parts);\n\n array_shift($parts);\n }\n\n return false;\n}\n\nfunction is_public_suffix($host) {\n global $suffix;\n return isset($suffix[$host]);\n}\n\nfunction get_private_domain($host) {\n $public = get_public_suffix($host);\n $public_parts = split(\"\\.\", $public);\n $all_parts = split(\"\\.\", $host);\n\n $private = [];\n\n for ($x = 0; $x < count($public_parts); ++$x) \n $private[] = array_pop($all_parts);\n\n if (count($all_parts) > 0)\n $private[] = array_pop($all_parts);\n\n return join(\".\", array_reverse($private));\n}\n</code></pre>\n"
},
{
"answer_id": 46145181,
"author": "fatih",
"author_id": 1112246,
"author_profile": "https://Stackoverflow.com/users/1112246",
"pm_score": 2,
"selected": false,
"text": "<p>I've found that @philfreo's solution (referenced from php.net) is pretty well to get fine result but in some cases it shows php's \"notice\" and \"Strict Standards\" message. Here a fixed version of this code.</p>\n\n<pre><code>function getHost($url) { \n $parseUrl = parse_url(trim($url)); \n if(isset($parseUrl['host']))\n {\n $host = $parseUrl['host'];\n }\n else\n {\n $path = explode('/', $parseUrl['path']);\n $host = $path[0];\n }\n return trim($host); \n} \n\necho getHost(\"http://example.com/anything.html\"); // example.com\necho getHost(\"http://www.example.net/directory/post.php\"); // www.example.net\necho getHost(\"https://example.co.uk\"); // example.co.uk\necho getHost(\"www.example.net\"); // example.net\necho getHost(\"subdomain.example.net/anything\"); // subdomain.example.net\necho getHost(\"example.net\"); // example.net\n</code></pre>\n"
},
{
"answer_id": 53990049,
"author": "Kristoffer Bohmann",
"author_id": 169224,
"author_profile": "https://Stackoverflow.com/users/169224",
"pm_score": 3,
"selected": false,
"text": "<p>Please consider replacring the accepted solution with the following:</p>\n\n<p>parse_url() will always include any sub-domain(s), so this function doesn't parse domain names very well.\nHere are some examples:</p>\n\n<pre><code>$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$parse = parse_url($url);\necho $parse['host']; // prints 'www.google.com'\n\necho parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);\n// Output: subdomain.example.com\n\necho parse_url('https://subdomain.example.co.uk/foo/bar', PHP_URL_HOST);\n// Output: subdomain.example.co.uk\n</code></pre>\n\n<p>Instead, you may consider this pragmatic solution.\nIt will cover many, but not all domain names -- for instance, lower-level domains such as 'sos.state.oh.us' are not covered.</p>\n\n<pre><code>function getDomain($url) {\n $host = parse_url($url, PHP_URL_HOST);\n\n if(filter_var($host,FILTER_VALIDATE_IP)) {\n // IP address returned as domain\n return $host; //* or replace with null if you don't want an IP back\n }\n\n $domain_array = explode(\".\", str_replace('www.', '', $host));\n $count = count($domain_array);\n if( $count>=3 && strlen($domain_array[$count-2])==2 ) {\n // SLD (example.co.uk)\n return implode('.', array_splice($domain_array, $count-3,3));\n } else if( $count>=2 ) {\n // TLD (example.com)\n return implode('.', array_splice($domain_array, $count-2,2));\n }\n}\n\n// Your domains\n echo getDomain('http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com\n echo getDomain('http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com\n echo getDomain('http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'); // google.co.uk\n\n// TLD\n echo getDomain('https://shop.example.com'); // example.com\n echo getDomain('https://foo.bar.example.com'); // example.com\n echo getDomain('https://www.example.com'); // example.com\n echo getDomain('https://example.com'); // example.com\n\n// SLD\n echo getDomain('https://more.news.bbc.co.uk'); // bbc.co.uk\n echo getDomain('https://www.bbc.co.uk'); // bbc.co.uk\n echo getDomain('https://bbc.co.uk'); // bbc.co.uk\n\n// IP\n echo getDomain('https://1.2.3.45'); // 1.2.3.45\n</code></pre>\n\n<p>Finally, Jeremy Kendall's <a href=\"https://github.com/jeremykendall/php-domain-parser\" rel=\"noreferrer\">PHP Domain Parser</a> allows you to parse the domain name from a url. <a href=\"https://uri.thephpleague.com/domain-parser/1.0/\" rel=\"noreferrer\">League URI Hostname Parser</a> will also do the job.</p>\n"
},
{
"answer_id": 60099587,
"author": "rk3263025",
"author_id": 3263025,
"author_profile": "https://Stackoverflow.com/users/3263025",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function getTrimmedUrl($link)\n{\n $str = str_replace([\"www.\",\"https://\",\"http://\"],[''],$link);\n $link = explode(\"/\",$str);\n return strtolower($link[0]); \n}\n</code></pre>\n"
},
{
"answer_id": 72008830,
"author": "Rawburner",
"author_id": 5884988,
"author_profile": "https://Stackoverflow.com/users/5884988",
"pm_score": 1,
"selected": false,
"text": "<p>None of this solutions worked for me when I use this test cases:</p>\n<pre><code>public function getTestCases(): array\n{\n return [\n //input expected\n ['http://google.com/dhasjkdas', 'google.com'],\n ['https://google.com/dhasjkdas', 'google.com'],\n ['https://www.google.com/dhasjkdas', 'google.com'],\n ['http://www.google.com/dhasjkdas', 'google.com'],\n ['www.google.com/dhasjkdas', 'google.com'],\n ['google.com/dhasjkdas', 'google.com'],\n ];\n}\n</code></pre>\n<p>but wrapping this answer into function worked in all cases: <a href=\"https://stackoverflow.com/a/65659814/5884988\">https://stackoverflow.com/a/65659814/5884988</a></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I need to build a function which parses the domain from a URL.
So, with
```
http://google.com/dhasjkdas/sadsdds/sdda/sdads.html
```
or
```
http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html
```
it should return `google.com`
with
```
http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html
```
it should return `google.co.uk`.
|
Check out [`parse_url()`](http://php.net/parse_url):
```
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
```
`parse_url` doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.
|
276,524 |
<p>In rpc.h, the GUID structure is declared as follows:</p>
<pre><code>typedef struct _GUID
{
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data[8];
} GUID;
</code></pre>
<p>I understand Data1, Data2, and Data3. They define the first, second, and third sets of hex digits when writing out a GUID (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX).</p>
<p>What I never understood was why the last 2 groups were declared together in the same byte array. Wouldn't this have made more sense (and been easier to code against)?</p>
<pre><code>typedef struct _GUID
{
DWORD Data1;
WORD Data2;
WORD Data3;
WORD Data4;
BYTE Data5[6];
} GUID;
</code></pre>
<p>Anyone know why it is declared this way?</p>
|
[
{
"answer_id": 276528,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Globally_Unique_Identifier\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Globally_Unique_Identifier</a> and <a href=\"http://www.opengroup.org/onlinepubs/9629399/apdxa.htm\" rel=\"nofollow noreferrer\">http://www.opengroup.org/onlinepubs/9629399/apdxa.htm</a> (DCE's orginal representation, you can see the grouping of <strong>bits</strong> there in a table)</p>\n"
},
{
"answer_id": 277107,
"author": "Larry Osterman",
"author_id": 761503,
"author_profile": "https://Stackoverflow.com/users/761503",
"pm_score": 5,
"selected": true,
"text": "<p>It's because a GUID is a special case of a <a href=\"http://en.wikipedia.org/wiki/UUID\" rel=\"noreferrer\">UUID</a>. For information on what all the fields mean, you can look at <a href=\"http://www.ietf.org/rfc/rfc4122.txt\" rel=\"noreferrer\">RFC 4122</a>.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14972/"
] |
In rpc.h, the GUID structure is declared as follows:
```
typedef struct _GUID
{
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data[8];
} GUID;
```
I understand Data1, Data2, and Data3. They define the first, second, and third sets of hex digits when writing out a GUID (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX).
What I never understood was why the last 2 groups were declared together in the same byte array. Wouldn't this have made more sense (and been easier to code against)?
```
typedef struct _GUID
{
DWORD Data1;
WORD Data2;
WORD Data3;
WORD Data4;
BYTE Data5[6];
} GUID;
```
Anyone know why it is declared this way?
|
It's because a GUID is a special case of a [UUID](http://en.wikipedia.org/wiki/UUID). For information on what all the fields mean, you can look at [RFC 4122](http://www.ietf.org/rfc/rfc4122.txt).
|
276,531 |
<p>If I have the LINQ objects:</p>
<pre><code>public class SampleDataContext : DataContext {
public Table<Customer> Customers { get { return this.GetTable<Customer>(); } }
public SampleDataContext( string connectionString ) : base( connectionString ) { }
}
[Table( Name="dbo.tblCustomers" )]
public class Customer {
private Guid? customerID;
[Column( Storage="customerID", DbType="uniqueidentifier NOT NULL", IsPrimaryKey=true )]
public Guid? CustomerID {
get { return this.customerID; }
set { this.customerID = value; }
}
private string customerName;
[Column( Storage = "customerName", DbType = "nvarchar(255) NOT NULL" )]
public string CustomerName {
get { return this.customerName; }
set { this.customerName = value; }
}
}
</code></pre>
<p>and somewhere else in application:</p>
<pre><code>public static void DoSomethingWithCustomer( Customer customer ) {
// some operations
// now, I want save changes to the database
}
</code></pre>
<p>how can I get instance of DataContext which tracks changes of the "customer" object?</p>
<p><strong>Edit: Why I don't want pass the DataContext into method.</strong></p>
<p>1) Passing always 2 objects instead of 1 is "ugly" pattern for whole application.</p>
<ul>
<li>Methods will need next parameter for every business object.</li>
<li>Collection will needs changed from "List" to "List>".</li>
</ul>
<p>Both points will more hard to maintain - developer must every-time sets the correct instance of DataContext (easy to create a bug), despite the DataContext know that the concrete object is(or not) attached to another DataContext.</p>
<p>2) I want (current version of application use it) process "any" business logic on collection of objects which came from different "places" ( floating windows by drag & drop for example ).</p>
<p>Currentyl we use custom typed DataSets, so informations about changes are in the data rows (DataRow = business object) and wasn't problem to get it, or create a clone and then save it into database.</p>
|
[
{
"answer_id": 276536,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest thing to do is to pass the DataContext into your method.</p>\n\n<p>However, you may also consider changing your design so that you follow the rule that \"a single method should have only one purpose\", in which case you wouldn't want to \"Save\" in the same method that you \"Modify\".</p>\n"
},
{
"answer_id": 276537,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Part of the fun of <a href=\"http://en.wikipedia.org/wiki/Plain_Old_CLR_Object\" rel=\"nofollow noreferrer\">POCO</a> is that you can't be sure that the object <em>knows</em> who is tracking him. If the object has data-aware / lazy-loading properties, then you <em>might</em> be able to trace the context via reflection, but in reality this would be a mess. It would be far cleaner to simply pass the data-context to the code that needs it.</p>\n"
},
{
"answer_id": 986109,
"author": "Mark",
"author_id": 64084,
"author_profile": "https://Stackoverflow.com/users/64084",
"pm_score": 4,
"selected": true,
"text": "<p>Kevin - I feel your pain... when you are building business logic around your business objects, there are times when you simply <em>have</em> to have access to the DataContext to which an object belongs, since not knowing the DataContext menas having to put your code in places that reduce the maintainability of your code.</p>\n<p>I wrote the following code (VB, I'm afraid), which presents a Context property which can be placed onto a data object, and then used to return the DataContext (if any) that the object is attached to.</p>\n<pre><code>Private Const StandardChangeTrackerName As String = "System.Data.Linq.ChangeTracker+StandardChangeTracker"\n\nPrivate _context As DataClasses1DataContext\nPublic Property Context() As DataClasses1DataContext\n Get\n Dim hasContext As Boolean = False\n Dim myType As Type = Me.GetType()\n Dim propertyChangingField As FieldInfo = myType.GetField("PropertyChangingEvent", BindingFlags.NonPublic Or BindingFlags.Instance)\n Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me)\n Dim delegateType As Type = Nothing\n\n For Each thisDelegate In propertyChangingDelegate.GetInvocationList()\n delegateType = thisDelegate.Target.GetType()\n If delegateType.FullName.Equals(StandardChangeTrackerName) Then\n propertyChangingDelegate = thisDelegate\n hasContext = True\n Exit For\n End If\n Next\n\n If hasContext Then\n Dim targetField = propertyChangingDelegate.Target\n Dim servicesField As FieldInfo = targetField.GetType().GetField("services", BindingFlags.NonPublic Or BindingFlags.Instance)\n If servicesField IsNot Nothing Then\n\n Dim servicesObject = servicesField.GetValue(targetField)\n\n Dim contextField As FieldInfo = servicesObject.GetType.GetField("context", BindingFlags.NonPublic Or BindingFlags.Instance)\n\n _context = contextField.GetValue(servicesObject)\n\n End If\n End If\n \n Return _context\n End Get\n Set(ByVal value As DataClasses1DataContext)\n\n _context = value\n\n End Set\n\nEnd Property\n</code></pre>\n<p>Here is a C# version:</p>\n<pre><code>public DataContext GetMyDataContext()\n{\n // Find the StandardChangeTracker listening to property changes on this object.\n // If no StandardChangeTracker is listening, then this object is probably not\n // attached to a data context.\n var eventField = this.GetType().GetField("PropertyChangingEvent", BindingFlags.NonPublic | BindingFlags.Instance);\n var eventDelegate = eventField.GetValue(this) as Delegate;\n if (eventDelegate == null)\n return null;\n eventDelegate = eventDelegate.GetInvocationList().FirstOrDefault(\n del => del.Target.GetType().FullName == "System.Data.Linq.ChangeTracker+StandardChangeTracker");\n if (eventDelegate == null)\n return null;\n\n // Dig through the objects to get the underlying DataContext.\n // If the following fails, then there was most likely an internal change\n // to the LINQ-to-SQL framework classes.\n var targetField = eventDelegate.Target;\n var servicesField = targetField.GetType().GetField("services", BindingFlags.NonPublic | BindingFlags.Instance);\n var servicesObject = servicesField.GetValue(targetField);\n var contextField = servicesObject.GetType().GetField("context", BindingFlags.NonPublic | BindingFlags.Instance);\n return (DataContext)contextField.GetValue(servicesObject);\n}\n</code></pre>\n<p>Take care to note that the object can only locate it's DataContext if it is currently attached to the context with ChangeTracking switched on. This property relies on the fact that the DataContext has subscribed to the object's OnPropertyChanging event to monitor changes over the lifespan of the object.</p>\n<p>If this was helpful, please up-vote this post.</p>\n<p>For more info on using reflection to find event handlers:</p>\n<ul>\n<li><a href=\"https://weblogs.asp.net/avnerk/reflecting-over-an-event\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/avnerk/archive/2007/03/29/reflecting-over-an-event.aspx</a></li>\n<li><a href=\"https://web.archive.org/web/20131213074318/http://bobpowell.net/eventsubscribers.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20131213074318/http://bobpowell.net/eventsubscribers.aspx</a></li>\n</ul>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20382/"
] |
If I have the LINQ objects:
```
public class SampleDataContext : DataContext {
public Table<Customer> Customers { get { return this.GetTable<Customer>(); } }
public SampleDataContext( string connectionString ) : base( connectionString ) { }
}
[Table( Name="dbo.tblCustomers" )]
public class Customer {
private Guid? customerID;
[Column( Storage="customerID", DbType="uniqueidentifier NOT NULL", IsPrimaryKey=true )]
public Guid? CustomerID {
get { return this.customerID; }
set { this.customerID = value; }
}
private string customerName;
[Column( Storage = "customerName", DbType = "nvarchar(255) NOT NULL" )]
public string CustomerName {
get { return this.customerName; }
set { this.customerName = value; }
}
}
```
and somewhere else in application:
```
public static void DoSomethingWithCustomer( Customer customer ) {
// some operations
// now, I want save changes to the database
}
```
how can I get instance of DataContext which tracks changes of the "customer" object?
**Edit: Why I don't want pass the DataContext into method.**
1) Passing always 2 objects instead of 1 is "ugly" pattern for whole application.
* Methods will need next parameter for every business object.
* Collection will needs changed from "List" to "List>".
Both points will more hard to maintain - developer must every-time sets the correct instance of DataContext (easy to create a bug), despite the DataContext know that the concrete object is(or not) attached to another DataContext.
2) I want (current version of application use it) process "any" business logic on collection of objects which came from different "places" ( floating windows by drag & drop for example ).
Currentyl we use custom typed DataSets, so informations about changes are in the data rows (DataRow = business object) and wasn't problem to get it, or create a clone and then save it into database.
|
Kevin - I feel your pain... when you are building business logic around your business objects, there are times when you simply *have* to have access to the DataContext to which an object belongs, since not knowing the DataContext menas having to put your code in places that reduce the maintainability of your code.
I wrote the following code (VB, I'm afraid), which presents a Context property which can be placed onto a data object, and then used to return the DataContext (if any) that the object is attached to.
```
Private Const StandardChangeTrackerName As String = "System.Data.Linq.ChangeTracker+StandardChangeTracker"
Private _context As DataClasses1DataContext
Public Property Context() As DataClasses1DataContext
Get
Dim hasContext As Boolean = False
Dim myType As Type = Me.GetType()
Dim propertyChangingField As FieldInfo = myType.GetField("PropertyChangingEvent", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me)
Dim delegateType As Type = Nothing
For Each thisDelegate In propertyChangingDelegate.GetInvocationList()
delegateType = thisDelegate.Target.GetType()
If delegateType.FullName.Equals(StandardChangeTrackerName) Then
propertyChangingDelegate = thisDelegate
hasContext = True
Exit For
End If
Next
If hasContext Then
Dim targetField = propertyChangingDelegate.Target
Dim servicesField As FieldInfo = targetField.GetType().GetField("services", BindingFlags.NonPublic Or BindingFlags.Instance)
If servicesField IsNot Nothing Then
Dim servicesObject = servicesField.GetValue(targetField)
Dim contextField As FieldInfo = servicesObject.GetType.GetField("context", BindingFlags.NonPublic Or BindingFlags.Instance)
_context = contextField.GetValue(servicesObject)
End If
End If
Return _context
End Get
Set(ByVal value As DataClasses1DataContext)
_context = value
End Set
End Property
```
Here is a C# version:
```
public DataContext GetMyDataContext()
{
// Find the StandardChangeTracker listening to property changes on this object.
// If no StandardChangeTracker is listening, then this object is probably not
// attached to a data context.
var eventField = this.GetType().GetField("PropertyChangingEvent", BindingFlags.NonPublic | BindingFlags.Instance);
var eventDelegate = eventField.GetValue(this) as Delegate;
if (eventDelegate == null)
return null;
eventDelegate = eventDelegate.GetInvocationList().FirstOrDefault(
del => del.Target.GetType().FullName == "System.Data.Linq.ChangeTracker+StandardChangeTracker");
if (eventDelegate == null)
return null;
// Dig through the objects to get the underlying DataContext.
// If the following fails, then there was most likely an internal change
// to the LINQ-to-SQL framework classes.
var targetField = eventDelegate.Target;
var servicesField = targetField.GetType().GetField("services", BindingFlags.NonPublic | BindingFlags.Instance);
var servicesObject = servicesField.GetValue(targetField);
var contextField = servicesObject.GetType().GetField("context", BindingFlags.NonPublic | BindingFlags.Instance);
return (DataContext)contextField.GetValue(servicesObject);
}
```
Take care to note that the object can only locate it's DataContext if it is currently attached to the context with ChangeTracking switched on. This property relies on the fact that the DataContext has subscribed to the object's OnPropertyChanging event to monitor changes over the lifespan of the object.
If this was helpful, please up-vote this post.
For more info on using reflection to find event handlers:
* [http://weblogs.asp.net/avnerk/archive/2007/03/29/reflecting-over-an-event.aspx](https://weblogs.asp.net/avnerk/reflecting-over-an-event)
* <https://web.archive.org/web/20131213074318/http://bobpowell.net/eventsubscribers.aspx>
|
276,546 |
<p>Let's say you have a text file like this one:
<a href="http://www.gutenberg.org/files/17921/17921-8.txt" rel="noreferrer">http://www.gutenberg.org/files/17921/17921-8.txt</a></p>
<p>Does anyone has a good algorithm, or open-source code, to extract words from a text file?
How to get all the words, while avoiding special characters, and keeping things like "it's", etc...</p>
<p>I'm working in Java.
Thanks</p>
|
[
{
"answer_id": 276554,
"author": "GurdeepS",
"author_id": 32484,
"author_profile": "https://Stackoverflow.com/users/32484",
"pm_score": 0,
"selected": false,
"text": "<p>You could try regex, using a pattern you've made, and run a count the number of times that pattern has been found.</p>\n"
},
{
"answer_id": 276559,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>Pseudocode would look like this:</p>\n\n<pre><code>create words, a list of words, by splitting the input by whitespace\nfor every word, strip out whitespace and punctuation on the left and the right\n</code></pre>\n\n<p>The python code would be something like this:</p>\n\n<pre><code>words = input.split()\nwords = [word.strip(PUNCTUATION) for word in words]\n</code></pre>\n\n<p>where</p>\n\n<pre><code>PUNCTUATION = \",. \\n\\t\\\\\\\"'][#*:\"\n</code></pre>\n\n<p>or any other characters you want to remove.</p>\n\n<p>I believe Java has equivalent functions in the String class: <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html\" rel=\"nofollow noreferrer\">String</a>.split() . </p>\n\n<hr>\n\n<p>Output of running this code on the text you provided in your link:</p>\n\n<pre><code>>>> print words[:100]\n['Project', \"Gutenberg's\", 'Manual', 'of', 'Surgery', 'by', 'Alexis', \n'Thomson', 'and', 'Alexander', 'Miles', 'This', 'eBook', 'is', 'for', \n'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no', 'cost', 'and', \n'with', 'almost', 'no', 'restrictions', 'whatsoever', 'You', 'may', \n'copy', 'it', 'give', 'it', 'away', 'or', 're-use', 'it', 'under', \n... etc etc.\n</code></pre>\n"
},
{
"answer_id": 276568,
"author": "Ed Marty",
"author_id": 36007,
"author_profile": "https://Stackoverflow.com/users/36007",
"pm_score": 1,
"selected": false,
"text": "<p>Basically, you want to match</p>\n\n<p>([A-Za-z])+('([A-Za-z])*)?</p>\n\n<p>right?</p>\n"
},
{
"answer_id": 276569,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>This sounds like the right job for regular expressions. Here is some Java code to give you an idea, in case you don't know how to start:</p>\n\n<pre><code>String input = \"Input text, with words, punctuation, etc. Well, it's rather short.\";\nPattern p = Pattern.compile(\"[\\\\w']+\");\nMatcher m = p.matcher(input);\n\nwhile ( m.find() ) {\n System.out.println(input.substring(m.start(), m.end()));\n}\n</code></pre>\n\n<p>The pattern <code>[\\w']+</code> matches all word characters, and the apostrophe, multiple times. The example string would be printed word-by-word. Have a look at the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\" rel=\"noreferrer\">Java Pattern class documentation</a> to read more.</p>\n"
},
{
"answer_id": 11898071,
"author": "Rafael Frost",
"author_id": 1344860,
"author_profile": "https://Stackoverflow.com/users/1344860",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a good approach to your problem:\nThis function receives your text as an input and returns an array of all the words inside the given text</p>\n\n<pre><code>private ArrayList<String> get_Words(String SInput){\n\n StringBuilder stringBuffer = new StringBuilder(SInput);\n ArrayList<String> all_Words_List = new ArrayList<String>();\n\n String SWord = \"\";\n for(int i=0; i<stringBuffer.length(); i++){\n Character charAt = stringBuffer.charAt(i);\n if(Character.isAlphabetic(charAt) || Character.isDigit(charAt)){\n SWord = SWord + charAt;\n }\n else{\n if(!SWord.isEmpty()) all_Words_List.add(new String(SWord));\n SWord = \"\";\n }\n\n }\n\n return all_Words_List;\n\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25645/"
] |
Let's say you have a text file like this one:
<http://www.gutenberg.org/files/17921/17921-8.txt>
Does anyone has a good algorithm, or open-source code, to extract words from a text file?
How to get all the words, while avoiding special characters, and keeping things like "it's", etc...
I'm working in Java.
Thanks
|
This sounds like the right job for regular expressions. Here is some Java code to give you an idea, in case you don't know how to start:
```
String input = "Input text, with words, punctuation, etc. Well, it's rather short.";
Pattern p = Pattern.compile("[\\w']+");
Matcher m = p.matcher(input);
while ( m.find() ) {
System.out.println(input.substring(m.start(), m.end()));
}
```
The pattern `[\w']+` matches all word characters, and the apostrophe, multiple times. The example string would be printed word-by-word. Have a look at the [Java Pattern class documentation](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) to read more.
|
276,555 |
<p>I'm looking to implement something in Java along the lines of:</p>
<pre><code>class Foo{
private int lorem; //
private int ipsum;
public setAttribute(String attr, int val){
//sets attribute based on name
}
public static void main(String [] args){
Foo f = new Foo();
f.setAttribute("lorem",1);
f.setAttribute("ipsum",2);
}
public Foo(){}
}
</code></pre>
<p>...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?</p>
|
[
{
"answer_id": 276561,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>In general, you want to use Reflection. Here is a good introduction to the <a href=\"http://web.archive.org/web/20081218060124/http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html\" rel=\"nofollow noreferrer\">topic with examples</a></p>\n\n<p>In particular, the \"Changing Values of Fields\" section describes how to do what you'd like to do.</p>\n\n<p>I note that the author says, \"This feature is extremely powerful and has no equivalent in other conventional languages.\" Of course, in the last ten years (the article was written in 1998) we have seen great strides made in dynamic languages. The above is fairly easily done in Perl, Python, PHP, Ruby, and so on. I suspect this is the direction you might have come from based on the \"eval\" tag.</p>\n"
},
{
"answer_id": 276572,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>Also, take a look at <a href=\"http://commons.apache.org/beanutils/\" rel=\"nofollow noreferrer\">BeanUtils</a> which can hide some of the complexity of using reflection from you.</p>\n"
},
{
"answer_id": 276576,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "<p>Here's how you might implement <code>setAttribute</code> using reflection (I've renamed the function; there are different reflection functions for different field types):</p>\n\n<pre><code>public void setIntField(String fieldName, int value)\n throws NoSuchFieldException, IllegalAccessException {\n Field field = getClass().getDeclaredField(fieldName);\n field.setInt(this, value);\n}\n</code></pre>\n"
},
{
"answer_id": 276653,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p>You might want to cache some of the reflection data while you're at it:</p>\n\n<pre><code>import java.lang.reflect.Field;\nimport java.util.HashMap;\n\nclass Foo {\n private HashMap<String, Field> fields = new HashMap<String, Field>();\n\n private void setAttribute(Field field, Object value) {\n field.set(this, value);\n }\n\n public void setAttribute(String fieldName, Object value) {\n if (!fields.containsKey(fieldName)) {\n fields.put(fieldName, value);\n }\n setAttribute(fields.get(fieldName), value);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 277442,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on the usage, you can use reflection as advised above, or perhaps a HashMap would be better suited...</p>\n"
},
{
"answer_id": 30310215,
"author": "Brian Risk",
"author_id": 2595659,
"author_profile": "https://Stackoverflow.com/users/2595659",
"pm_score": 2,
"selected": false,
"text": "<p>The question is specific to ints, which is helpful, however here is something a bit more general. This type of method is useful if you are loading in <code>String</code> representations of field name / field value pairs.</p>\n\n<pre><code>import java.lang.reflect.Field;\n\npublic class FieldTest {\n\n static boolean isValid = false;\n static int count = 5;\n\n public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {\n FieldTest test = new FieldTest();\n test.setProperty(\"count\", \"24\");\n System.out.println(count);\n test.setProperty(\"isValid\", \"true\");\n System.out.println(isValid);\n }\n\n public void setProperty(String fieldName, String value) throws NoSuchFieldException, IllegalAccessException {\n Field field = this.getClass().getDeclaredField(fieldName);\n if (field.getType() == Character.TYPE) {field.set(getClass(), value.charAt(0)); return;}\n if (field.getType() == Short.TYPE) {field.set(getClass(), Short.parseShort(value)); return;}\n if (field.getType() == Integer.TYPE) {field.set(getClass(), Integer.parseInt(value)); return;}\n if (field.getType() == Long.TYPE) {field.set(getClass(), Long.parseLong(value)); return;}\n if (field.getType() == Float.TYPE) {field.set(getClass(), Float.parseFloat(value)); return;}\n if (field.getType() == Double.TYPE) {field.set(getClass(), Double.parseDouble(value)); return;}\n if (field.getType() == Byte.TYPE) {field.set(getClass(), Byte.parseByte(value)); return;}\n if (field.getType() == Boolean.TYPE) {field.set(getClass(), Boolean.parseBoolean(value)); return;}\n field.set(getClass(), value);\n }\n\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25985/"
] |
I'm looking to implement something in Java along the lines of:
```
class Foo{
private int lorem; //
private int ipsum;
public setAttribute(String attr, int val){
//sets attribute based on name
}
public static void main(String [] args){
Foo f = new Foo();
f.setAttribute("lorem",1);
f.setAttribute("ipsum",2);
}
public Foo(){}
}
```
...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?
|
Here's how you might implement `setAttribute` using reflection (I've renamed the function; there are different reflection functions for different field types):
```
public void setIntField(String fieldName, int value)
throws NoSuchFieldException, IllegalAccessException {
Field field = getClass().getDeclaredField(fieldName);
field.setInt(this, value);
}
```
|
276,575 |
<p>I am trying to migrate my .net remoting code to wcf but I'm finding it difficult. Can someone help me migrate this simple Remoting based program below to use WCF? The program implements a simple publisher/subscriber pattern where we have a single TemperatureProviderProgram that publishers to many TemperatureSubcriberPrograms that subcribe to the TemperatureProvider.</p>
<p>To run the programs:</p>
<ol>
<li>Copy the TemperatureProviderProgram and TemperatureSubcriberProgram into seperate console application projects.</li>
<li>Copying to remaining classes and interfaces into a common Class Library project then add a reference to System.Runtime.Remoting library</li>
<li>Add a reference to the Class Library project from the console app projects.</li>
<li>Complie and run 1 TemperatureProviderProgram and multiple TemperatureSubcriberProgram.</li>
</ol>
<p>Please note no IIS or xml should be used. Thanks in advance.</p>
<pre><code>public interface ITemperatureProvider
{
void Subcribe(ObjRef temperatureSubcriber);
}
[Serializable]
public sealed class TemperatureProvider : MarshalByRefObject, ITemperatureProvider
{
private readonly List<ITemperatureSubcriber> _temperatureSubcribers = new List<ITemperatureSubcriber>();
private readonly Random randomTemperature = new Random();
public void Subcribe(ObjRef temperatureSubcriber)
{
ITemperatureSubcriber tempSubcriber = (ITemperatureSubcriber)RemotingServices.Unmarshal(temperatureSubcriber);
lock (_temperatureSubcribers)
{
_temperatureSubcribers.Add(tempSubcriber);
}
}
public void Start()
{
Console.WriteLine("TemperatureProvider started...");
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
TcpServerChannel tcpChannel = new TcpServerChannel("TemperatureProviderChannel", 5001, provider);
ChannelServices.RegisterChannel(tcpChannel, false);
RemotingServices.Marshal(this, "TemperatureProvider", typeof(ITemperatureProvider));
while (true)
{
double nextTemp = randomTemperature.NextDouble();
lock (_temperatureSubcribers)
{
foreach (var item in _temperatureSubcribers)
{
try
{
item.OnTemperature(nextTemp);
}
catch (SocketException)
{}
catch(RemotingException)
{}
}
}
Thread.Sleep(200);
}
}
}
public interface ITemperatureSubcriber
{
void OnTemperature(double temperature);
}
[Serializable]
public sealed class TemperatureSubcriber : MarshalByRefObject, ITemperatureSubcriber
{
private ObjRef _clientRef;
private readonly Random portGen = new Random();
public void OnTemperature(double temperature)
{
Console.WriteLine(temperature);
}
public override object InitializeLifetimeService()
{
return null;
}
public void Start()
{
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
int port = portGen.Next(1, 65535);
TcpServerChannel tcpChannel = new TcpServerChannel(string.Format("TemperatureSubcriber_{0}", Guid.NewGuid()), port, provider);
ChannelServices.RegisterChannel(tcpChannel, false);
ITemperatureProvider p1 = (ITemperatureProvider)RemotingServices.Connect(typeof(ITemperatureProvider), "tcp://localhost:5001/TemperatureProvider");
_clientRef = RemotingServices.Marshal(this, string.Format("TemperatureSubcriber_{0}_{1}.rem", Environment.MachineName, Guid.NewGuid()));
p1.Subcribe(_clientRef);
}
}
public class TemperatureProviderProgram
{
static void Main(string[] args)
{
TemperatureProvider tp = new TemperatureProvider();
tp.Start();
}
}
public class TemperatureSubcriberProgram
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start TemperatureSubcriber.");
Console.ReadLine();
TemperatureSubcriber ts = new TemperatureSubcriber();
ts.Start();
Console.ReadLine();
}
}
</code></pre>
|
[
{
"answer_id": 277405,
"author": "Alexandre Brisebois",
"author_id": 18619,
"author_profile": "https://Stackoverflow.com/users/18619",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to modify your logic a bit. If you want to migrate this app to <code>WCF</code>. You will need to have clients pull data from the service at regular intervals.</p>\n\n<p>You will also need a Windows service or application to host the <code>WCF</code> like the console you are using in the previous code.</p>\n"
},
{
"answer_id": 277406,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>In WCF, with a \"push\" from the server you're really talking about duplex comms; the <code>MarshalByRefObject</code> is largely redundant here (AFAIK). The page <a href=\"http://msdn.microsoft.com/en-us/library/ms735103.aspx\" rel=\"nofollow noreferrer\">here</a> discusses various scenarios, including duplex/callbacks.</p>\n\n<p>If the issue is xml (for some philosophical reason), then simply using <code>NetDataContractSerializer</code> rather than <code>DataContractSerializer</code> might help.</p>\n\n<p>The other approach is to have the clients \"pull\" data periodically; this works well if you need to support basic http, etc.</p>\n"
},
{
"answer_id": 277845,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well I build real time systems so polling is not an option - I need to push data.</p>\n\n<p>Also I am finding there is no WCF equivalent of System.Runtime.Remoting.ObjRef! This is an extremely useful type that encapsulates a service endpoint and can be serialise and passed around the network to other remoting service. </p>\n\n<p>Think I’ll be sticking with good old remoting until the ObjRef equivalent is introduced.</p>\n"
},
{
"answer_id": 359542,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What it sounds like you want to do is use WCF NetTcpBinding with Callbacks.</p>\n\n<p>Take a look at this: <a href=\"http://www.codeproject.com/KB/WCF/publisher_subscriber.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/WCF/publisher_subscriber.aspx</a></p>\n\n<p>\"Learning WCF\" by Michele Bustamante is also very good. You can get Chpt1 for VS2008 at her website along with the code for the book. Chpt1 will explain/demo setting up connections and such. She also has downloadable sample code. One of the Samples is a DuplexPublishSubscribe.</p>\n"
},
{
"answer_id": 424325,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it is true, just one correction..\nObjRefs are created automatically when any MarshalByRefObject derived object is going outside the appdomain. \nSo in this case your ITemperatureProvider interface Subscribe method shoud take ITemperatureSubscriber instead of objref.\nAnd then on client side just call p1.Subscribe(this) and the remoting layer will generate ObjRef from the object that will be serialized and sent. (sending b reference)</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to migrate my .net remoting code to wcf but I'm finding it difficult. Can someone help me migrate this simple Remoting based program below to use WCF? The program implements a simple publisher/subscriber pattern where we have a single TemperatureProviderProgram that publishers to many TemperatureSubcriberPrograms that subcribe to the TemperatureProvider.
To run the programs:
1. Copy the TemperatureProviderProgram and TemperatureSubcriberProgram into seperate console application projects.
2. Copying to remaining classes and interfaces into a common Class Library project then add a reference to System.Runtime.Remoting library
3. Add a reference to the Class Library project from the console app projects.
4. Complie and run 1 TemperatureProviderProgram and multiple TemperatureSubcriberProgram.
Please note no IIS or xml should be used. Thanks in advance.
```
public interface ITemperatureProvider
{
void Subcribe(ObjRef temperatureSubcriber);
}
[Serializable]
public sealed class TemperatureProvider : MarshalByRefObject, ITemperatureProvider
{
private readonly List<ITemperatureSubcriber> _temperatureSubcribers = new List<ITemperatureSubcriber>();
private readonly Random randomTemperature = new Random();
public void Subcribe(ObjRef temperatureSubcriber)
{
ITemperatureSubcriber tempSubcriber = (ITemperatureSubcriber)RemotingServices.Unmarshal(temperatureSubcriber);
lock (_temperatureSubcribers)
{
_temperatureSubcribers.Add(tempSubcriber);
}
}
public void Start()
{
Console.WriteLine("TemperatureProvider started...");
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
TcpServerChannel tcpChannel = new TcpServerChannel("TemperatureProviderChannel", 5001, provider);
ChannelServices.RegisterChannel(tcpChannel, false);
RemotingServices.Marshal(this, "TemperatureProvider", typeof(ITemperatureProvider));
while (true)
{
double nextTemp = randomTemperature.NextDouble();
lock (_temperatureSubcribers)
{
foreach (var item in _temperatureSubcribers)
{
try
{
item.OnTemperature(nextTemp);
}
catch (SocketException)
{}
catch(RemotingException)
{}
}
}
Thread.Sleep(200);
}
}
}
public interface ITemperatureSubcriber
{
void OnTemperature(double temperature);
}
[Serializable]
public sealed class TemperatureSubcriber : MarshalByRefObject, ITemperatureSubcriber
{
private ObjRef _clientRef;
private readonly Random portGen = new Random();
public void OnTemperature(double temperature)
{
Console.WriteLine(temperature);
}
public override object InitializeLifetimeService()
{
return null;
}
public void Start()
{
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
int port = portGen.Next(1, 65535);
TcpServerChannel tcpChannel = new TcpServerChannel(string.Format("TemperatureSubcriber_{0}", Guid.NewGuid()), port, provider);
ChannelServices.RegisterChannel(tcpChannel, false);
ITemperatureProvider p1 = (ITemperatureProvider)RemotingServices.Connect(typeof(ITemperatureProvider), "tcp://localhost:5001/TemperatureProvider");
_clientRef = RemotingServices.Marshal(this, string.Format("TemperatureSubcriber_{0}_{1}.rem", Environment.MachineName, Guid.NewGuid()));
p1.Subcribe(_clientRef);
}
}
public class TemperatureProviderProgram
{
static void Main(string[] args)
{
TemperatureProvider tp = new TemperatureProvider();
tp.Start();
}
}
public class TemperatureSubcriberProgram
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start TemperatureSubcriber.");
Console.ReadLine();
TemperatureSubcriber ts = new TemperatureSubcriber();
ts.Start();
Console.ReadLine();
}
}
```
|
You will need to modify your logic a bit. If you want to migrate this app to `WCF`. You will need to have clients pull data from the service at regular intervals.
You will also need a Windows service or application to host the `WCF` like the console you are using in the previous code.
|
276,585 |
<p>In vs2008, is it possible to write an extension methods which would apply to any enumeration.</p>
<p>I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?</p>
|
[
{
"answer_id": 276589,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, just code against the base <code>Enum</code> type, e.g.</p>\n\n<pre><code>public static void Something(this Enum e)\n{\n // code here\n}\n</code></pre>\n\n<p>The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.getunderlyingtype.aspx\" rel=\"noreferrer\"><code>Enum.GetUnderlyingType</code></a>, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have <code>IsOneOf</code> and <code>IsCombinationOf</code> methods that apply to all enums).</p>\n\n<p>PS: Remember when writing the method that, although ill advised, you can use <code>float</code> and <code>double</code> as the base types for enums so you'll need some special cases for those as well as unsigned values.</p>\n"
},
{
"answer_id": 276600,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, you can. The target extenstion type is of type <code>Enum</code>. In C#, this would be done as:</p>\n\n<pre><code>public static void EnumExtension(this Enum e)\n{\n}\n</code></pre>\n\n<p>or like this in VB:</p>\n\n<pre><code><Extension()> _\nPublic Sub EnumExtension(ByVal s As Enum)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 1010107,
"author": "Michael La Voie",
"author_id": 65843,
"author_profile": "https://Stackoverflow.com/users/65843",
"pm_score": 4,
"selected": false,
"text": "<p>FYI Here is a great example of an Enum Extension method that I have been able to use. It implements a case insensitive TryParse() function for enums:</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static bool TryParse<T>(this Enum theEnum, string strType, \n out T result)\n {\n string strTypeFixed = strType.Replace(' ', '_');\n if (Enum.IsDefined(typeof(T), strTypeFixed))\n {\n result = (T)Enum.Parse(typeof(T), strTypeFixed, true);\n return true;\n }\n else\n {\n foreach (string value in Enum.GetNames(typeof(T)))\n {\n if (value.Equals(strTypeFixed, \n StringComparison.OrdinalIgnoreCase))\n {\n result = (T)Enum.Parse(typeof(T), value);\n return true;\n }\n }\n result = default(T);\n return false;\n }\n }\n}\n</code></pre>\n\n<p>You would use it in the following manner:</p>\n\n<pre><code>public enum TestEnum\n{\n A,\n B,\n C\n}\n\npublic void TestMethod(string StringOfEnum)\n{\n TestEnum myEnum;\n myEnum.TryParse(StringOfEnum, out myEnum);\n}\n</code></pre>\n\n<p>Here are the two sites that I visited to help come up with this code:</p>\n\n<p><a href=\"http://mironabramson.com/blog/post/2008/03/Another-version-for-the-missing-method-EnumTryParse.aspx\" rel=\"noreferrer\">Case Insensitive TryParse for Enums</a></p>\n\n<p><a href=\"http://www.objectreference.net/post/Enum-TryParse-Extension-Method.aspx\" rel=\"noreferrer\">Extension methods for Enums</a></p>\n"
},
{
"answer_id": 8830545,
"author": "Adriaan de Beer",
"author_id": 1144750,
"author_profile": "https://Stackoverflow.com/users/1144750",
"pm_score": 3,
"selected": false,
"text": "<p>Here's another example - also nicer IMHO than having to create and initialize a temp variable.</p>\n\n<pre><code>public static class ExtensionMethods \n{\n public static void ForEach(this Enum enumType, Action<Enum> action)\n {\n foreach (var type in Enum.GetValues(enumType.GetType()))\n {\n action((Enum)type);\n }\n }\n}\n\npublic enum TestEnum { A,B,C } \npublic void TestMethod() \n{\n default(TestEnum).ForEach(Console.WriteLine); \n} \n</code></pre>\n"
},
{
"answer_id": 11191138,
"author": "Koray Bayram",
"author_id": 846384,
"author_profile": "https://Stackoverflow.com/users/846384",
"pm_score": 2,
"selected": false,
"text": "<p>You can also implement conversion method as follows:</p>\n\n<pre><code>public static class Extensions\n{\n public static ConvertType Convert<ConvertType>(this Enum e)\n {\n object o = null;\n Type type = typeof(ConvertType);\n\n if (type == typeof(int))\n {\n o = Convert.ToInt32(e);\n }\n else if (type == typeof(long))\n {\n o = Convert.ToInt64(e);\n }\n else if (type == typeof(short))\n {\n o = Convert.ToInt16(e);\n }\n else\n {\n o = Convert.ToString(e);\n }\n\n return (ConvertType)o;\n }\n}\n</code></pre>\n\n<p>Here is an example usage:</p>\n\n<pre><code>int a = MyEnum.A.Convert<int>();\n</code></pre>\n"
},
{
"answer_id": 19707946,
"author": "Esge",
"author_id": 2190520,
"author_profile": "https://Stackoverflow.com/users/2190520",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes there is a need to convert from one enum to another, based on the name or value of the enum. Here is how it can be done nicely with extension methods:</p>\n\n<pre><code>enum Enum1 { One = 1, Two = 2, Three = 3 };\nenum Enum2 { Due = 2, Uno = 1 };\nenum Enum3 { Two, One };\n\nEnum2 e2 = Enum1.One.ConvertByValue<Enum2>();\nEnum3 e3 = Enum1.One.ConvertByName<Enum3>();\nEnum3 x2 = Enum1.Three.ConvertByValue<Enum3>();\n\npublic static class EnumConversionExtensions\n{\n public static T ConvertByName<T>(this Enum value)\n {\n return (T)Enum.Parse(typeof(T), Enum.GetName(value.GetType(), value));\n }\n\n public static T ConvertByValue<T>(this Enum value)\n {\n return (T)((dynamic)((int)((object)value)));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31527513,
"author": "Bronek",
"author_id": 769465,
"author_profile": "https://Stackoverflow.com/users/769465",
"pm_score": 1,
"selected": false,
"text": "<p>Another example of making Enum extension - but this time it returns the input enum type.</p>\n\n<pre><code>public static IEnumerable<T> toElementsCollection<T>(this T value) where T : struct, IConvertible\n {\n if (typeof(T).IsEnum == false) throw new Exception(\"typeof(T).IsEnum == false\");\n\n return Enum.GetValues(typeof(T)).Cast<T>();\n }\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code>public enum TestEnum { A,B,C };\n\nTestEnum.A.toElementsCollection();\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
] |
In vs2008, is it possible to write an extension methods which would apply to any enumeration.
I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?
|
Yes, just code against the base `Enum` type, e.g.
```
public static void Something(this Enum e)
{
// code here
}
```
The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using [`Enum.GetUnderlyingType`](http://msdn.microsoft.com/en-us/library/system.enum.getunderlyingtype.aspx), casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have `IsOneOf` and `IsCombinationOf` methods that apply to all enums).
PS: Remember when writing the method that, although ill advised, you can use `float` and `double` as the base types for enums so you'll need some special cases for those as well as unsigned values.
|
276,602 |
<p>In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x.</p>
|
[
{
"answer_id": 276611,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 4,
"selected": true,
"text": "<p>Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison.</p>\n\n<pre><code>$url = 'http://my.url.com/';\n$data = file_get_contents( $url );\n\nif ( strpos( 'maybe baby love you', $data ) === false )\n{\n\n // do something\n\n}\n</code></pre>\n"
},
{
"answer_id": 276614,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming fopen URL Wrappers are on ...</p>\n\n<pre><code>$string = file_get_contents('http://example.com/file.html');\nif(strpos ('maybe baby love you', $string) === false){ \n //do X\n}\n</code></pre>\n"
},
{
"answer_id": 276999,
"author": "Hugh Bothwell",
"author_id": 33258,
"author_profile": "https://Stackoverflow.com/users/33258",
"pm_score": 0,
"selected": false,
"text": "<p>If fopen URL wrappers are not enabled, you may be able to use the curl module (see <a href=\"http://www.php.net/curl\" rel=\"nofollow noreferrer\">http://www.php.net/curl</a> )</p>\n\n<p>Curl also gives you the ability to deal with authenticated pages, redirects, etc.</p>\n"
},
{
"answer_id": 2040523,
"author": "Tarek Ahmed",
"author_id": 247871,
"author_profile": "https://Stackoverflow.com/users/247871",
"pm_score": 3,
"selected": false,
"text": "<pre><code>//The Answer No 3 Is good But a small Mistake in the function strpos() I have correction the code bellow.\n\n$url = 'http://my.url.com/';\n$data = file_get_contents( $url );\n\nif ( strpos($data,'maybe baby love you' ) === false )\n{\n // do something\n}\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x.
|
Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison.
```
$url = 'http://my.url.com/';
$data = file_get_contents( $url );
if ( strpos( 'maybe baby love you', $data ) === false )
{
// do something
}
```
|
276,644 |
<p>A voice recorder doesn't need uncompressed Linear PCM audio. Compressed <code>AMR</code> would do fine. The iPhone framework built for recording audio is simple enough, but the only examples I've found for setting up the audio format (which come from Apple) use LinearPCM. I've tried various other combinations of values, but can't seem to get anything to work. </p>
<p>Does anybody have any code that actually records <code>AMR</code>?</p>
<p><b>Edit:</b>
The AMR format is one of the options for setting the data type, but the other options (packet size, frame size, etc.) don't seem to match up no matter what I set them to.</p>
<p><b>Edit:</b> Here's what I have for the PCM version:</p>
<pre><code>/*
If we want to use AMR instead of PCM:
AMR Format:
Sampling Frequency: 8 kHz/13-bit (160 samples for 20 ms frames), filtered to 200-3400 Hz
eight source codecs : 12.2, 1.2, 7.95, 7.40, 6.70, 5.90, 5.15, 4.75 kbit/s
generated frame length: 244, 204, 159, 148, 134, 118, 103, 95 bits per frame
*/
format->mFormatID = kAudioFormatLinearPCM;
format->mSampleRate = 8000.0; //8 kHz
format->mFramesPerPacket = 1; //1 frame per packet
format->mChannelsPerFrame = 1; //Mono
format->mBytesPerFrame = 2; //8/bits per frame (round up)
format->mBytesPerPacket = 2; //Same as bytes per frame
format->mBitsPerChannel = 16; //16-bit audio
format->mReserved = 0; //always 0
format->mFormatFlags = kLinearPCMFormatFlagIsBigEndian |
kLinearPCMFormatFlagIsSignedInteger |
kLinearPCMFormatFlagIsPacked;
</code></pre>
|
[
{
"answer_id": 276794,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 2,
"selected": false,
"text": "<p>I guess AMR codec format is not supported my iPhone voice recorder app.</p>\n\n<p>May be one can try integrating some open-source, implementation of AMR encoder into the apples' iPhone application framework and try making the voice recorder store the audio in AMR encoded format. (i dont know if thats allowed by apple by their NDA/license).</p>\n\n<p>-AD</p>\n"
},
{
"answer_id": 614686,
"author": "olegueret",
"author_id": 10421,
"author_profile": "https://Stackoverflow.com/users/10421",
"pm_score": 5,
"selected": true,
"text": "<p>AMR codec is NOT supported for encoding/recording on the iPhone, albeit it is supported for playback: this is the reason the kAudioFormatAMR constant exists.</p>\n\n<p><a href=\"http://developer.apple.com/library/ios/#qa/qa1615/_index.html\" rel=\"nofollow noreferrer\">Official api</a> says that supported encoding formats are:</p>\n\n<ul>\n<li><strong>ALAC</strong> (Apple Lossless) ~> kAudioFormatAppleLossless</li>\n<li><strong>iLBC</strong> (internet Low Bitrate Codec, for speech) ~> kAudioFormatiLBC</li>\n<li><strong>IMA/ADPCM</strong> (IMA4) ~> kAudioFormatAppleIMA4</li>\n<li><strong>linear PCM</strong> ~> kAudioFormatLinearPCM</li>\n<li><strong>µ-law</strong> ~> kAudioFormatULaw</li>\n<li><strong>a-law</strong> ~> kAudioFormatALaw</li>\n</ul>\n\n<p>You may try one of these formats or use an open source AMR encoder as <a href=\"https://stackoverflow.com/questions/276644/how-can-i-record-amr-audio-format-on-the-iphone/276794#276794\">goldenmean</a> suggests.</p>\n\n<p><strong>edit</strong>: Updated Official api link</p>\n"
},
{
"answer_id": 3833935,
"author": "ima747",
"author_id": 463183,
"author_profile": "https://Stackoverflow.com/users/463183",
"pm_score": 2,
"selected": false,
"text": "<p>To update olegueret's link to the official documentation (why do they hide this stuff?)</p>\n\n<p><a href=\"http://developer.apple.com/library/ios/#qa/qa2008/qa1615.html\" rel=\"nofollow\">http://developer.apple.com/library/ios/#qa/qa2008/qa1615.html</a></p>\n"
},
{
"answer_id": 10251670,
"author": "hotpaw2",
"author_id": 341750,
"author_profile": "https://Stackoverflow.com/users/341750",
"pm_score": 1,
"selected": false,
"text": "<p>You can record audio to a uncompressed Linear PCM buffer (circular or ring), and, in another thread, convert data in this buffer, using your own AMR (or other) compression engine, before saving the compressed audio data to a file.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36007/"
] |
A voice recorder doesn't need uncompressed Linear PCM audio. Compressed `AMR` would do fine. The iPhone framework built for recording audio is simple enough, but the only examples I've found for setting up the audio format (which come from Apple) use LinearPCM. I've tried various other combinations of values, but can't seem to get anything to work.
Does anybody have any code that actually records `AMR`?
**Edit:**
The AMR format is one of the options for setting the data type, but the other options (packet size, frame size, etc.) don't seem to match up no matter what I set them to.
**Edit:** Here's what I have for the PCM version:
```
/*
If we want to use AMR instead of PCM:
AMR Format:
Sampling Frequency: 8 kHz/13-bit (160 samples for 20 ms frames), filtered to 200-3400 Hz
eight source codecs : 12.2, 1.2, 7.95, 7.40, 6.70, 5.90, 5.15, 4.75 kbit/s
generated frame length: 244, 204, 159, 148, 134, 118, 103, 95 bits per frame
*/
format->mFormatID = kAudioFormatLinearPCM;
format->mSampleRate = 8000.0; //8 kHz
format->mFramesPerPacket = 1; //1 frame per packet
format->mChannelsPerFrame = 1; //Mono
format->mBytesPerFrame = 2; //8/bits per frame (round up)
format->mBytesPerPacket = 2; //Same as bytes per frame
format->mBitsPerChannel = 16; //16-bit audio
format->mReserved = 0; //always 0
format->mFormatFlags = kLinearPCMFormatFlagIsBigEndian |
kLinearPCMFormatFlagIsSignedInteger |
kLinearPCMFormatFlagIsPacked;
```
|
AMR codec is NOT supported for encoding/recording on the iPhone, albeit it is supported for playback: this is the reason the kAudioFormatAMR constant exists.
[Official api](http://developer.apple.com/library/ios/#qa/qa1615/_index.html) says that supported encoding formats are:
* **ALAC** (Apple Lossless) ~> kAudioFormatAppleLossless
* **iLBC** (internet Low Bitrate Codec, for speech) ~> kAudioFormatiLBC
* **IMA/ADPCM** (IMA4) ~> kAudioFormatAppleIMA4
* **linear PCM** ~> kAudioFormatLinearPCM
* **µ-law** ~> kAudioFormatULaw
* **a-law** ~> kAudioFormatALaw
You may try one of these formats or use an open source AMR encoder as [goldenmean](https://stackoverflow.com/questions/276644/how-can-i-record-amr-audio-format-on-the-iphone/276794#276794) suggests.
**edit**: Updated Official api link
|
276,654 |
<p>I have an initialization class that preloads content into a variable (probably a list or array). There will only be one instance of this initialization class but there will be many classes that need to access the preloaded content.</p>
<p>The problem is not many of them are related and none of them extend my initialization class. I thought about this for a bit and decided on using a static method and variable for this use. So something like this...</p>
<pre><code>public class InitClass
{
static List PreloadedContent;
static ModelData GetContent(String ContentName)
{
//return the preloaded content that matches given name
}
}
</code></pre>
<p>The preloaded content may at some time decrease or increase in size depending on what the situation may call for. I've run into situations where something like this has been the only decent looking solution however; I think its an ugly solution.</p>
<p>Note: I can't load the data onto a class that needs it when it is created due to a variety of reasons - most of which are reasons I don't know about yet but will most likely come up. Certain classes will be loaded/unloaded depending on the rendering of the scene and my InitClass won't handle the creation of these objects most of the time.</p>
<p>Can anyone give me a better solution?</p>
|
[
{
"answer_id": 276659,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid static/global scope you could use some kind of Registry class. This means you have one class which you initialize at program startup. This class holds references to all other classes that need to be accessed globally.\nNow you pass the initialized instance of your registry class to all instances in your application.\nIt isn't a very pretty soluation, but for me it is the best. With Static and global variables I always ended up in having some problems when testing or debugging code.</p>\n\n<p>Another aproach would be to use a Singleton. Since they also just hold a static instance I would not prefer them. </p>\n"
},
{
"answer_id": 276662,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": true,
"text": "<p>what you are doing is known as <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a>. here are some previous discussions on this:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/246710/how-to-implement-a-singleton-in-c\">How to implement a singleton in C#</a></li>\n<li><a href=\"https://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c\">What’s a good threadsafe singleton generic template pattern in C#</a></li>\n</ul>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an initialization class that preloads content into a variable (probably a list or array). There will only be one instance of this initialization class but there will be many classes that need to access the preloaded content.
The problem is not many of them are related and none of them extend my initialization class. I thought about this for a bit and decided on using a static method and variable for this use. So something like this...
```
public class InitClass
{
static List PreloadedContent;
static ModelData GetContent(String ContentName)
{
//return the preloaded content that matches given name
}
}
```
The preloaded content may at some time decrease or increase in size depending on what the situation may call for. I've run into situations where something like this has been the only decent looking solution however; I think its an ugly solution.
Note: I can't load the data onto a class that needs it when it is created due to a variety of reasons - most of which are reasons I don't know about yet but will most likely come up. Certain classes will be loaded/unloaded depending on the rendering of the scene and my InitClass won't handle the creation of these objects most of the time.
Can anyone give me a better solution?
|
what you are doing is known as [singleton](http://en.wikipedia.org/wiki/Singleton_pattern). here are some previous discussions on this:
* [How to implement a singleton in C#](https://stackoverflow.com/questions/246710/how-to-implement-a-singleton-in-c)
* [What’s a good threadsafe singleton generic template pattern in C#](https://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c)
|
276,656 |
<p>So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code:</p>
<pre><code>class SomeEntity(models.Model):
some_field = models.CharField(max_length=50, db_index=True, unique=True)
</code></pre>
<p>I've got the admin interface setup and everything appears to be working fine except that I can create two SomeEntity records, one with some_field='some value' and one with some_field='Some Value' because the unique constraint on some_field appears to be case sensitive.</p>
<p>Is there some way to force sqlite to perform a case <em>in</em>sensitive comparison when checking for uniqueness?</p>
<p>I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)</p>
|
[
{
"answer_id": 276708,
"author": "Doug Currie",
"author_id": 33252,
"author_profile": "https://Stackoverflow.com/users/33252",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you can create and use a custom model field; it would be a subclass of CharField but providing a <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#db_type\" rel=\"nofollow noreferrer\">db_type</a> method returning \"text collate nocase\"</p>\n"
},
{
"answer_id": 471066,
"author": "Noah",
"author_id": 12113,
"author_profile": "https://Stackoverflow.com/users/12113",
"pm_score": 5,
"selected": true,
"text": "<p>Yes this can easily be done by adding a unique index to the table with the following command:</p>\n\n<p>CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE)</p>\n\n<p>If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following:</p>\n\n<p>The following example shows a custom collation that sorts “the wrong way”:</p>\n\n<pre><code>import sqlite3\n\ndef collate_reverse(string1, string2):\n return -cmp(string1, string2)\n\ncon = sqlite3.connect(\":memory:\")\ncon.create_collation(\"reverse\", collate_reverse)\n\ncur = con.cursor()\ncur.execute(\"create table test(x)\")\ncur.executemany(\"insert into test(x) values (?)\", [(\"a\",), (\"b\",)])\ncur.execute(\"select x from test order by x collate reverse\")\nfor row in cur:\n print row\ncon.close()\n</code></pre>\n\n<p>Additional python documentation for sqlite3 shown <a href=\"http://docs.python.org/library/sqlite3.html\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 70322810,
"author": "Alireza Farahani",
"author_id": 1660013,
"author_profile": "https://Stackoverflow.com/users/1660013",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone in 2021, with the help of <a href=\"https://docs.djangoproject.com/en/4.0/releases/4.0/#functional-unique-constraints\" rel=\"nofollow noreferrer\">Django 4.0 UniqueConstraint expressions</a> you could add a Meta class to your model like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Meta:\n constraints = [\n models.UniqueConstraint(\n Lower('<field name>'),\n name='<constraint name>'\n ),\n ]\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29123/"
] |
So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code:
```
class SomeEntity(models.Model):
some_field = models.CharField(max_length=50, db_index=True, unique=True)
```
I've got the admin interface setup and everything appears to be working fine except that I can create two SomeEntity records, one with some\_field='some value' and one with some\_field='Some Value' because the unique constraint on some\_field appears to be case sensitive.
Is there some way to force sqlite to perform a case *in*sensitive comparison when checking for uniqueness?
I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)
|
Yes this can easily be done by adding a unique index to the table with the following command:
CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE)
If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following:
The following example shows a custom collation that sorts “the wrong way”:
```
import sqlite3
def collate_reverse(string1, string2):
return -cmp(string1, string2)
con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)
cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
print row
con.close()
```
Additional python documentation for sqlite3 shown [here](http://docs.python.org/library/sqlite3.html)
|
276,660 |
<p>I need to warn users about unsaved changes before they leave a page (a pretty common problem).</p>
<pre><code>window.onbeforeunload = handler
</code></pre>
<p>This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.</p>
<p>So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?</p>
<p>Javascript in my page:</p>
<pre><code><script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
</code></pre>
<p>The closeIt() function:</p>
<pre><code>function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
</code></pre>
<p>Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):</p>
<pre><code>$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
</code></pre>
<p>which also doesn't work - I cannot seem to bind to the <code>beforeunload</code> event.</p>
|
[
{
"answer_id": 276739,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": true,
"text": "<p>You can't modify the default dialogue for <code>onbeforeunload</code>, so your best bet may be to work with it.</p>\n\n<pre><code>window.onbeforeunload = function() {\n return 'You have unsaved changes!';\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx\" rel=\"noreferrer\">Here's a reference</a> to this from Microsoft:</p>\n\n<blockquote>\n <p>When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, \"Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.\", cannot be removed or altered.</p>\n</blockquote>\n\n<p>The problem seems to be:</p>\n\n<ol>\n<li>When <code>onbeforeunload</code> is called, it will take the return value of the handler as <code>window.event.returnValue</code>.</li>\n<li>It will then parse the return value as a string (unless it is null).</li>\n<li>Since <code>false</code> is parsed as a string, the dialogue box will fire, which will then pass an appropriate <code>true</code>/<code>false</code>.</li>\n</ol>\n\n<p>The result is, there doesn't seem to be a way of assigning <code>false</code> to <code>onbeforeunload</code> to prevent it from the default dialogue.</p>\n\n<p>Additional notes on jQuery:</p>\n\n<ul>\n<li>Setting the event in jQuery <strong>may</strong> be problematic, as that allows other <code>onbeforeunload</code> events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.</li>\n<li><p>jQuery doesn't have a shortcut for <code>onbeforeunload</code> so you'd have to use the generic <code>bind</code> syntax.</p>\n\n<pre><code>$(window).bind('beforeunload', function() {} );\n</code></pre></li>\n</ul>\n\n<p><strong>Edit 09/04/2018</strong>: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: <a href=\"https://developers.google.com/web/updates/2016/04/chrome-51-deprecations#remove_custom_messages_in_onbeforeunload_dialogs\" rel=\"noreferrer\">release note</a>)</p>\n"
},
{
"answer_id": 3532762,
"author": "Ricardo stands with Ukraine",
"author_id": 364568,
"author_profile": "https://Stackoverflow.com/users/364568",
"pm_score": 1,
"selected": false,
"text": "<p>What about to use the specialized version of the \"bind\" command \"one\". Once the event handler executes the first time, it’s automatically removed as an event handler.</p>\n\n<pre><code>$(window).one(\"beforeunload\", BeforeUnload);\n</code></pre>\n"
},
{
"answer_id": 4991688,
"author": "grebe",
"author_id": 616120,
"author_profile": "https://Stackoverflow.com/users/616120",
"pm_score": 5,
"selected": false,
"text": "<p>What worked for me, using <a href=\"https://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> and tested in IE8, Chrome and Firefox, is:</p>\n\n<pre><code>$(window).bind(\"beforeunload\",function(event) {\n if(hasChanged) return \"You have unsaved changes\";\n});\n</code></pre>\n\n<p>It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.</p>\n"
},
{
"answer_id": 6305669,
"author": "Imran Rizvi",
"author_id": 252975,
"author_profile": "https://Stackoverflow.com/users/252975",
"pm_score": 2,
"selected": false,
"text": "<p>I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :\n1) It was giving message on all navigations I want it only for close click. \n2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.</p>\n\n<p>Following is the solutions code I found, which I wrote on my Master page.</p>\n\n<pre><code>function closeMe(evt) {\n if (typeof evt == 'undefined') {\n evt = window.event; }\n if (evt && evt.clientX >= (window.event.screenX - 150) &&\n evt.clientY >= -150 && evt.clientY <= 0) {\n return \"Do you want to log out of your current session?\";\n }\n}\nwindow.onbeforeunload = closeMe;\n</code></pre>\n"
},
{
"answer_id": 9546411,
"author": "Tamas Cseh",
"author_id": 1246818,
"author_profile": "https://Stackoverflow.com/users/1246818",
"pm_score": 2,
"selected": false,
"text": "<p>You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.</p>\n\n<pre><code>function onunload = (){\n window.open('logout.php');\n}\n</code></pre>\n\n<p>This code called when user leave the page or close the active window and user logged out by 'logout.php'.\nThe new window close immediately when logout php consist of code:</p>\n\n<pre><code>window.close();\n</code></pre>\n"
},
{
"answer_id": 9735315,
"author": "Krishna Patel",
"author_id": 1273745,
"author_profile": "https://Stackoverflow.com/users/1273745",
"pm_score": 1,
"selected": false,
"text": "<pre><code> <script type=\"text/javascript\">\n window.onbeforeunload = function(evt) {\n var message = 'Are you sure you want to leave?';\n if (typeof evt == 'undefined') {\n evt = window.event;\n } \n if (evt) {\n evt.returnValue = message;\n }\n return message;\n } \n </script>\n</code></pre>\n\n<p>refer from <a href=\"http://www.codeprojectdownload.com\" rel=\"nofollow\">http://www.codeprojectdownload.com</a></p>\n"
},
{
"answer_id": 11445108,
"author": "Dan Power",
"author_id": 1118863,
"author_profile": "https://Stackoverflow.com/users/1118863",
"pm_score": 5,
"selected": false,
"text": "<p>While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.</p>\n\n<p>I've used Boxy instead of the standard jQuery Dialog, it is available here: <a href=\"http://onehackoranother.com/projects/jquery/boxy/\" rel=\"noreferrer\">http://onehackoranother.com/projects/jquery/boxy/</a></p>\n\n<pre><code>$(':input').change(function() {\n if(!is_dirty){\n // When the user changes a field on this page, set our is_dirty flag.\n is_dirty = true;\n }\n});\n\n$('a').mousedown(function(e) {\n if(is_dirty) {\n // if the user navigates away from this page via an anchor link, \n // popup a new boxy confirmation.\n answer = Boxy.confirm(\"You have made some changes which you might want to save.\");\n }\n});\n\nwindow.onbeforeunload = function() {\nif((is_dirty)&&(!answer)){\n // call this if the box wasn't shown.\n return 'You have made some changes which you might want to save.';\n }\n};\n</code></pre>\n\n<p>You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.</p>\n\n<p><em>I have cut out code, so this may not work as is.</em></p>\n"
},
{
"answer_id": 12484786,
"author": "user1164763",
"author_id": 1164763,
"author_profile": "https://Stackoverflow.com/users/1164763",
"pm_score": 3,
"selected": false,
"text": "<p>1) Use onbeforeunload, not onunload.</p>\n\n<p>2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.</p>\n\n<p>3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.</p>\n"
},
{
"answer_id": 15005467,
"author": "Donald Powell",
"author_id": 1735037,
"author_profile": "https://Stackoverflow.com/users/1735037",
"pm_score": 2,
"selected": false,
"text": "<p>Try placing a <code>return;</code> instead of a message.. this is working most browsers for me.\n(This only really prevents dialog's presents)</p>\n\n<pre><code>window.onbeforeunload = function(evt) { \n //Your Extra Code\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 44273942,
"author": "Abhijeet",
"author_id": 2012163,
"author_profile": "https://Stackoverflow.com/users/2012163",
"pm_score": 3,
"selected": false,
"text": "<p>This can't be done in chrome now to avoid spamming, refer to <a href=\"https://stackoverflow.com/questions/37782104/javascript-onbeforeunload-not-showing-custom-message\">javascript onbeforeunload not showing custom message</a> for more details.</p>\n"
},
{
"answer_id": 61478410,
"author": "Istvan Dembrovszky",
"author_id": 7751106,
"author_profile": "https://Stackoverflow.com/users/7751106",
"pm_score": 3,
"selected": false,
"text": "<p>Angular 9 approach:</p>\n\n<pre><code>constructor() {\n window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {\n if (this.generatedBarcodeIndex) {\n event.preventDefault(); // for Firefox\n event.returnValue = ''; // for Chrome\n return '';\n }\n return false;\n });\n }\n</code></pre>\n\n<p>Browsers support and the removal of the custom message:</p>\n\n<ul>\n<li>Chrome removed support for the custom message in ver 51 min</li>\n<li>Opera removed support for the custom message in ver 38 min</li>\n<li>Firefox removed support for the custom message in ver 44.0 min</li>\n<li>Safari removed support for the custom message in ver 9.1 min</li>\n</ul>\n"
},
{
"answer_id": 71094846,
"author": "Muhwezi Jerald basasa",
"author_id": 6682117,
"author_profile": "https://Stackoverflow.com/users/6682117",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n<pre><code>$(window).bind('beforeunload', function (event) {\n setTimeout(function () {\n var retVal = confirm("Do you want to continue ?");\n if (retVal == true) {\n alert("User wants to continue!");\n return true;\n }\n else {\n window.stop();\n return false;\n }\n });\n return;\n });\n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
I need to warn users about unsaved changes before they leave a page (a pretty common problem).
```
window.onbeforeunload = handler
```
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
```
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
```
The closeIt() function:
```
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
```
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
```
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
```
which also doesn't work - I cannot seem to bind to the `beforeunload` event.
|
You can't modify the default dialogue for `onbeforeunload`, so your best bet may be to work with it.
```
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
```
[Here's a reference](http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx) to this from Microsoft:
>
> When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
>
>
>
The problem seems to be:
1. When `onbeforeunload` is called, it will take the return value of the handler as `window.event.returnValue`.
2. It will then parse the return value as a string (unless it is null).
3. Since `false` is parsed as a string, the dialogue box will fire, which will then pass an appropriate `true`/`false`.
The result is, there doesn't seem to be a way of assigning `false` to `onbeforeunload` to prevent it from the default dialogue.
Additional notes on jQuery:
* Setting the event in jQuery **may** be problematic, as that allows other `onbeforeunload` events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
* jQuery doesn't have a shortcut for `onbeforeunload` so you'd have to use the generic `bind` syntax.
```
$(window).bind('beforeunload', function() {} );
```
**Edit 09/04/2018**: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: [release note](https://developers.google.com/web/updates/2016/04/chrome-51-deprecations#remove_custom_messages_in_onbeforeunload_dialogs))
|
276,677 |
<p>I'm a self-taught developer and my experience is all in small applications that I've developed.</p>
<p>I'm currently working on an application that I've made public, and I've realized that I need to start doing good unit testing to catch regressions and generally make sure everything works.</p>
<p>I've read up on a <a href="https://stackoverflow.com/questions/205566/comprehensive-introduction-to-unit-testing">previous question</a>. I would like to know if there are any resources online specifically dealing with C# unit testing in Visual Studio 2008, preferably with examples.</p>
<p>EDIT: I'm using Visual Studio 2008 Professional for Windows applications, no web development.</p>
|
[
{
"answer_id": 276681,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.asp.net/learn/mvc-videos/\" rel=\"nofollow noreferrer\">http://www.asp.net/learn/mvc-videos/</a></p>\n\n<p>Storefront and the Pair Programming videos involve a lot of TDD (Test Driven Development)</p>\n"
},
{
"answer_id": 276767,
"author": "user32326",
"author_id": 32326,
"author_profile": "https://Stackoverflow.com/users/32326",
"pm_score": 1,
"selected": false,
"text": "<p>You don't specify whether you're working on web/windows apps, but if you're learning ASP.NET as well then Richard Dingwall has some excellent links to example asp.net mvc applications that use TDD. There are examples using nUnit as well as mocking frameworks such as Rhino.Mocks and Moq.</p>\n\n<p>Have a look at his blog post here for some links:</p>\n\n<p><a href=\"http://richarddingwall.name/2008/11/02/best-practice-dddtdd-aspnet-mvc-example-applications/\" rel=\"nofollow noreferrer\">http://richarddingwall.name/2008/11/02/best-practice-dddtdd-aspnet-mvc-example-applications/</a></p>\n\n<p>James Gregory posted a pretty good primer on unit testing in general here:</p>\n\n<p><a href=\"http://blog.jagregory.com/2007/07/17/getting-with-it-test-driven-development/\" rel=\"nofollow noreferrer\">http://blog.jagregory.com/2007/07/17/getting-with-it-test-driven-development/</a></p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 276786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The e-book Foundations of programming: <a href=\"http://codebetter.com/blogs/karlseguin/archive/2008/06/24/foundations-of-programming-ebook.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/karlseguin/archive/2008/06/24/foundations-of-programming-ebook.aspx</a></p>\n\n<p>also covers unit testing.</p>\n"
},
{
"answer_id": 277253,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>You don't specify which <a href=\"http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx\" rel=\"noreferrer\">flavor of VS2008</a> you are using. If it is Pro or above, then MSTest is bundled, but a lot of people have issues with it - it isn't always very intuitive, and it takes far too much setup to do simple things like coverage / file deployment.</p>\n\n<p>A walkthrough is <a href=\"http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>As a recommendation, I suggest using VS2008 with <a href=\"http://www.nunit.org/\" rel=\"noreferrer\">NUnit</a> (free) and <a href=\"http://testdriven.net/\" rel=\"noreferrer\">TestDriven.NET</a> (not free). It takes away all the pain, allowing you to just write simple things like:</p>\n\n<pre><code>[TestFixture]\npublic class Foo {\n [Test]\n public void Bar() {\n Assert.AreEqual(2, 1+1);\n }\n}\n</code></pre>\n\n<p>Then just right-click (on the class, on the method, on the project, on the solution) and use the Test options that TestDriven.NET provides, including (if you have MSTest) \"Test With -> Team Coverage\", which runs your NUnit tests with the MSTest coverage tools, including giving the colorization back into the IDE to show which lines executed. No messing with \"testrunconfig\" and the other files that MSTest wants you to use.</p>\n"
},
{
"answer_id": 278733,
"author": "cordellcp3",
"author_id": 36267,
"author_profile": "https://Stackoverflow.com/users/36267",
"pm_score": 0,
"selected": false,
"text": "<p>If you interested in more than just normal unit-tests, then take a look at <a href=\"http://research.microsoft.com/Pex/\" rel=\"nofollow noreferrer\">PEX</a></p>\n"
},
{
"answer_id": 344357,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend looking at screencasts, to get a feel for how TDD is applied. At <a href=\"http://www.dnrtv.com/\" rel=\"nofollow noreferrer\">Dnr TV</a> there are two episodes with JP Boodhoo, where he gives an introduction to test driven development:</p>\n\n<ul>\n<li><a href=\"http://www.dnrtv.com/default.aspx?showNum=10\" rel=\"nofollow noreferrer\">Test Driven Development with JP Boodhoo, Part 1</a></li>\n<li><a href=\"http://www.dnrtv.com/default.aspx?showNum=11\" rel=\"nofollow noreferrer\">Test Driven Development with JP Boodhoo, Part 2</a></li>\n</ul>\n\n<p>If you want to see unit testing and TDD used together with a whole bunch of other agile practices, I would recommend watching the sceencast series <a href=\"http://autumnofagile.net/\" rel=\"nofollow noreferrer\">Autumn of Agile</a>. This series shows the development of a fully unit tested application from start to finish.</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5982/"
] |
I'm a self-taught developer and my experience is all in small applications that I've developed.
I'm currently working on an application that I've made public, and I've realized that I need to start doing good unit testing to catch regressions and generally make sure everything works.
I've read up on a [previous question](https://stackoverflow.com/questions/205566/comprehensive-introduction-to-unit-testing). I would like to know if there are any resources online specifically dealing with C# unit testing in Visual Studio 2008, preferably with examples.
EDIT: I'm using Visual Studio 2008 Professional for Windows applications, no web development.
|
You don't specify which [flavor of VS2008](http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx) you are using. If it is Pro or above, then MSTest is bundled, but a lot of people have issues with it - it isn't always very intuitive, and it takes far too much setup to do simple things like coverage / file deployment.
A walkthrough is [here](http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx).
As a recommendation, I suggest using VS2008 with [NUnit](http://www.nunit.org/) (free) and [TestDriven.NET](http://testdriven.net/) (not free). It takes away all the pain, allowing you to just write simple things like:
```
[TestFixture]
public class Foo {
[Test]
public void Bar() {
Assert.AreEqual(2, 1+1);
}
}
```
Then just right-click (on the class, on the method, on the project, on the solution) and use the Test options that TestDriven.NET provides, including (if you have MSTest) "Test With -> Team Coverage", which runs your NUnit tests with the MSTest coverage tools, including giving the colorization back into the IDE to show which lines executed. No messing with "testrunconfig" and the other files that MSTest wants you to use.
|
276,678 |
<p>C#: What is the proper way to change the font style (underline) from a Label at runtime?</p>
<p>So far I understand that if you want to change font related properties at runtime from a label, mainly all font properties, you would have to use,</p>
<pre><code> lblName.Font = new Font(... etc. etc.
</code></pre>
<p>Is there a shortcut to the above but only assign nothing but a new Font style such FontStyle.Underline? </p>
<p>or </p>
<p>Would I have to proceed with using the "new Font()" method and assign all fields along with it too just to underline my label?</p>
|
[
{
"answer_id": 276686,
"author": "wonderchook",
"author_id": 32113,
"author_profile": "https://Stackoverflow.com/users/32113",
"pm_score": 0,
"selected": false,
"text": "<p>How about (I'm using .Net Framework 2.0) Okay so this works for a Web Application. In a forms application it is read-only.</p>\n\n<p>lblName.Font.Underline = true;</p>\n\n<p>Here's the definition:</p>\n\n<pre><code> //\n // Summary:\n // Gets or sets a value that indicates whether the font is underlined.\n //\n // Returns:\n // true if the font is underlined; otherwise, false. The default value is false.\n [DefaultValue(false)]\n [NotifyParentProperty(true)]\n public bool Underline { get; set; }\n</code></pre>\n"
},
{
"answer_id": 276725,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Resorted to,</p>\n\n<blockquote>\n <p>this.Font = new Font(this.Font, FontStyle.Underline);</p>\n</blockquote>\n\n<p>Works for Win32 Forms.</p>\n"
},
{
"answer_id": 276785,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 4,
"selected": false,
"text": "<p>The way you did it:</p>\n\n<pre><code>this.Font = new Font(this.Font, FontStyle.Underline);\n</code></pre>\n\n<p>is correct. The reason is that Font is a sealed and immutable type (by design). When introduced in .NET 1 this seemed a bit strange but with today's emphasis on functional programming, concurrency and immutability this style is seen a lot more. Perhaps it was done this way since controls inherit the font of their container and tracking individual font property changes would be more work than tracking a wholesale font change. </p>\n"
},
{
"answer_id": 9751280,
"author": "Syed Baqar Hassan",
"author_id": 1271468,
"author_profile": "https://Stackoverflow.com/users/1271468",
"pm_score": 1,
"selected": false,
"text": "<pre><code>//Bold.\n label1.Font = new Font(label1.Font.Name, 12, FontStyle.Bold); \n\n//Bold With Underline.\n label1.Font = new Font(label1.Font.Name, 12, FontStyle.Bold | FontStyle.Underline); \n\n//Bold with Underline with Italic.\n label1.Font = new Font(label1.Font.Name, 12, FontStyle.Bold | FontStyle.Underline | FontStyle.Italic); \n</code></pre>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
C#: What is the proper way to change the font style (underline) from a Label at runtime?
So far I understand that if you want to change font related properties at runtime from a label, mainly all font properties, you would have to use,
```
lblName.Font = new Font(... etc. etc.
```
Is there a shortcut to the above but only assign nothing but a new Font style such FontStyle.Underline?
or
Would I have to proceed with using the "new Font()" method and assign all fields along with it too just to underline my label?
|
The way you did it:
```
this.Font = new Font(this.Font, FontStyle.Underline);
```
is correct. The reason is that Font is a sealed and immutable type (by design). When introduced in .NET 1 this seemed a bit strange but with today's emphasis on functional programming, concurrency and immutability this style is seen a lot more. Perhaps it was done this way since controls inherit the font of their container and tracking individual font property changes would be more work than tracking a wholesale font change.
|
276,693 |
<p>What is the best way to change the height and width of an ASP.NET control from a client-side Javascript function?</p>
<p>Thanks,
Jeff</p>
|
[
{
"answer_id": 276699,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the controls .ClientID and some javascript and change it that way.</p>\n\n<p>You can do it through CSS height/width or on some controls directly on the control itself.</p>\n"
},
{
"answer_id": 276789,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": true,
"text": "<p>Because of the name mangling introduced by ASP.NET, I use the function at the bottom to find ASP controls. Once you have the control, you can set the height/width as needed.</p>\n\n<pre><code>example usage:\n\n<input type='button' value='Expand' onclick='setSize(\"myDiv\", 500, 500);' />\n\n...\n\nfunction setSize(ctlName, height, width ) {\n var ctl = asp$( ctlName, 'div' );\n if (ctl) {\n ctl.style.height = height + 'px';\n ctl.style.width = width + 'px';\n }\n}\n\n\nfunction asp$( id, tagName ) {\n var idRegexp = new RegExp( id + '$', 'i' );\n var tags = new Array();\n if (tagName) {\n tags = document.getElementsByTagName( tagName );\n }\n else {\n tags = document.getElementsByName( id );\n }\n var control = null;\n for (var i = 0; i < tags.length; ++i) {\n var ctl = tags[i];\n if (idRegexp.test(ctl.id)) {\n control = ctl;\n break;\n }\n }\n\n if (control) {\n return $(control.id);\n }\n else {\n return null;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 277525,
"author": "Cyril Gupta",
"author_id": 33052,
"author_profile": "https://Stackoverflow.com/users/33052",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it's possible. ASP Controls are rendered as HTML controls on the browser with some added attributes. If you gave your ASP.Net control an ID while you created it, it will show up as the ID of the HTML control too.</p>\n\n<p>You should be able to access the controls using javascript's getElementById() function, and you should be able to modify the CSS attributes (style as specified in the message above this one).</p>\n\n<p>If you use JQuery, selection and setting CSS styles can be easier, example</p>\n\n<p>$(\"#myControl\").css(\"width\")== myNewValue;</p>\n\n<p>Cheers</p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
What is the best way to change the height and width of an ASP.NET control from a client-side Javascript function?
Thanks,
Jeff
|
Because of the name mangling introduced by ASP.NET, I use the function at the bottom to find ASP controls. Once you have the control, you can set the height/width as needed.
```
example usage:
<input type='button' value='Expand' onclick='setSize("myDiv", 500, 500);' />
...
function setSize(ctlName, height, width ) {
var ctl = asp$( ctlName, 'div' );
if (ctl) {
ctl.style.height = height + 'px';
ctl.style.width = width + 'px';
}
}
function asp$( id, tagName ) {
var idRegexp = new RegExp( id + '$', 'i' );
var tags = new Array();
if (tagName) {
tags = document.getElementsByTagName( tagName );
}
else {
tags = document.getElementsByName( id );
}
var control = null;
for (var i = 0; i < tags.length; ++i) {
var ctl = tags[i];
if (idRegexp.test(ctl.id)) {
control = ctl;
break;
}
}
if (control) {
return $(control.id);
}
else {
return null;
}
}
```
|
276,706 |
<p>I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me.</p>
<p>I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D</p>
<p>Just a few more questions - what are some practical applications of bitwise operations? When might you use them?</p>
|
[
{
"answer_id": 276711,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 4,
"selected": false,
"text": "<p>These are the bitwise operators, all supported in JavaScript:</p>\n\n<ul>\n<li><p><code>op1 & op2</code> -- The <code>AND</code> operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.</p></li>\n<li><p><code>op1 | op2</code> -- The <code>OR</code> operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.</p></li>\n<li><p><code>op1 ^ op2</code> -- The <code>EXCLUSIVE-OR</code> operator compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.</p></li>\n<li><p><code>~op1</code> -- The <code>COMPLEMENT</code> operator is used to invert all of the bits of the operand.</p></li>\n<li><p><code>op1 << op2</code> -- The <code>SHIFT LEFT</code> operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.</p></li>\n<li><p><code>op1 >> op2</code> -- The <code>SHIFT RIGHT</code> operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is preserved.</p></li>\n<li><p><code>op1 >>> op2</code> -- The <code>SHIFT RIGHT</code> - <code>ZERO FILL</code> operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is discarded.</p></li>\n</ul>\n"
},
{
"answer_id": 276715,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": "<p>Bitwise operators are operators that work on a bit at a time.</p>\n\n<p>AND is 1 only if both of its inputs are 1.</p>\n\n<p>OR is 1 if one or more of its inputs are 1.</p>\n\n<p>XOR is 1 only if exactly one of its inputs are 1.</p>\n\n<p>NOT is 1 only if its input are 0.</p>\n\n<p>These can be best described as truth tables. Inputs possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the two inputs.</p>\n\n<pre><code>AND|0 1 OR|0 1\n---+---- ---+----\n 0|0 0 0|0 1\n 1|0 1 1|1 1\n\nXOR|0 1 NOT|0 1\n---+---- ---+---\n 0|0 1 |1 0\n 1|1 0\n</code></pre>\n\n<p>One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:</p>\n\n<pre><code> 203: 1100 1011\nAND 15: 0000 1111\n------------------\n IS 11: 0000 1011\n</code></pre>\n"
},
{
"answer_id": 276724,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<p>It is worth noting that the single-bit truth tables listed as other answers work on only one or two input bits at a time. What happens when you use integers, such as:</p>\n\n<pre><code>int x = 5 & 6;\n</code></pre>\n\n<p>The answer lies in the binary expansion of each input:</p>\n\n<pre><code> 5 = 0 0 0 0 0 1 0 1\n& 6 = 0 0 0 0 0 1 1 0\n---------------------\n 0 0 0 0 0 1 0 0\n</code></pre>\n\n<p>Each pair of bits in each column is run through the \"AND\" function to give the corresponding output bit on the bottom line. So the answer to the above expression is 4. The CPU has done (in this example) 8 separate \"AND\" operations in parallel, one for each column.</p>\n\n<p>I mention this because I still remember having this \"AHA!\" moment when I learned about this many years ago.</p>\n"
},
{
"answer_id": 276728,
"author": "javamonkey79",
"author_id": 27657,
"author_profile": "https://Stackoverflow.com/users/27657",
"pm_score": 2,
"selected": false,
"text": "<p>To break it down a bit more, it has a lot to do with the binary representation of the value in question. </p>\n\n<pre>\nFor example (in decimal):\nx = 8\ny = 1\n\nwould come out to (in binary):\nx = 1000\ny = 0001\n\nFrom there, you can do computational operations such as 'and' or 'or'; in this case:\nx | y = \n1000 \n0001 |\n------\n1001\n\nor...9 in decimal\n</pre>\n\n<p>Hope this helps. </p>\n"
},
{
"answer_id": 276750,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "<p>When the term \"bitwise\" is mentioned, it is sometimes clarifying that is is not a \"logical\" operator.</p>\n\n<p>For example in JavaScript, <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators\" rel=\"nofollow noreferrer\">bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)</a>; meanwhile, <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Logical_Operators\" rel=\"nofollow noreferrer\">logical operators are typically used with Boolean (logical) values</a> but can work with non-Boolean types.</p>\n\n<p>Take expr1 && expr2 for example.</p>\n\n<blockquote>\n <p>Returns expr1 if it can be converted\n to false; otherwise, returns expr2.\n Thus, when used with Boolean values,\n && returns true if both operands are\n true; otherwise, returns false.</p>\n</blockquote>\n\n<pre><code>a = \"Cat\" && \"Dog\" // t && t returns Dog\na = 2 && 4 // t && t returns 4\n</code></pre>\n\n<p>As others have noted, 2 & 4 is a bitwise AND, so it will return 0.</p>\n\n<p>You can copy the following to test.html or something and test:</p>\n\n<pre><code><html>\n<body>\n<script>\n alert(\"\\\"Cat\\\" && \\\"Dog\\\" = \" + (\"Cat\" && \"Dog\") + \"\\n\"\n + \"2 && 4 = \" + (2 && 4) + \"\\n\"\n + \"2 & 4 = \" + (2 & 4));\n</script>\n</code></pre>\n"
},
{
"answer_id": 276771,
"author": "Ed Marty",
"author_id": 36007,
"author_profile": "https://Stackoverflow.com/users/36007",
"pm_score": 9,
"selected": true,
"text": "<p>Since nobody has broached the subject of why these are useful:</p>\n\n<p>I use bitwise operations a lot when working with flags. For example, if you want to pass a series of flags to an operation (say, <code>File.Open()</code>, with Read mode and Write mode both enabled), you could pass them as a single value. This is accomplished by assigning each possible flag it's own bit in a bitset (byte, short, int, or long). For example:</p>\n\n<pre><code> Read: 00000001\nWrite: 00000010\n</code></pre>\n\n<p>So if you want to pass read AND write, you would pass (READ | WRITE) which then combines the two into </p>\n\n<pre><code>00000011\n</code></pre>\n\n<p>Which then can be decrypted on the other end like:</p>\n\n<pre><code>if ((flag & Read) != 0) { //...\n</code></pre>\n\n<p>which checks</p>\n\n<pre><code>00000011 &\n00000001\n</code></pre>\n\n<p>which returns</p>\n\n<pre><code>00000001\n</code></pre>\n\n<p>which is not 0, so the flag does specify READ.</p>\n\n<p>You can use XOR to toggle various bits. I've used this when using a flag to specify directional inputs (Up, Down, Left, Right). For example, if a sprite is moving horizontally, and I want it to turn around:</p>\n\n<pre><code> Up: 00000001\n Down: 00000010\n Left: 00000100\n Right: 00001000\nCurrent: 00000100\n</code></pre>\n\n<p>I simply XOR the current value with (LEFT | RIGHT) which will turn LEFT off and RIGHT on, in this case.</p>\n\n<p>Bit Shifting is useful in several cases.</p>\n\n<pre><code>x << y\n</code></pre>\n\n<p>is the same as</p>\n\n<blockquote>\n <p>x * 2<sup>y</sup></p>\n</blockquote>\n\n<p>if you need to quickly multiply by a power of two, but watch out for shifting a 1-bit into the top bit - this makes the number negative unless it's unsigned. It's also useful when dealing with different sizes of data. For example, reading an integer from four bytes:</p>\n\n<pre><code>int val = (A << 24) | (B << 16) | (C << 8) | D;\n</code></pre>\n\n<p>Assuming that A is the most-significant byte and D the least. It would end up as:</p>\n\n<pre><code>A = 01000000\nB = 00000101\nC = 00101011\nD = 11100011\nval = 01000000 00000101 00101011 11100011\n</code></pre>\n\n<p>Colors are often stored this way (with the most significant byte either ignored or used as Alpha):</p>\n\n<pre><code>A = 255 = 11111111\nR = 21 = 00010101\nG = 255 = 11111111\nB = 0 = 00000000\nColor = 11111111 00010101 11111111 00000000\n</code></pre>\n\n<p>To find the values again, just shift the bits to the right until it's at the bottom, then mask off the remaining higher-order bits:</p>\n\n<pre><code>Int Alpha = Color >> 24\nInt Red = Color >> 16 & 0xFF\nInt Green = Color >> 8 & 0xFF\nInt Blue = Color & 0xFF\n</code></pre>\n\n<p><code>0xFF</code> is the same as <code>11111111</code>. So essentially, for Red, you would be doing this:</p>\n\n<pre><code>Color >> 16 = (filled in 00000000 00000000)11111111 00010101 (removed 11111111 00000000)\n00000000 00000000 11111111 00010101 &\n00000000 00000000 00000000 11111111 =\n00000000 00000000 00000000 00010101 (The original value)\n</code></pre>\n"
},
{
"answer_id": 530672,
"author": "Nosredna",
"author_id": 61027,
"author_profile": "https://Stackoverflow.com/users/61027",
"pm_score": -1,
"selected": false,
"text": "<p>I kept hearing about how slow JavaScript bitwise operators were. I did some tests for <a href=\"http://dreaminginjavascript.wordpress.com/2009/02/09/bitwise-byte-foolish/\" rel=\"nofollow noreferrer\">my latest blog post</a> and found out they were 40% to 80% faster than the arithmetic alternative in several tests. Perhaps they used to be slow. In modern browsers, I love them.</p>\n\n<p>I have one case in my code that will be faster and easier to read because of this. I'll keep my eyes open for more.</p>\n"
},
{
"answer_id": 24329660,
"author": "user3677963",
"author_id": 3677963,
"author_profile": "https://Stackoverflow.com/users/3677963",
"pm_score": 0,
"selected": false,
"text": "<p>It might help to think of it this way. This is how AND (&) works:</p>\n\n<p>It basically says are both of these numbers ones, so if you have two numbers 5 and 3 they will be converted into binary and the computer will think</p>\n\n<pre><code> 5: 00000101\n 3: 00000011\n</code></pre>\n\n<p>are both one: 00000001\n0 is false, 1 is true</p>\n\n<p>So the AND of 5 and 3 is one. The OR (|) operator does the same thing except only one of the numbers must be one to output 1, not both.</p>\n"
},
{
"answer_id": 36762031,
"author": "Prashant",
"author_id": 3404480,
"author_profile": "https://Stackoverflow.com/users/3404480",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations.</p>\n</blockquote>\n\n<p><strong>operations</strong>:</p>\n\n<ul>\n<li><p>bitwise AND</p></li>\n<li><p>bitwise OR</p></li>\n<li><p>bitwise NOT</p></li>\n<li><p>bitwise XOR</p></li>\n<li><p>etc</p></li>\n</ul>\n\n<p>List item</p>\n\n<pre><code> AND|0 1 OR|0 1 \n ---+---- ---+---- \n 0|0 0 0|0 1 \n 1|0 1 1|1 1 \n\n XOR|0 1 NOT|0 1 \n ---+---- ---+--- \n 0|0 1 |1 0 \n 1|1 0\n</code></pre>\n\n<p>Eg.</p>\n\n<pre><code> 203: 1100 1011\nAND 15: 0000 1111\n------------------\n = 11: 0000 1011\n</code></pre>\n\n<p><strong>Uses of bitwise operator</strong></p>\n\n<ul>\n<li>The left-shift and right-shift operators are equivalent to multiplication and division by x * 2<sup>y</sup> respectively.</li>\n</ul>\n\n<p>Eg.</p>\n\n<pre><code>int main()\n{\n int x = 19;\n printf (\"x << 1 = %d\\n\" , x <<1);\n printf (\"x >> 1 = %d\\n\", x >>1);\n return 0;\n}\n// Output: 38 9\n</code></pre>\n\n<ul>\n<li>The & operator can be used to quickly check if a number is odd or even</li>\n</ul>\n\n<p>Eg.</p>\n\n<pre><code>int main()\n{\n int x = 19;\n (x & 1)? printf(\"Odd\"): printf(\"Even\");\n return 0;\n }\n// Output: Odd\n</code></pre>\n\n<ul>\n<li>Quick find minimum of x and y without <code>if else</code> statement</li>\n</ul>\n\n<p>Eg.</p>\n\n<pre><code>int min(int x, int y)\n{\n return y ^ ((x ^ y) & - (x < y))\n}\n</code></pre>\n\n<ul>\n<li>Decimal to binary\nconversion</li>\n</ul>\n\n<p>Eg.</p>\n\n<pre><code>#include <stdio.h>\nint main ()\n{\n int n , c , k ;\n printf(\"Enter an integer in decimal number system\\n \" ) ;\n scanf( \"%d\" , & n );\n printf(\"%d in binary number\n system is: \\n \" , n ) ;\n for ( c = 31; c >= 0 ; c -- )\n {\n k = n >> c ;\n if ( k & 1 )\n printf(\"1\" ) ;\n else\n printf(\"0\" ) ;\n }\n printf(\" \\n \" );\n return 0 ;\n}\n</code></pre>\n\n<ul>\n<li>The XOR gate encryption is popular technique, because of its complixblity and reare use by the programmer.</li>\n<li>bitwise XOR operator is the most useful operator from technical interview perspective.</li>\n</ul>\n\n<p><em>bitwise shifting works only with +ve number</em></p>\n\n<p><strong>Also there is a wide range of use of bitwise logic</strong></p>\n"
}
] |
2008/11/09
|
[
"https://Stackoverflow.com/questions/276706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36032/"
] |
I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me.
I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D
Just a few more questions - what are some practical applications of bitwise operations? When might you use them?
|
Since nobody has broached the subject of why these are useful:
I use bitwise operations a lot when working with flags. For example, if you want to pass a series of flags to an operation (say, `File.Open()`, with Read mode and Write mode both enabled), you could pass them as a single value. This is accomplished by assigning each possible flag it's own bit in a bitset (byte, short, int, or long). For example:
```
Read: 00000001
Write: 00000010
```
So if you want to pass read AND write, you would pass (READ | WRITE) which then combines the two into
```
00000011
```
Which then can be decrypted on the other end like:
```
if ((flag & Read) != 0) { //...
```
which checks
```
00000011 &
00000001
```
which returns
```
00000001
```
which is not 0, so the flag does specify READ.
You can use XOR to toggle various bits. I've used this when using a flag to specify directional inputs (Up, Down, Left, Right). For example, if a sprite is moving horizontally, and I want it to turn around:
```
Up: 00000001
Down: 00000010
Left: 00000100
Right: 00001000
Current: 00000100
```
I simply XOR the current value with (LEFT | RIGHT) which will turn LEFT off and RIGHT on, in this case.
Bit Shifting is useful in several cases.
```
x << y
```
is the same as
>
> x \* 2y
>
>
>
if you need to quickly multiply by a power of two, but watch out for shifting a 1-bit into the top bit - this makes the number negative unless it's unsigned. It's also useful when dealing with different sizes of data. For example, reading an integer from four bytes:
```
int val = (A << 24) | (B << 16) | (C << 8) | D;
```
Assuming that A is the most-significant byte and D the least. It would end up as:
```
A = 01000000
B = 00000101
C = 00101011
D = 11100011
val = 01000000 00000101 00101011 11100011
```
Colors are often stored this way (with the most significant byte either ignored or used as Alpha):
```
A = 255 = 11111111
R = 21 = 00010101
G = 255 = 11111111
B = 0 = 00000000
Color = 11111111 00010101 11111111 00000000
```
To find the values again, just shift the bits to the right until it's at the bottom, then mask off the remaining higher-order bits:
```
Int Alpha = Color >> 24
Int Red = Color >> 16 & 0xFF
Int Green = Color >> 8 & 0xFF
Int Blue = Color & 0xFF
```
`0xFF` is the same as `11111111`. So essentially, for Red, you would be doing this:
```
Color >> 16 = (filled in 00000000 00000000)11111111 00010101 (removed 11111111 00000000)
00000000 00000000 11111111 00010101 &
00000000 00000000 00000000 11111111 =
00000000 00000000 00000000 00010101 (The original value)
```
|
276,709 |
<p>It's easy to wrap optional memcached caching around your existing database queries. For example:</p>
<p>Old (DB-only):</p>
<pre><code>function getX
x = get from db
return x
end
</code></pre>
<p>New (DB with memcache):</p>
<pre><code>function getX
x = get from memcache
if found
return x
endif
x = get from db
set x in memcache
return x
end
</code></pre>
<p>The thing is though, that's not always how you want to cache. For instance take the following two queries:</p>
<pre><code>-- get all items (recordset)
SELECT * FROM items;
-- get one item (record)
SELECT * FROM items WHERE pkid = 42;
</code></pre>
<p>If I was to use the above pseudo-code to handle the caching, I would be storing all fields of item 42 twice. Once in the big record set and once on its own. Whereas I'd rather do something like this:</p>
<pre><code>SELECT pkid FROM items;
</code></pre>
<p>and cache that index of PK's. Then cache each record individually as well.</p>
<p>So in summary, the data access strategy that will work best for the DB doesn't neatly fit the memcache strategy. Since I want the memcache layer to be optional (i.e. if memcache is down, the site still works) I kind of want to have the best of both worlds, but to do so, I'm pretty sure I'll need to maintain a lot of the queries in 2 different forms (1. fetch index, then records; and 2. fetch recordset in one query). It gets more complicated with pagination. With the DB you'd do LIMIT/OFFSET SQL queries, but with memcache you'd just fetch the index of PK's and then batch-get the relevant slice of the array.</p>
<p>I'm not sure how to neatly design this, does anyone have any suggestions?</p>
<p>Better yet, if you've come up against this yourself. How do you handle it?</p>
|
[
{
"answer_id": 276831,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I guess that's something you'll have to live with. Memcahced will work the best if you don't really do stuff in batches. For example it's great for stuff like \"where are the things for this user? Here is a bunch of things for this user.\" This doesn't really mean that this query doesn't do batches. Of course it will - if some of the user stuff is stuff like his/her posts.</p>\n\n<p>I guess the problem you'll have is cases where you are mixing queries that need to get an item from the DB on its own and some that get bunch of the same kind of the previous items.</p>\n\n<p>There is always a flip side to the situation. If you really want to get hairy with your implementation you can change your batch queries to not include the items already present in memcached.Very very ugly...</p>\n\n<p>In my opinion it always comes down to \"which queries do I <strong>really</strong> want to cache?\"</p>\n\n<p>EDIT:</p>\n\n<p>The way I would go about this is:</p>\n\n<ul>\n<li>Single-item query - if in memcached, use that one, otherwise fetch from DB and update memcached.</li>\n<li>Batch query - don't worry about which items are in memcached, just get everything and update memcached.</li>\n</ul>\n\n<p>This of course assumes that the batch queries already take hell a lot more time to complete and so it I'm already spending so much time I can live with external lookups to already cached items.</p>\n\n<p>However, eventually, your cache will contain a lot of the items if you use the batch queries a lot. Therefore you'll have to strike the balance for determining at which point you still want to perform the database lookups. Good thing is if the batch query is earlier in the life cycle of your applications, then everything will be cached earlier. After the first batch query you can tell yourself that you don't need to fetch from DB anymore unless the data in the cache is invalidated by updates or deletes.</p>\n"
},
{
"answer_id": 276857,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "<p>Read about the <a href=\"http://martinfowler.com/eaaCatalog/identityMap.html\" rel=\"nofollow noreferrer\">Identity Map</a> pattern. This is a way to make sure you only keep one copy of a given row in your application space. Whether you store it in memcached or just plain objects, this is a way to handle what you want. I would guess that Identity Map is best used when you typically fetch one row at a time. </p>\n\n<p>When you fetch whole subsets of a table, then you have to process each row individually. You might frequently have the dilemma of whether you're getting the best use out of your cache, because if 99% of your rows are in the cache but one requires fetching from the database, you have to run the SQL query anyway (at least once). </p>\n\n<p>You could transform the SQL query to fetch only rows that aren't in the cache, but it's nontrivial to perform this transformation automatically without making the SQL query more costly.</p>\n"
},
{
"answer_id": 276882,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using a cache then, to get the most out of it, you have to accept that your data will always be stale to an extent, and that some portions of the data will be out of sync with each other. Trying to keep all the records up to date by maintaining a single copy is something best left to relational databases, so if this is the behaviour you need then you're probably better off with a powerful 64-bit DB server with a lot of RAM so it can perform its own internal caching.</p>\n\n<p>If you can accept stale data (which you'll need to if real scalability is important) then one approach is to just throw the whole result set into the cache; don't worry about duplication. RAM is cheap. If you find your cache is getting full then just buy more RAM and/or cache servers. For example if you have a query that represents items 1-24 in a set filtered by conditions X and Y then use a cache key that contains all this information, and then when asked for that same search again just return the entire result set from the cache. You either get the full result set from the cache in one hit, or you go to the database.</p>\n\n<p>The hardest thing is working out how much data can be stale, and how stale it can be without either (a) people noticing too much, or (b) breaking business requirements such as minimum update intervals.</p>\n\n<p>This approach works well for read-mostly applications, particularly ones that have paged queries and/or a finite set of filter criteria for the data. It also means that your application works exactly the same with the cache on or off, just with 0% hit rate when the cache is off. It's the approach we take at blinkBox in almost all cases.</p>\n"
},
{
"answer_id": 3556775,
"author": "zcrar70",
"author_id": 59384,
"author_profile": "https://Stackoverflow.com/users/59384",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my understanding of how NHibernate (and therefore probably Hibernate) does it. It has 4 caches:</p>\n\n<ul>\n<li>row cache: this caches DB rows. The cache key is TableName#id, the other entries are the row values.</li>\n<li>query cache: this caches the results returned for a particular query. The cache key is the query with parameters, the data is a list of the TableName#id row keys that were returned as query results.</li>\n<li>collections cache: this caches the child objects of any given parent (which NHibernate allows to be lazy-loaded.) So if you access myCompany.Employees, the employees collection will be cached in the collections cache. The cache key is CollectionName#entityId, the data is a list of the TableName#id row keys for the child rows.</li>\n<li>table update cache: a list of each table and when it was last updated. If a table was updated after the data was cached, the data is considered stale.</li>\n</ul>\n\n<p>This is a pretty flexible solution, is very efficient space-wise, and guarantees that the data won't be stale. The disadvantage is that a single query can require several round-trips to the cache, which can be a problem if the cache server is on the network.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
It's easy to wrap optional memcached caching around your existing database queries. For example:
Old (DB-only):
```
function getX
x = get from db
return x
end
```
New (DB with memcache):
```
function getX
x = get from memcache
if found
return x
endif
x = get from db
set x in memcache
return x
end
```
The thing is though, that's not always how you want to cache. For instance take the following two queries:
```
-- get all items (recordset)
SELECT * FROM items;
-- get one item (record)
SELECT * FROM items WHERE pkid = 42;
```
If I was to use the above pseudo-code to handle the caching, I would be storing all fields of item 42 twice. Once in the big record set and once on its own. Whereas I'd rather do something like this:
```
SELECT pkid FROM items;
```
and cache that index of PK's. Then cache each record individually as well.
So in summary, the data access strategy that will work best for the DB doesn't neatly fit the memcache strategy. Since I want the memcache layer to be optional (i.e. if memcache is down, the site still works) I kind of want to have the best of both worlds, but to do so, I'm pretty sure I'll need to maintain a lot of the queries in 2 different forms (1. fetch index, then records; and 2. fetch recordset in one query). It gets more complicated with pagination. With the DB you'd do LIMIT/OFFSET SQL queries, but with memcache you'd just fetch the index of PK's and then batch-get the relevant slice of the array.
I'm not sure how to neatly design this, does anyone have any suggestions?
Better yet, if you've come up against this yourself. How do you handle it?
|
Read about the [Identity Map](http://martinfowler.com/eaaCatalog/identityMap.html) pattern. This is a way to make sure you only keep one copy of a given row in your application space. Whether you store it in memcached or just plain objects, this is a way to handle what you want. I would guess that Identity Map is best used when you typically fetch one row at a time.
When you fetch whole subsets of a table, then you have to process each row individually. You might frequently have the dilemma of whether you're getting the best use out of your cache, because if 99% of your rows are in the cache but one requires fetching from the database, you have to run the SQL query anyway (at least once).
You could transform the SQL query to fetch only rows that aren't in the cache, but it's nontrivial to perform this transformation automatically without making the SQL query more costly.
|
276,732 |
<p>I have a CSS like this</p>
<pre><code>ul {
list-style-image:url(images/bulletArrow.gif);
}
ul li {
background: url(images/hr.gif) no-repeat left bottom;
padding: 5px 0 7px 0;
}
</code></pre>
<p>But the bullet image doesn't align properly in IE (it's fine in Firefox).
I already have a background image for li, so I can't use the bullet image as a background.
Is there any solution to this?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 276820,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": false,
"text": "<p>There is a good explanation and solution of this here: <a href=\"http://css.maxdesign.com.au/listutorial/master.htm\" rel=\"noreferrer\">http://css.maxdesign.com.au/listutorial/master.htm</a></p>\n\n<p>It says that using <code>list-style-image</code> results in inconsistent placement of the image with different browsers. Then it explains how to use background images for the bullets for a better result.</p>\n"
},
{
"answer_id": 276834,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "<p>I see you're removing left padding for list items. For IE, you need to do the same with the left margin - either completely remove it (set to zero) or make it something smaller than the default. Then your list items will align nicely.</p>\n"
},
{
"answer_id": 276859,
"author": "Aximili",
"author_id": 36036,
"author_profile": "https://Stackoverflow.com/users/36036",
"pm_score": 3,
"selected": true,
"text": "<p>Thank you both of you.\nThe problem is that I already use background for a line-separator. But I'll change it to border then I'll use background for the bullet image.</p>\n"
},
{
"answer_id": 2525671,
"author": "Stavros",
"author_id": 302768,
"author_profile": "https://Stackoverflow.com/users/302768",
"pm_score": 2,
"selected": false,
"text": "<p>use line-height :)</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36036/"
] |
I have a CSS like this
```
ul {
list-style-image:url(images/bulletArrow.gif);
}
ul li {
background: url(images/hr.gif) no-repeat left bottom;
padding: 5px 0 7px 0;
}
```
But the bullet image doesn't align properly in IE (it's fine in Firefox).
I already have a background image for li, so I can't use the bullet image as a background.
Is there any solution to this?
Thanks in advance.
|
Thank you both of you.
The problem is that I already use background for a line-separator. But I'll change it to border then I'll use background for the bullet image.
|
276,737 |
<p>I have one large access database that I need to normalize into five tables and a lookup table. I understand the theory behind normalization and have already sketched out the look of the tables but I am lost on how to transform my table to get the database normalized. The table analyzers doesn't offer the the breakdown that I want. </p>
|
[
{
"answer_id": 276741,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>Can queries, particularly Union queries, offer a solution? Where are you seeing a problem?</p>\n"
},
{
"answer_id": 276784,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The database is a pretty typical database with nothing special to distinguish it from others.</p>\n\n<p>The database consists of one table with:</p>\n\n<p>company name, addess, telephone etc.\ncontact person with the typical related fields</p>\n\n<p>This will basically serve as a marketing database and I will need to keep track of events, business correspondence and the like. I'm just lost on how to keep the relationships intact.</p>\n"
},
{
"answer_id": 276804,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>Do you mean relationships in the relationships window? These can easily be rebuilt. Or do you mean key fields etc? This can sometimes be difficult and may involve intermediate tables. Each case is different. As doofledorfer said, you are likely to get more specific advice if you post schemas.</p>\n"
},
{
"answer_id": 276953,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 3,
"selected": false,
"text": "<p>If you have a single table, add an Autonumber field to it.</p>\n\n<p>Then create your other tables, and use the Autonumber value from the original single table as the foreign key to join them back to the original data.</p>\n\n<p>If you had tblPerson:</p>\n\n<pre><code> tblPerson\n LastName, FirstName, WorkPhone, HomePhone\n</code></pre>\n\n<p>and you wanted to break it down, add PersonID autonumber and then create a phone table:</p>\n\n<pre><code> tblPhone\n PhoneID, PersonID, PhoneNumber, Type\n</code></pre>\n\n<p>Then you'd append data from tblPerson for the appropriate fields:</p>\n\n<pre><code> INSERT INTO tblPhone (PersonID, PhoneNumber, Type)\n SELECT tblPerson.PersonID, tblPerson.WorkPhone, \"Work\"\n FROM tblPerson\n WHERE tblPerson.WorkPhone Is Not Null;\n</code></pre>\n\n<p>and then you'd run another query for the home phone:</p>\n\n<pre><code> INSERT INTO tblPhone (PersonID, PhoneNumber, Type)\n SELECT tblPerson.PersonID, tblPerson.HomePhone, \"Home\"\n FROM tblPerson\n WHERE tblPerson.HomePhone Is Not Null;\n</code></pre>\n\n<p>Someone suggested a UNION query, which you'd have to save as you can't have a UNION query as a subselect in Jet SQL. The saved query would look something like this:</p>\n\n<pre><code> SELECT tblPerson.PersonID, tblPerson.WorkPhone, \"Work\" As Type\n FROM tblPerson\n WHERE tblPerson.WorkPhone Is Not Null\n UNION ALL \n SELECT tblPerson.PersonID, tblPerson.HomePhone, \"Home\" As Type\n FROM tblPerson\n WHERE tblPerson.HomePhone Is Not Null;\n</code></pre>\n\n<p>If you saved that as qryPhones, you'd then append qryPhones with this SQL:</p>\n\n<pre><code> INSERT INTO tblPhone (PersonID, PhoneNumber, Type)\n SELECT qryPhones.PersonID, qryPhones.WorkPhone, qryPhones.Type\n FROM qryPhones;\n</code></pre>\n\n<p>Obviously, this is just the simplest example. You'd do the same for all the fields. The key is that you have to create a PK value for your source table that will tie all the derived records back to the original table.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have one large access database that I need to normalize into five tables and a lookup table. I understand the theory behind normalization and have already sketched out the look of the tables but I am lost on how to transform my table to get the database normalized. The table analyzers doesn't offer the the breakdown that I want.
|
If you have a single table, add an Autonumber field to it.
Then create your other tables, and use the Autonumber value from the original single table as the foreign key to join them back to the original data.
If you had tblPerson:
```
tblPerson
LastName, FirstName, WorkPhone, HomePhone
```
and you wanted to break it down, add PersonID autonumber and then create a phone table:
```
tblPhone
PhoneID, PersonID, PhoneNumber, Type
```
Then you'd append data from tblPerson for the appropriate fields:
```
INSERT INTO tblPhone (PersonID, PhoneNumber, Type)
SELECT tblPerson.PersonID, tblPerson.WorkPhone, "Work"
FROM tblPerson
WHERE tblPerson.WorkPhone Is Not Null;
```
and then you'd run another query for the home phone:
```
INSERT INTO tblPhone (PersonID, PhoneNumber, Type)
SELECT tblPerson.PersonID, tblPerson.HomePhone, "Home"
FROM tblPerson
WHERE tblPerson.HomePhone Is Not Null;
```
Someone suggested a UNION query, which you'd have to save as you can't have a UNION query as a subselect in Jet SQL. The saved query would look something like this:
```
SELECT tblPerson.PersonID, tblPerson.WorkPhone, "Work" As Type
FROM tblPerson
WHERE tblPerson.WorkPhone Is Not Null
UNION ALL
SELECT tblPerson.PersonID, tblPerson.HomePhone, "Home" As Type
FROM tblPerson
WHERE tblPerson.HomePhone Is Not Null;
```
If you saved that as qryPhones, you'd then append qryPhones with this SQL:
```
INSERT INTO tblPhone (PersonID, PhoneNumber, Type)
SELECT qryPhones.PersonID, qryPhones.WorkPhone, qryPhones.Type
FROM qryPhones;
```
Obviously, this is just the simplest example. You'd do the same for all the fields. The key is that you have to create a PK value for your source table that will tie all the derived records back to the original table.
|
276,740 |
<p>I want to retrieve a list of the files that has been added or deleted from our Subversion repository over, for example, the last month.</p>
<p>I'd prefer to have the file names, and not just a count.</p>
<p>Is this possible from the Subversion command line, or would I need to use a script to trawl the log?</p>
|
[
{
"answer_id": 276755,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": true,
"text": "<p>I don't think you can do it with just the command-line tools, but outputting it with an XML format and doing some grepping or filtering would probably give you what you want.</p>\n\n<p>Try this for a start:</p>\n\n<pre><code>svn log -v --xml | grep 'action=\"[A|D]\"'\n</code></pre>\n"
},
{
"answer_id": 19625050,
"author": "M0les",
"author_id": 2060068,
"author_profile": "https://Stackoverflow.com/users/2060068",
"pm_score": 2,
"selected": false,
"text": "<p>I use a mishmash of the SVN log command and grep to get just the deletions.\ne.g.</p>\n\n<pre><code>% svn log -v -r \\{2013-09-01\\}:\\{2013-10-31\\}|grep ' D'\n</code></pre>\n\n<p>Will list the files deleted from the current branch in September-October, 2013 (Or... anything else with \"space, space, dee\" in it)</p>\n"
},
{
"answer_id": 33172450,
"author": "Danny Parker",
"author_id": 164089,
"author_profile": "https://Stackoverflow.com/users/164089",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following lines to create 2 files with lists of added and deleted files. It's very useful for updating Visual Studio projects, when it's not the main dev environment.</p>\n\n<pre><code>svn diff -r 14311:HEAD --summarize | findstr \"^A\" > AddedFiles.txt\nsvn diff -r 14311:HEAD --summarize | findstr \"^D\" > DeletedFiles.txt\n</code></pre>\n\n<p>In the example it finds all differences between revision 14311 and HEAD.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] |
I want to retrieve a list of the files that has been added or deleted from our Subversion repository over, for example, the last month.
I'd prefer to have the file names, and not just a count.
Is this possible from the Subversion command line, or would I need to use a script to trawl the log?
|
I don't think you can do it with just the command-line tools, but outputting it with an XML format and doing some grepping or filtering would probably give you what you want.
Try this for a start:
```
svn log -v --xml | grep 'action="[A|D]"'
```
|
276,766 |
<p>I need help with this route map</p>
<pre><code>routes.MapRoute("Blog_Archive",
"Blog/Archive/{year}/{month}/{day}",
new {
controller = "Blog",
action = "archive",
year = "",
month = "",
day = "",
page = 0
});
</code></pre>
<p>When I call <strong><a href="http://localhost:5060/blog/Archive/2008/11" rel="noreferrer">http://localhost:5060/blog/Archive/2008/11</a></strong>, it picks up the year and month and sends it to the controller. But when I try <strong><a href="http://localhost:5060/blog/Archive/2008" rel="noreferrer">http://localhost:5060/blog/Archive/2008</a></strong><br>
it sends it to the controller but the year parameter is null and so are all the other parameters.</p>
|
[
{
"answer_id": 276772,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 5,
"selected": true,
"text": "<p>Do you have any other Route for Blog/Archive/{something}?</p>\n\n<p>Use the <a href=\"http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx\" rel=\"noreferrer\">Routing Debugger</a> to see which route actually gets hit, most likely it's not hitting that route.</p>\n"
},
{
"answer_id": 807530,
"author": "Mouffette",
"author_id": 84825,
"author_profile": "https://Stackoverflow.com/users/84825",
"pm_score": 0,
"selected": false,
"text": "<p>Subnus,\nI noticed in your code that you have routes.IgnoreRoute(\"favicon.ico\");\nI don't think this is required with MVC 1.0 right because the period is no longer ignored correct?</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31296/"
] |
I need help with this route map
```
routes.MapRoute("Blog_Archive",
"Blog/Archive/{year}/{month}/{day}",
new {
controller = "Blog",
action = "archive",
year = "",
month = "",
day = "",
page = 0
});
```
When I call **<http://localhost:5060/blog/Archive/2008/11>**, it picks up the year and month and sends it to the controller. But when I try **<http://localhost:5060/blog/Archive/2008>**
it sends it to the controller but the year parameter is null and so are all the other parameters.
|
Do you have any other Route for Blog/Archive/{something}?
Use the [Routing Debugger](http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx) to see which route actually gets hit, most likely it's not hitting that route.
|
276,769 |
<p>I'm trying to expose this function to Python using SWIG:</p>
<pre><code>std::vector<int> get_match_stats();
</code></pre>
<p>And I want SWIG to generate wrapping code for Python so I can see it as a list of integers.</p>
<p>Adding this to the .i file:</p>
<pre>
%include "typemaps.i"
%include "std_vector.i"
namespace std
{
%template(IntVector) vector<int>;
}
</pre>
<p>I'm running <code>SWIG Version 1.3.36</code> and calling swig with <code>-Wall</code> and I get no warnings.</p>
<p>I'm able to get access to a list but I get a bunch of warnings when compiling with <code>-Wall</code> (with <code>g++ (GCC) 4.2.4</code> ) the generated C++ code that say:</p>
<pre>
warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
<p>Am I exposing the function correctly? If so, what does the warning mean?</p>
<hr>
<p>These are the lines before the offending line in the same function:</p>
<pre>
SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::vector *arg1 = (std::vector *) 0 ;
std::vector::iterator arg2 ;
std::vector::iterator result;
void *argp1 = 0 ;
int res1 = 0 ;
swig::PySwigIterator *iter2 = 0 ;
int res2 ;
PyObject * obj0 = 0 ;
PyObject * obj1 = 0 ;
if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'");
}
arg1 = reinterpret_cast * >(argp1);
</pre>
<p>And this is the offending line:</p>
<pre>
res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0);
</pre>
<p>More code follows that.</p>
<p>The warning generated when compiling with g++ 4.2.4 is:</p>
<pre>
swig_iss_wrap.cxx: In function ‘PyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)’:
swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
|
[
{
"answer_id": 277687,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 5,
"selected": true,
"text": "<pre><code>%template(IntVector) vector<int>;\n</code></pre>\n"
},
{
"answer_id": 368961,
"author": "Fergal",
"author_id": 46407,
"author_profile": "https://Stackoverflow.com/users/46407",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have much experience with Swig, but are you #including your C++ header file in your .i file? Try one (or both) of</p>\n\n<pre><code>%include \"myvector.h\"\n\n\n%{\n# include \"myvector.h\"\n%}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30626/"
] |
I'm trying to expose this function to Python using SWIG:
```
std::vector<int> get_match_stats();
```
And I want SWIG to generate wrapping code for Python so I can see it as a list of integers.
Adding this to the .i file:
```
%include "typemaps.i"
%include "std_vector.i"
namespace std
{
%template(IntVector) vector<int>;
}
```
I'm running `SWIG Version 1.3.36` and calling swig with `-Wall` and I get no warnings.
I'm able to get access to a list but I get a bunch of warnings when compiling with `-Wall` (with `g++ (GCC) 4.2.4` ) the generated C++ code that say:
```
warning: dereferencing type-punned pointer will break strict-aliasing rules
```
Am I exposing the function correctly? If so, what does the warning mean?
---
These are the lines before the offending line in the same function:
```
SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::vector *arg1 = (std::vector *) 0 ;
std::vector::iterator arg2 ;
std::vector::iterator result;
void *argp1 = 0 ;
int res1 = 0 ;
swig::PySwigIterator *iter2 = 0 ;
int res2 ;
PyObject * obj0 = 0 ;
PyObject * obj1 = 0 ;
if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'");
}
arg1 = reinterpret_cast * >(argp1);
```
And this is the offending line:
```
res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0);
```
More code follows that.
The warning generated when compiling with g++ 4.2.4 is:
```
swig_iss_wrap.cxx: In function ‘PyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)’:
swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
```
|
```
%template(IntVector) vector<int>;
```
|
276,780 |
<p>My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.</p>
<p>This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture is and how full the character is.</p>
<p>So my question is, Using the GD Library (or i guess some other means if necessary) how do I make an image black and white?</p>
|
[
{
"answer_id": 276877,
"author": "Austin Platt",
"author_id": 7206,
"author_profile": "https://Stackoverflow.com/users/7206",
"pm_score": 1,
"selected": false,
"text": "<p>You don't have to convert it to grayscale... the result would be the same if you just calculated how close a pixel is to a certain colour (in your case a series of gray points), which you would have to have done anyway when comparing your grayscale image, and then chosing the appropriate character.</p>\n"
},
{
"answer_id": 276898,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 0,
"selected": false,
"text": "<p>Typically in a RGB color space, value of 128 for each color component(RG and B) will give a medium gray. You might as well put any value lower or greater than 128 to get different intensities(shades) of gray.</p>\n\n<p>-AD</p>\n"
},
{
"answer_id": 277175,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>A common formula to convert RGB to greyscale is:</p>\n\n<pre>Gray scale intensity = 0.30R + 0.59G + 0.11B</pre>\n"
},
{
"answer_id": 277354,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 5,
"selected": false,
"text": "<p>As pointed out by <a href=\"https://stackoverflow.com/users/9021/nickf\">nickf</a> in his <a href=\"https://stackoverflow.com/questions/276780/making-an-image-greyscale-with-gd-library#276811\">comment</a>, the simple formula <code>(pixel.r + pixel.g + pixel.b) / 3</code> is not correct. Use the GD-included function <code>imagefilter()</code> (no need to iterate over all pixels in an image using PHP loops) instead:</p>\n\n<pre><code>$im = imagecreatefrompng('dave.png');\nimagefilter($im, IMG_FILTER_GRAYSCALE);\nimagepng($im, 'dave.png');\n</code></pre>\n"
},
{
"answer_id": 3551573,
"author": "Mark Lalor",
"author_id": 1246275,
"author_profile": "https://Stackoverflow.com/users/1246275",
"pm_score": 3,
"selected": false,
"text": "<p>To make it purely black and white (as you wrote) use this</p>\n\n<pre><code>imagefilter($im, IMG_FILTER_GRAYSCALE);\nimagefilter($im, IMG_FILTER_CONTRAST, -1000);\n</code></pre>\n"
},
{
"answer_id": 3552025,
"author": "Jive Dadson",
"author_id": 445296,
"author_profile": "https://Stackoverflow.com/users/445296",
"pm_score": 3,
"selected": false,
"text": "<p>The answer from nickf, although quite common, is wrong. (Sorry, Nick.) For starters, those are the luminosity numbers for NTSC RGB, not sRGB, which is what computer images use. The right numbers are 0.21, 0.72, 0.07. Secondly, the weightings must be applied to the un-gamma-corrected RGB values, then the gamma correction re-applied. Gamma for sRGB is approximately, 2.2. Precisely, it is a composite function that approximates exponentiation by 1/2.2. Here it is in C++. (I do not speak php. Sorry, you'll need to translate.)</p>\n\n<pre><code>// sRGB luminance(Y) values\nconst double rY = 0.212655;\nconst double gY = 0.715158;\nconst double bY = 0.072187;\n\n// Inverse of sRGB \"gamma\" function. (approx 2.2)\ndouble inv_gam_sRGB(int ic) {\n double c = ic/255.0;\n if ( c <= 0.04045 )\n return c/12.92;\n else \n return pow(((c+0.055)/(1.055)),2.4);\n}\n\n// sRGB \"gamma\" function (approx 2.2)\nint gam_sRGB(double v) {\n if(v<=0.0031308)\n v *= 12.92;\n else \n v = 1.055*pow(v,1.0/2.4)-0.055;\n return int(v*255+.5);\n}\n\n// GRAY VALUE\nint gray(int r, int g, int b) {\n return gam_sRGB(\n rY*inv_gam_sRGB(r) +\n gY*inv_gam_sRGB(g) +\n bY*inv_gam_sRGB(b)\n );\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.
This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture is and how full the character is.
So my question is, Using the GD Library (or i guess some other means if necessary) how do I make an image black and white?
|
A common formula to convert RGB to greyscale is:
```
Gray scale intensity = 0.30R + 0.59G + 0.11B
```
|
276,790 |
<pre><code>(define (repeated f n)
if (= n 0)
f
((compose repeated f) (lambda (x) (- n 1))))
</code></pre>
<p>I wrote this function, but how would I express this more clearly, using simple recursion with repeated?</p>
<p>I'm sorry, I forgot to define my compose function.</p>
<pre><code>(define (compose f g) (lambda (x) (f (g x))))
</code></pre>
<p>And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.</p>
|
[
{
"answer_id": 276885,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>What <em>is</em> your function trying to do, just out of curiosity? Is it to run <code>f</code>, <code>n</code> times? If so, you can do this.</p>\n\n<pre><code>(define (repeated f n)\n (for-each (lambda (i) (f)) (iota n)))\n</code></pre>\n"
},
{
"answer_id": 276967,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated can be written as follows:</p>\n\n<pre><code>(define (repeated f n)\n (lambda (x)\n (if (= n 0)\n x\n ((repeated f (- n 1)) (f x))))) \n\n(define (square x)\n (* x x))\n\n(define y (repeated square 3))\n\n(y 2) ; returns 256, which is (square (square (square 2)))\n</code></pre>\n"
},
{
"answer_id": 276972,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 1,
"selected": false,
"text": "<pre><code>(define (repeated f n)\n (lambda (x)\n (let recur ((x x) (n n))\n (if (= n 0)\n args\n (recur (f x) (sub1 n))))))\n</code></pre>\n\n<p>Write the function the way you normally would, except that the arguments are passed in two stages. It might be even clearer to define <code>repeated</code> this way:</p>\n\n<pre><code>(define repeated (lambda (f n) (lambda (x) \n (define (recur x n)\n (if (= n 0)\n x\n (recur (f x) (sub1 n))))\n (recur x n))))\n</code></pre>\n\n<p>You don't have to use a 'let-loop' this way, and the lambdas make it obvious that you expect your arguments in two stages.\n(Note:recur is not built in to Scheme as it is in Clojure, I just like the name)</p>\n\n<pre><code>> (define foonly (repeat sub1 10))\n> (foonly 11)\n1\n> (foonly 9)\n-1\n</code></pre>\n\n<p>The cool functional feature you want here is currying, not composition. Here's the Haskell with implicit currying:</p>\n\n<pre><code>repeated _ 0 x = x\nrepeated f n x = repeated f (pred n) (f x)\n</code></pre>\n\n<p>I hope this isn't a homework problem.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
(define (repeated f n)
if (= n 0)
f
((compose repeated f) (lambda (x) (- n 1))))
```
I wrote this function, but how would I express this more clearly, using simple recursion with repeated?
I'm sorry, I forgot to define my compose function.
```
(define (compose f g) (lambda (x) (f (g x))))
```
And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.
|
I'm assuming that (repeated f 3) should return a function g(x)=f(f(f(x))). If that's not what you want, please clarify. Anyways, that definition of repeated can be written as follows:
```
(define (repeated f n)
(lambda (x)
(if (= n 0)
x
((repeated f (- n 1)) (f x)))))
(define (square x)
(* x x))
(define y (repeated square 3))
(y 2) ; returns 256, which is (square (square (square 2)))
```
|
276,808 |
<p>I have a 2-dimensional array of objects and I basically want to databind each one to a cell in a WPF grid. Currently I have this working but I am doing most of it procedurally. I create the correct number of row and column definitions, then I loop through the cells and create the controls and set up the correct bindings for each one. </p>
<p>At a minimum I would like to be able to use a template to specify the controls and bindings in xaml. Ideally I would like to get rid of the procedural code and just do it all with databinding, but I'm not sure that's possible.</p>
<p>Here is the code I am currently using:</p>
<pre><code>public void BindGrid()
{
m_Grid.Children.Clear();
m_Grid.ColumnDefinitions.Clear();
m_Grid.RowDefinitions.Clear();
for (int x = 0; x < MefGrid.Width; x++)
{
m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });
}
for (int y = 0; y < MefGrid.Height; y++)
{
m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });
}
for (int x = 0; x < MefGrid.Width; x++)
{
for (int y = 0; y < MefGrid.Height; y++)
{
Cell cell = (Cell)MefGrid[x, y];
SolidColorBrush brush = new SolidColorBrush();
var binding = new Binding("On");
binding.Converter = new BoolColorConverter();
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
var rect = new Rectangle();
rect.DataContext = cell;
rect.Fill = brush;
rect.SetValue(Grid.RowProperty, y);
rect.SetValue(Grid.ColumnProperty, x);
m_Grid.Children.Add(rect);
}
}
}
</code></pre>
|
[
{
"answer_id": 276868,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 7,
"selected": true,
"text": "<p>The purpose of the Grid is not for real databinding, it is just a panel. I am listing down the easiest way to accomplish the visualization of a two dimensional list </p>\n\n<pre><code><Window.Resources>\n <DataTemplate x:Key=\"DataTemplate_Level2\">\n <Button Content=\"{Binding}\" Height=\"40\" Width=\"50\" Margin=\"4,4,4,4\"/>\n </DataTemplate>\n\n <DataTemplate x:Key=\"DataTemplate_Level1\">\n <ItemsControl ItemsSource=\"{Binding}\" ItemTemplate=\"{DynamicResource DataTemplate_Level2}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Horizontal\"/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n </ItemsControl>\n </DataTemplate>\n\n</Window.Resources>\n<Grid>\n <ItemsControl x:Name=\"lst\" ItemTemplate=\"{DynamicResource DataTemplate_Level1}\"/>\n</Grid>\n</code></pre>\n\n<p>And in the code behind set the ItemsSource of lst with a TwoDimentional data structure.</p>\n\n<pre><code> public Window1()\n {\n List<List<int>> lsts = new List<List<int>>();\n\n for (int i = 0; i < 5; i++)\n {\n lsts.Add(new List<int>());\n\n for (int j = 0; j < 5; j++)\n {\n lsts[i].Add(i * 10 + j);\n }\n }\n\n InitializeComponent();\n\n lst.ItemsSource = lsts;\n }\n</code></pre>\n\n<p>This gives you the following screen as output. You can edit the DataTemplate_Level2 to add more specific data of your object.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Y6yH9.jpg\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 1636058,
"author": "Torsten",
"author_id": 103412,
"author_profile": "https://Stackoverflow.com/users/103412",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to check out this link: <a href=\"http://www.thinkbottomup.com.au/site/blog/Game_of_Life_in_XAML_WPF_using_embedded_Python\" rel=\"nofollow noreferrer\">http://www.thinkbottomup.com.au/site/blog/Game_of_Life_in_XAML_WPF_using_embedded_Python</a></p>\n\n<p>If you use a List within a List you can use myList[x][y] to access a cell.</p>\n"
},
{
"answer_id": 4002409,
"author": "Fredrik Hedblad",
"author_id": 318425,
"author_profile": "https://Stackoverflow.com/users/318425",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a Control called <code>DataGrid2D</code> that can be populated based on a 2D or<br>\n1D array (or anything that implements the <code>IList</code> interface). It subclasses <code>DataGrid</code> and adds a property called <code>ItemsSource2D</code> which is used for binding against 2D or 1D sources. Library can be downloaded <a href=\"http://www.mediafire.com/download.php?1bw6dm9y11fbmnu\" rel=\"nofollow noreferrer\">here</a> and source code can be downloaded <a href=\"http://www.mediafire.com/download.php?tm1arm230rr1tgi\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>To use it just add a reference to DataGrid2DLibrary.dll, add this namespace</p>\n\n<pre><code>xmlns:dg2d=\"clr-namespace:DataGrid2DLibrary;assembly=DataGrid2DLibrary\"\n</code></pre>\n\n<p>and then create a DataGrid2D and bind it to your IList, 2D array or 1D array like this</p>\n\n<pre><code><dg2d:DataGrid2D Name=\"dataGrid2D\"\n ItemsSource2D=\"{Binding Int2DList}\"/>\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/JL7xy.png\" alt=\"enter image description here\"></p>\n\n<hr>\n\n<p><strong>OLD POST</strong><br>\nHere is an implementation that can bind a 2D array to the WPF datagrid. </p>\n\n<p>Say we have this 2D array</p>\n\n<pre><code>private int[,] m_intArray = new int[5, 5];\n...\nfor (int i = 0; i < 5; i++)\n{\n for (int j = 0; j < 5; j++)\n {\n m_intArray[i,j] = (i * 10 + j);\n }\n}\n</code></pre>\n\n<p>And then we want to bind this 2D array to the WPF DataGrid and the changes we make shall be reflected in the array. To do this I used Eric Lippert's Ref class from <a href=\"https://stackoverflow.com/questions/2980463/how-do-i-assign-by-reference-to-a-class-field-in-c/2982037#2982037\">this</a> thread.</p>\n\n<pre><code>public class Ref<T> \n{ \n private readonly Func<T> getter; \n private readonly Action<T> setter; \n public Ref(Func<T> getter, Action<T> setter) \n { \n this.getter = getter; \n this.setter = setter; \n } \n public T Value { get { return getter(); } set { setter(value); } } \n} \n</code></pre>\n\n<p>Then I made a static helper class with a method that could take a 2D array and return a DataView using the Ref class above.</p>\n\n<pre><code>public static DataView GetBindable2DArray<T>(T[,] array)\n{\n DataTable dataTable = new DataTable();\n for (int i = 0; i < array.GetLength(1); i++)\n {\n dataTable.Columns.Add(i.ToString(), typeof(Ref<T>));\n }\n for (int i = 0; i < array.GetLength(0); i++)\n {\n DataRow dataRow = dataTable.NewRow();\n dataTable.Rows.Add(dataRow);\n }\n DataView dataView = new DataView(dataTable);\n for (int i = 0; i < array.GetLength(0); i++)\n {\n for (int j = 0; j < array.GetLength(1); j++)\n {\n int a = i;\n int b = j;\n Ref<T> refT = new Ref<T>(() => array[a, b], z => { array[a, b] = z; });\n dataView[i][j] = refT;\n }\n }\n return dataView;\n}\n</code></pre>\n\n<p>This would almost be enough to bind to but the Path in the Binding will point to the Ref object instead of the Ref.Value which we need so we have to change this when the Columns get generated.</p>\n\n<pre><code><DataGrid Name=\"c_dataGrid\"\n RowHeaderWidth=\"0\"\n ColumnHeaderHeight=\"0\"\n AutoGenerateColumns=\"True\"\n AutoGeneratingColumn=\"c_dataGrid_AutoGeneratingColumn\"/>\n\nprivate void c_dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n{\n DataGridTextColumn column = e.Column as DataGridTextColumn;\n Binding binding = column.Binding as Binding;\n binding.Path = new PropertyPath(binding.Path.Path + \".Value\");\n}\n</code></pre>\n\n<p>And after this we can use</p>\n\n<pre><code>c_dataGrid.ItemsSource = BindingHelper.GetBindable2DArray<int>(m_intArray);\n</code></pre>\n\n<p>And the output will look like this</p>\n\n<p><img src=\"https://i.stack.imgur.com/FvZro.png\" alt=\"alt text\"></p>\n\n<p>Any changes made in the <code>DataGrid</code> will be reflected in the m_intArray.</p>\n"
},
{
"answer_id": 8326875,
"author": "CitizenInsane",
"author_id": 684399,
"author_profile": "https://Stackoverflow.com/users/684399",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another solution based on <a href=\"https://stackoverflow.com/a/4002409/684399\">Meleak</a>'s answer but without requiring for an <code>AutoGeneratingColumn</code> event handler in the code behind of each binded <code>DataGrid</code>:</p>\n\n<pre><code>public static DataView GetBindable2DArray<T>(T[,] array)\n{\n var table = new DataTable();\n for (var i = 0; i < array.GetLength(1); i++)\n {\n table.Columns.Add(i+1, typeof(bool))\n .ExtendedProperties.Add(\"idx\", i); // Save original column index\n }\n for (var i = 0; i < array.GetLength(0); i++)\n {\n table.Rows.Add(table.NewRow());\n }\n\n var view = new DataView(table);\n for (var ri = 0; ri < array.GetLength(0); ri++)\n {\n for (var ci = 0; ci < array.GetLength(1); ci++)\n {\n view[ri][ci] = array[ri, ci];\n }\n }\n\n // Avoids writing an 'AutogeneratingColumn' handler\n table.ColumnChanged += (s, e) => \n {\n var ci = (int)e.Column.ExtendedProperties[\"idx\"]; // Retrieve original column index\n var ri = e.Row.Table.Rows.IndexOf(e.Row); // Retrieve row index\n\n array[ri, ci] = (T)view[ri][ci];\n };\n\n return view;\n}\n</code></pre>\n"
},
{
"answer_id": 31103075,
"author": "Johan Larsson",
"author_id": 1069200,
"author_profile": "https://Stackoverflow.com/users/1069200",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a small library of attached properties for the <code>DataGrid</code>. \n<a href=\"https://github.com/JohanLarsson/Gu.Wpf.DataGrid2D\" rel=\"noreferrer\">Here is the source</a></p>\n\n<p>Sample, where Data2D is <code>int[,]</code>:</p>\n\n<pre><code><DataGrid HeadersVisibility=\"None\"\n dataGrid2D:Source2D.ItemsSource2D=\"{Binding Data2D}\" />\n</code></pre>\n\n<p>Renders:\n<img src=\"https://i.stack.imgur.com/uYv8v.png\" alt=\"enter image description here\"></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509/"
] |
I have a 2-dimensional array of objects and I basically want to databind each one to a cell in a WPF grid. Currently I have this working but I am doing most of it procedurally. I create the correct number of row and column definitions, then I loop through the cells and create the controls and set up the correct bindings for each one.
At a minimum I would like to be able to use a template to specify the controls and bindings in xaml. Ideally I would like to get rid of the procedural code and just do it all with databinding, but I'm not sure that's possible.
Here is the code I am currently using:
```
public void BindGrid()
{
m_Grid.Children.Clear();
m_Grid.ColumnDefinitions.Clear();
m_Grid.RowDefinitions.Clear();
for (int x = 0; x < MefGrid.Width; x++)
{
m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });
}
for (int y = 0; y < MefGrid.Height; y++)
{
m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });
}
for (int x = 0; x < MefGrid.Width; x++)
{
for (int y = 0; y < MefGrid.Height; y++)
{
Cell cell = (Cell)MefGrid[x, y];
SolidColorBrush brush = new SolidColorBrush();
var binding = new Binding("On");
binding.Converter = new BoolColorConverter();
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
var rect = new Rectangle();
rect.DataContext = cell;
rect.Fill = brush;
rect.SetValue(Grid.RowProperty, y);
rect.SetValue(Grid.ColumnProperty, x);
m_Grid.Children.Add(rect);
}
}
}
```
|
The purpose of the Grid is not for real databinding, it is just a panel. I am listing down the easiest way to accomplish the visualization of a two dimensional list
```
<Window.Resources>
<DataTemplate x:Key="DataTemplate_Level2">
<Button Content="{Binding}" Height="40" Width="50" Margin="4,4,4,4"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplate_Level1">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl x:Name="lst" ItemTemplate="{DynamicResource DataTemplate_Level1}"/>
</Grid>
```
And in the code behind set the ItemsSource of lst with a TwoDimentional data structure.
```
public Window1()
{
List<List<int>> lsts = new List<List<int>>();
for (int i = 0; i < 5; i++)
{
lsts.Add(new List<int>());
for (int j = 0; j < 5; j++)
{
lsts[i].Add(i * 10 + j);
}
}
InitializeComponent();
lst.ItemsSource = lsts;
}
```
This gives you the following screen as output. You can edit the DataTemplate\_Level2 to add more specific data of your object.

|
276,827 |
<p>I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".</p>
<pre><code>char *StringPadRight(char *string, int padded_len, char *pad) {
int len = (int) strlen(string);
if (len >= padded_len) {
return string;
}
int i;
for (i = 0; i < padded_len - len; i++) {
strcat(string, pad);
}
return string;
}
</code></pre>
<p>It works but has some weird side effects... some of the other variables get changed. How can I fix this?</p>
|
[
{
"answer_id": 276835,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "<p>The argument you passed \"Hello\" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.</p>\n\n<pre><code>char buffer[1024];\nmemset(buffer, 0, sizeof(buffer));\nstrncpy(buffer, \"Hello\", sizeof(buffer));\nStringPadRight(buffer, 10, \"0\");\n</code></pre>\n\n<p>Edit: Corrected from stack to constant data area.</p>\n"
},
{
"answer_id": 276836,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You must make sure that the input string has enough space to hold all the padding characters. Try this:</p>\n\n<pre><code>char hello[11] = \"Hello\";\nStringPadRight(hello, 10, \"0\");\n</code></pre>\n\n<p>Note that I allocated 11 bytes for the <code>hello</code> string to account for the null terminator at the end.</p>\n"
},
{
"answer_id": 276837,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>The function itself looks fine to me. The problem could be that you aren't allocating enough space for your string to pad that many characters onto it. You could avoid this problem in the future by passing a <code>size_of_string</code> argument to the function and make sure you don't pad the string when the length is about to be greater than the size.</p>\n"
},
{
"answer_id": 276851,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Oh okay, makes sense. So I did this:</p>\n\n<pre><code> char foo[10] = \"hello\";\n char padded[16];\n strcpy(padded, foo);\n printf(\"%s\", StringPadRight(padded, 15, \" \"));\n</code></pre>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 276869,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 9,
"selected": true,
"text": "<p>It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long</p>\n\n<pre><code>printf(\"|%-10s|\", \"Hello\");\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>|Hello |\n</code></pre>\n\n<p>In this case the - symbol means \"Left align\", the 10 means \"Ten characters in field\" and the s means you are aligning a string.</p>\n\n<p>Printf style formatting is available in many languages and has plenty of references on the web. Here is <a href=\"http://en.cppreference.com/w/c/io/fprintf\" rel=\"noreferrer\">one of many pages</a> explaining the formatting flags. As usual <a href=\"http://en.wikipedia.org/wiki/Printf\" rel=\"noreferrer\">WikiPedia's printf page</a> is of help too (mostly a history lesson of how widely printf has spread).</p>\n"
},
{
"answer_id": 9741091,
"author": "J Jorgenson",
"author_id": 310231,
"author_profile": "https://Stackoverflow.com/users/310231",
"pm_score": 6,
"selected": false,
"text": "<p>For 'C' there is alternative (more complex) use of [s]printf that does not require any malloc() or pre-formatting, when custom padding is desired.</p>\n\n<p>The trick is to use '*' length specifiers (min and max) for %s, plus a string filled with your padding character to the maximum potential length. </p>\n\n<pre><code>int targetStrLen = 10; // Target output length \nconst char *myString=\"Monkey\"; // String for output \nconst char *padding=\"#####################################################\";\n\nint padLen = targetStrLen - strlen(myString); // Calc Padding length\nif(padLen < 0) padLen = 0; // Avoid negative length\n\nprintf(\"[%*.*s%s]\", padLen, padLen, padding, myString); // LEFT Padding \nprintf(\"[%s%*.*s]\", myString, padLen, padLen, padding); // RIGHT Padding \n</code></pre>\n\n<p>The \"%*.*s\" can be placed before OR after your \"%s\", depending desire for LEFT or RIGHT padding.</p>\n\n<blockquote>\n <p><code>[####Monkey] <-- Left padded, \"%*.*s%s\"</code> <br>\n <code>[Monkey####] <-- Right padded, \"%s%*.*s\"</code></p>\n</blockquote>\n\n<p>I found that the PHP printf (<a href=\"http://www.php.net/manual/en/function.sprintf.php\">here</a>) does support the ability to give a custom padding character, <em>using the single quote (') followed by your custom padding character</em>, within the %s format.<br>\n <code>printf(\"[%'#10s]\\n\", $s); // use the custom padding character '#'</code><br>\nproduces:<br>\n <code>[####monkey]</code></p>\n"
},
{
"answer_id": 28070342,
"author": "user4478828",
"author_id": 4478828,
"author_profile": "https://Stackoverflow.com/users/4478828",
"pm_score": 0,
"selected": false,
"text": "<p>One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal \"Hello\" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.</p>\n"
},
{
"answer_id": 38697789,
"author": "Naga",
"author_id": 5036010,
"author_profile": "https://Stackoverflow.com/users/5036010",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\nusing namespace std;\n\nint main() {\n // your code goes here\n int pi_length=11; //Total length \n char *str1;\n const char *padding=\"0000000000000000000000000000000000000000\";\n const char *myString=\"Monkey\";\n\n int padLen = pi_length - strlen(myString); //length of padding to apply\n\n if(padLen < 0) padLen = 0; \n\n str1= (char *)malloc(100*sizeof(char));\n\n sprintf(str1,\"%*.*s%s\", padLen, padLen, padding, myString);\n\n printf(\"%s --> %d \\n\",str1,strlen(str1));\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 49163578,
"author": "Izya Budman",
"author_id": 9120297,
"author_profile": "https://Stackoverflow.com/users/9120297",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#include <stdio.h>\n#include <string.h>\n\nint main(void) {\n char buf[BUFSIZ] = { 0 };\n char str[] = \"Hello\";\n char fill = '#';\n int width = 20; /* or whatever you need but less than BUFSIZ ;) */\n\n printf(\"%s%s\\n\", (char*)memset(buf, fill, width - strlen(str)), str);\n\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ gcc -Wall -ansi -pedantic padding.c\n$ ./a.out \n###############Hello\n</code></pre>\n"
},
{
"answer_id": 52043319,
"author": "Ayodeji",
"author_id": 7499394,
"author_profile": "https://Stackoverflow.com/users/7499394",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include<stdio.h>\n#include <string.h>\n\n\nvoid padLeft(int length, char pad, char* inStr,char* outStr) {\n int minLength = length * sizeof(char);\n if (minLength < sizeof(outStr)) {\n return;\n }\n\n int padLen = length - strlen(inStr);\n padLen = padLen < 0 ? 0 : padLen;\n\n memset(outStr, 0, sizeof(outStr));\n memset(outStr, pad,padLen);\n memcpy(outStr+padLen, inStr, minLength - padLen);\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".
```
char *StringPadRight(char *string, int padded_len, char *pad) {
int len = (int) strlen(string);
if (len >= padded_len) {
return string;
}
int i;
for (i = 0; i < padded_len - len; i++) {
strcat(string, pad);
}
return string;
}
```
It works but has some weird side effects... some of the other variables get changed. How can I fix this?
|
It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long
```
printf("|%-10s|", "Hello");
```
will output
```
|Hello |
```
In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.
Printf style formatting is available in many languages and has plenty of references on the web. Here is [one of many pages](http://en.cppreference.com/w/c/io/fprintf) explaining the formatting flags. As usual [WikiPedia's printf page](http://en.wikipedia.org/wiki/Printf) is of help too (mostly a history lesson of how widely printf has spread).
|
276,843 |
<p>Is there a way short of writing a seperate batch file or adding a system call to pause or getch or a breakpoint right before the end of the main function to keep a command window open after a command line application has finished running?</p>
<p>Put differently, is there a way in the project properties to run another command after running the target path? If my program is "foo.exe", something equivalent to a batch file containing</p>
<pre><code>@foo
@pause
</code></pre>
<p>Edit: added "or a getch or a breakpoint"</p>
|
[
{
"answer_id": 276849,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 0,
"selected": false,
"text": "<p>In C++</p>\n\n<pre><code>#include <conio.h>\n\n// .. Your code\n\nint main()\n{\n // More of your code\n\n // Tell the user to press a key \n getch(); // Get one character from the user (i.e a keypress)\n\n return 0;\n\n}\n</code></pre>\n\n<p>If you are in a batch file, the command \"pause\" outputs \"Press any key to continue\" and waits for a keypress.</p>\n"
},
{
"answer_id": 276850,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>If running in the debugger (going by the title of your question), I just put a breakpoint at the closing brace in the main method.</p>\n"
},
{
"answer_id": 276854,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 0,
"selected": false,
"text": "<p>If one has access to source code,</p>\n\n<p>1.) Will adding a getch() added just before main ends, not puase the application executuion, while displaying the console applications console window as it was?\nBasically add any code which waits on a keyboard input</p>\n\n<p>-AD</p>\n"
},
{
"answer_id": 276858,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": false,
"text": "<p>As you may know, at least in the C# project system, pressing Ctrl-F5 will add a \"press any key to continue\" to the end. But this doesn't run under the debugger, so I endorse the prior answer that said 'put a breakpoint at the end of main'.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34799/"
] |
Is there a way short of writing a seperate batch file or adding a system call to pause or getch or a breakpoint right before the end of the main function to keep a command window open after a command line application has finished running?
Put differently, is there a way in the project properties to run another command after running the target path? If my program is "foo.exe", something equivalent to a batch file containing
```
@foo
@pause
```
Edit: added "or a getch or a breakpoint"
|
As you may know, at least in the C# project system, pressing Ctrl-F5 will add a "press any key to continue" to the end. But this doesn't run under the debugger, so I endorse the prior answer that said 'put a breakpoint at the end of main'.
|
276,856 |
<p>I have a lot of assignments where I have to continually update a Makefile as I add more subsequently numbered C programs. Is there a way to do this with a loop which iterates over the values 1.1, 1.2, 1.3, etc.?</p>
<pre><code>all: 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9
1.1: 1.1.o
gcc -o 1.1 $(FLAGS) 1.1.o
1.1.o: 1.1.c
gcc -c $(FLAGS) 1.1.c
1.2: 1.2.o
gcc -o 1.2 $(FLAGS) 1.2.o
1.2.o: 1.2.c
gcc -c $(FLAGS) 1.2.c
1.3: 1.3.o
gcc -o 1.3 $(FLAGS) 1.3.o
1.3.o: 1.3.c
gcc -c $(FLAGS) 1.3.c
1.4: 1.4.o
gcc -o 1.4 $(FLAGS) 1.4.o
1.4.o: 1.4.c
gcc -c $(FLAGS) 1.4.c
1.5: 1.5.o
gcc -o 1.5 $(FLAGS) 1.5.o
1.5.o: 1.5.c
gcc -c $(FLAGS) 1.5.c
1.6: 1.6.o
gcc -o 1.6 $(FLAGS) 1.6.o
1.6.o: 1.6.c
gcc -c $(FLAGS) 1.6.c
1.7: 1.7.o
gcc -o 1.7 $(FLAGS) 1.7.o
1.7.o: 1.7.c
gcc -c $(FLAGS) 1.7.c
1.8: 1.8.o
gcc -o 1.8 $(FLAGS) 1.8.o
1.8.o: 1.8.c
gcc -c $(FLAGS) 1.8.c
1.9: 1.9.o
gcc -o 1.9 $(FLAGS) 1.9.o
1.9.o: 1.9.c
gcc -c $(FLAGS) 1.9.c
clean:
rm -f *.o
rm -f 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9</code></pre>
|
[
{
"answer_id": 276860,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 0,
"selected": false,
"text": "<p>Yes; you can use shell commands in a Makefile, and make itself may offer the looping you need. There are oodles of good examples all over the web; assuming from your use of <code>gcc</code> that you're also using GNU make, try here:</p>\n\n<p><a href=\"http://www.gnu.org/software/make/manual/make.html#Foreach-Function\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/make/manual/make.html#Foreach-Function</a></p>\n"
},
{
"answer_id": 276863,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "<p>You want a <a href=\"http://owen.sj.ca.us/rkowen/howto/slides/make/slides/makesuff.html\" rel=\"nofollow noreferrer\">suffix rule</a>, not a loop.</p>\n"
},
{
"answer_id": 276873,
"author": "David Martin",
"author_id": 34879,
"author_profile": "https://Stackoverflow.com/users/34879",
"pm_score": 2,
"selected": false,
"text": "<p>Try a rule like:</p>\n\n<pre><code>OBJECTS = 1.1.o 1.2.o 1.3.o\n\nall: $(OBJECTS)\n\n%.o: %.c\n gcc $(FLAGS) %< -o $*\n</code></pre>\n\n<p>Then you just need to add the extra object to the list and all is sweet.</p>\n\n<p>Implicit rules help you really minimise the copy/paste cycle in your makefile.</p>\n\n<p><a href=\"http://www.gnu.org/software/autoconf/manual/make/Implicit-Rules.html#Implicit-Rules\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/autoconf/manual/make/Implicit-Rules.html#Implicit-Rules</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18091/"
] |
I have a lot of assignments where I have to continually update a Makefile as I add more subsequently numbered C programs. Is there a way to do this with a loop which iterates over the values 1.1, 1.2, 1.3, etc.?
```
all: 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9
1.1: 1.1.o
gcc -o 1.1 $(FLAGS) 1.1.o
1.1.o: 1.1.c
gcc -c $(FLAGS) 1.1.c
1.2: 1.2.o
gcc -o 1.2 $(FLAGS) 1.2.o
1.2.o: 1.2.c
gcc -c $(FLAGS) 1.2.c
1.3: 1.3.o
gcc -o 1.3 $(FLAGS) 1.3.o
1.3.o: 1.3.c
gcc -c $(FLAGS) 1.3.c
1.4: 1.4.o
gcc -o 1.4 $(FLAGS) 1.4.o
1.4.o: 1.4.c
gcc -c $(FLAGS) 1.4.c
1.5: 1.5.o
gcc -o 1.5 $(FLAGS) 1.5.o
1.5.o: 1.5.c
gcc -c $(FLAGS) 1.5.c
1.6: 1.6.o
gcc -o 1.6 $(FLAGS) 1.6.o
1.6.o: 1.6.c
gcc -c $(FLAGS) 1.6.c
1.7: 1.7.o
gcc -o 1.7 $(FLAGS) 1.7.o
1.7.o: 1.7.c
gcc -c $(FLAGS) 1.7.c
1.8: 1.8.o
gcc -o 1.8 $(FLAGS) 1.8.o
1.8.o: 1.8.c
gcc -c $(FLAGS) 1.8.c
1.9: 1.9.o
gcc -o 1.9 $(FLAGS) 1.9.o
1.9.o: 1.9.c
gcc -c $(FLAGS) 1.9.c
clean:
rm -f *.o
rm -f 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9
```
|
You want a [suffix rule](http://owen.sj.ca.us/rkowen/howto/slides/make/slides/makesuff.html), not a loop.
|
276,861 |
<p>I would like to dynamically hide a button in one of my views depending on a certain condition.</p>
<p>I tried adding some code to the view controller's <code>-viewWillAppear</code> method, to make the button hidden before displaying the actual view, but I still don't know how to do that.</p>
<p>I have a reference to the button through an IBOutlet, but I'm not sure how to move forward from here. For reference, this is a UIBarButtonItem instance.</p>
|
[
{
"answer_id": 276890,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": -1,
"selected": false,
"text": "<p>Just set the button's hidden property to true:</p>\n\n<pre><code>myButton.hidden = YES;\n</code></pre>\n"
},
{
"answer_id": 277052,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 7,
"selected": true,
"text": "<p>If you're trying to hide a UIBarButtonItem, you'll actually have to modify the contents of the parent bar. If it's a UIToolBar, you'll need to set the bar's items array to an array that doesn't include your item.</p>\n\n<pre><code>NSMutableArray *items = [[myToolbar.items mutableCopy] autorelease];\n[items removeObject: myButton];\nmyToolbar.items = items;\n</code></pre>\n"
},
{
"answer_id": 1209938,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Set the bar item to nil.</p>\n\n<p>For example:</p>\n\n<pre><code>self.navigationItem.leftBarButtonItem = nil;\n</code></pre>\n"
},
{
"answer_id": 1912277,
"author": "Gary Riley",
"author_id": 232642,
"author_profile": "https://Stackoverflow.com/users/232642",
"pm_score": 1,
"selected": false,
"text": "<p>This is what I did for button items that weren't part of the navigation bar (where Blank.png is a blank image I created that's the same size of the image it replaces):</p>\n\n<pre><code>theButton.enabled = NO;\ntheButton.image = [UIImage imageNamed: @\"Blank.png\"];\n</code></pre>\n"
},
{
"answer_id": 2640609,
"author": "Heather Shoemaker",
"author_id": 316896,
"author_profile": "https://Stackoverflow.com/users/316896",
"pm_score": 4,
"selected": false,
"text": "<p>So I tried Ben's winning approach but in the end I found it to be wrong for my purposes - though I'm sure it depends upon what you're trying to do. I was trying to show a nav bar button under certain conditions only and then hide it as soon as the condition was no longer met (in my case it's a \"Done\" button used to hide the keyboard associated with a UITextView. It should only be displayed when the user is typing in the text view). My steps were as follows:</p>\n\n<ol>\n<li><p>I added a UIBarButtonItem as a\nproperty in my UIViewController\nclass. I instantiate it in the\ninitWithNibName method. </p></li>\n<li><p>I assigned the UIBarButtonItem property as the\nrightBarButtonItem in the nav bar as\nsoon as the user starts typing in\nthe text view.</p></li>\n<li><p>I set the UIBarButtonItem property\nto nil when the user is done typing.</p></li>\n</ol>\n\n<p>It's working like a charm. I'm adding some code samples below.</p>\n\n<p>First to instantiate the button in my view controller init method:</p>\n\n<pre><code>barButtonItemDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];\n</code></pre>\n\n<p>Then I set it as the right bar button in the delegate method that is called as soon as the user starts to edit the text view:</p>\n\n<pre><code>self.navigationItem.rightBarButtonItem=[self barButtonItemDone];\n</code></pre>\n\n<p>Finally, when the button itself is clicked, a method called \"done\" is called and I just set the rightBarButtonItem to nil inside that method:</p>\n\n<pre><code>self.navigationItem.rightBarButtonItem=nil;\n</code></pre>\n"
},
{
"answer_id": 3550375,
"author": "Sara",
"author_id": 402150,
"author_profile": "https://Stackoverflow.com/users/402150",
"pm_score": 3,
"selected": false,
"text": "<p>If all that one is trying to hide is the back button in the navigation bar, there is an easier way:</p>\n\n<pre><code>self.navigationItem.hidesBackButton = YES;\n</code></pre>\n\n<p>Quote from developer documentation:</p>\n\n<blockquote>\n <p>hidesBackButton</p>\n \n <p>A Boolean value that determines whether the back button is hidden.</p>\n \n <p>@property(nonatomic, assign) BOOL hidesBackButton</p>\n \n <p>Discussion</p>\n \n <p>YES if the back button is hidden when this navigation item is the top\n item; otherwise, NO. The default value\n is NO.</p>\n \n <p>Availability</p>\n \n <p>Available in iPhone OS 2.0 and later.</p>\n</blockquote>\n"
},
{
"answer_id": 3945625,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 2,
"selected": false,
"text": "<p>The best solution to this is less technical. All you need to do is create your normal navigation bar (top) or toolbar (bottom), but without the optional button. Then create another identical, but shorter bar which you then place at the part you want the optional button and create your optional button on this second shorter bar.</p>\n\n<p>Now you can call <code>hidden = YES</code> on the whole additional bar.</p>\n\n<p>The bars seamlessly overlap for me, your mileage may vary.</p>\n"
},
{
"answer_id": 7290517,
"author": "Jon",
"author_id": 463059,
"author_profile": "https://Stackoverflow.com/users/463059",
"pm_score": 1,
"selected": false,
"text": "<p>Ben's answer is technically correct, though when I try it on my custom UIToolbar, the items space out in a way that I don't like, because I use UIBarButtonSystemItemFlexibleSpace items. </p>\n\n<p>If you want your other items to stay in the same place, you'll either have to set your flexible spaces to fixed spaces, or try what I did:</p>\n\n<pre><code>[filterBarButton.customView setHidden:YES];\n</code></pre>\n\n<p>note: this only works if your UIBarButtonItem uses custom views.</p>\n"
},
{
"answer_id": 8298969,
"author": "Michael",
"author_id": 1031265,
"author_profile": "https://Stackoverflow.com/users/1031265",
"pm_score": 3,
"selected": false,
"text": "<p>This is a bit of a hack, but it works in my case (and it properly handles dynamic spacing):</p>\n\n<p>To hide:</p>\n\n<pre><code>myButton.width = 0.1;\n</code></pre>\n\n<p>To show:</p>\n\n<pre><code>myButton.width = 0.0;\n</code></pre>\n\n<p>A width of 0.0 is \"auto width\", and with a width of 0.1, the button totally disappears (not even a \"sliver\" of a button, though I haven't tried this on a retina display).</p>\n"
},
{
"answer_id": 8331436,
"author": "Christopher Shortt",
"author_id": 1074063,
"author_profile": "https://Stackoverflow.com/users/1074063",
"pm_score": 1,
"selected": false,
"text": "<p>If you add a <code>UIButton</code> to the <code>UIBarButtonItem</code> rather than just use the <code>UIBarButtonItem</code>.</p>\n\n<p>You can then assign <code>UIButton.hidden</code> to <code>TRUE</code> or <code>YES</code> and it (and the <code>UIBarButtonItem</code>) will not be visible or active.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 8949434,
"author": "jonnysamps",
"author_id": 201134,
"author_profile": "https://Stackoverflow.com/users/201134",
"pm_score": 3,
"selected": false,
"text": "<p>Another hacky solution:</p>\n\n<pre><code>myButton.customView = [[UIView alloc] init];\n</code></pre>\n"
},
{
"answer_id": 20509232,
"author": "Michael DiStefano",
"author_id": 2533208,
"author_profile": "https://Stackoverflow.com/users/2533208",
"pm_score": 2,
"selected": false,
"text": "<p>This answer is regarding text-based UIBarButtonItems, however, the same concept could be applied to other types of buttons as well. Note that this will allow one to both hide <em>and</em> show the item again. Many of the answers above (those setting the button's value to nil, for example, do not allow the button to be re-shown if that's desired).</p>\n\n<p>TL;DR:</p>\n\n<pre><code>if (shouldShowMyBarButtonItem) {\n self.myBarButtonItem.title = nil;\n self.myBarButtonItem.action = nil;\n} else if (!shouldShowMyBarButtonItem) {\n self.myBarButtonItem.title = @\"Title\";\n self.myBarButtonItem.action = @selector(mySelector:);\n}\n</code></pre>\n\n<p>The long version:</p>\n\n<p>The UIBarButtonItem I was trying to hide is in a UIToolbar, not a UINavigationBar so all the suggestions that access the left (or right) barButtonItem properties on the navigation item don't work for me. Also, as stated above, I wished to re-show the button when circumstances change.</p>\n\n<p>Michael's suggestion came closest to working, however, with iOS 7 at least, there was still a <em>very</em> small sliver of the button displayed that was tappable. In my app, tapping the item when it's not supposed to be available was unacceptable. The above code both hides and, crucially, deactivates the button.</p>\n\n<p>I call the above code in a private refresh method, which is called when a user event occurs.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
I would like to dynamically hide a button in one of my views depending on a certain condition.
I tried adding some code to the view controller's `-viewWillAppear` method, to make the button hidden before displaying the actual view, but I still don't know how to do that.
I have a reference to the button through an IBOutlet, but I'm not sure how to move forward from here. For reference, this is a UIBarButtonItem instance.
|
If you're trying to hide a UIBarButtonItem, you'll actually have to modify the contents of the parent bar. If it's a UIToolBar, you'll need to set the bar's items array to an array that doesn't include your item.
```
NSMutableArray *items = [[myToolbar.items mutableCopy] autorelease];
[items removeObject: myButton];
myToolbar.items = items;
```
|
276,867 |
<p>In this <a href="https://stackoverflow.com/questions/275545/does-aspnet-mvc-framework-support-asynchronous-page-execution">question & answer</a>, I found one way to make ASP.NET MVC support asynchronous processing. However, I cannot make it work.</p>
<p>Basically, the idea is to create a new implementation of IRouteHandler which has only one method <strong><em>GetHttpHandler</em></strong>. The <strong><em>GetHttpHandler</em></strong> method should return an <code>IHttpAsyncHandler</code> implementation instead of just <code>IHttpHandler</code>, because <code>IHttpAsyncHandler</code> has Begin/EndXXXX pattern API.</p>
<pre><code>public class AsyncMvcRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new AsyncMvcHandler(requestContext);
}
class AsyncMvcHandler : IHttpAsyncHandler, IRequiresSessionState
{
public AsyncMvcHandler(RequestContext context)
{
}
// IHttpHandler members
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext httpContext) { throw new NotImplementedException(); }
// IHttpAsyncHandler members
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
throw new NotImplementedException();
}
public void EndProcessRequest(IAsyncResult result)
{
throw new NotImplementedException();
}
}
}
</code></pre>
<p>Then, in the RegisterRoutes method of file Global.asax.cs, register this class <strong><em>AsyncMvcRouteHandler</em></strong>.</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new Route("{controller}/{action}/{id}", new AsyncMvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
});
}
</code></pre>
<p>I set breakpoint at <strong><em>ProcessRequest</em></strong>, <strong><em>BeginProcessRequest</em></strong> and <strong><em>EndProcessRequest</em></strong>. Only <strong><em>ProcessRequest</em></strong> is executed. In another word, even though <strong><em>AsyncMvcHandler</em></strong> implements <strong><em>IHttpAsyncHandler</em></strong>. ASP.NET MVC doesn't know that and just handle it as an <code>IHttpHandler</code> implementation.</p>
<p>How to make ASP.NET MVC treat <strong><em>AsyncMvcHandler</em></strong> as <strong><em>IHttpAsyncHandler</em></strong> so we can have asynchronous page processing?</p>
|
[
{
"answer_id": 278831,
"author": "MrJavaGuy",
"author_id": 7138,
"author_profile": "https://Stackoverflow.com/users/7138",
"pm_score": 0,
"selected": false,
"text": "<p>I have tried to do this in the past, I manage to either get the view to render and then all the async tasks would finish. Or the async tasks to finish but the view would not render.</p>\n\n<p>I created a RouteCollectionExtensions based on the original MVC code. In my AsyncMvcHandler, I had an empty method (no exception) for ProcessMethod.</p>\n"
},
{
"answer_id": 282827,
"author": "Morgan Cheng",
"author_id": 26349,
"author_profile": "https://Stackoverflow.com/users/26349",
"pm_score": 3,
"selected": true,
"text": "<p>After hours of hassle with the code, I found out the issue.</p>\n\n<p>In my Visual Studio 2008, when I press Ctrl+F5, the Application Development Server is launched and IE is popped up to access \"<a href=\"http://localhost:3573/\" rel=\"nofollow noreferrer\">http://localhost:3573/</a>\". In this case, the sync API <strong><em>ProcessRequest</em></strong> is invoked. The stack trace is like this.</p>\n\n<blockquote>\n <blockquote>\n <p>MyMvcApplication.DLL!MyMvcApplication.AsyncMvcRouteHandler.AsyncMvcHandler.ProcessRequest(System.Web.HttpContext\n httpContext =\n {System.Web.HttpContext}) Line 59 C# \n System.Web.Mvc.dll!System.Web.Mvc.MvcHttpHandler.VerifyAndProcessRequest(System.Web.IHttpHandler\n httpHandler,\n System.Web.HttpContextBase\n httpContext) + 0x19 bytes<br>\n System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.ProcessRequest(System.Web.HttpContextBase\n httpContext) + 0x66 bytes<br>\n System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.ProcessRequest(System.Web.HttpContext\n httpContext) + 0x28 bytes<br>\n System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext\n context) + 0x8 bytes<br>\n MyMvcApplication.DLL!MyMvcApplication._Default.Page_Load(object\n sender = {ASP.default_aspx},\n System.EventArgs e =\n {System.EventArgs}) Line 13 + 0x1a\n bytes C#</p>\n </blockquote>\n</blockquote>\n\n<p>However, when I change the URL in IE to be \"<a href=\"http://localhost:3573/whatever.mvc\" rel=\"nofollow noreferrer\">http://localhost:3573/whatever.mvc</a>\", it hits the <strong><em>BeginProcessRequest</em></strong>. The stack trace is like this.</p>\n\n<blockquote>\n <blockquote>\n <p>MyMvcApplication.DLL!MyMvcApplication.AsyncMvcRouteHandler.AsyncMvcHandler.BeginProcessRequest(System.Web.HttpContext\n context = {System.Web.HttpContext},\n System.AsyncCallback cb = {Method =\n {Void\n OnAsyncHandlerCompletion(System.IAsyncResult)}},\n object extraData = null) Line 66 C# \n System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\n + 0x249 bytes System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep\n step =\n {System.Web.HttpApplication.CallHandlerExecutionStep},\n ref bool completedSynchronously =\n true) + 0x9c bytes<br>\n System.Web.dll!System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(System.Exception\n error) + 0x133 bytes<br>\n System.Web.dll!System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext\n context, System.AsyncCallback cb,\n object extraData) + 0x7c bytes<br>\n System.Web.dll!System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest\n wr =\n {Microsoft.VisualStudio.WebHost.Request})\n + 0x17c bytes System.Web.dll!System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest\n wr) + 0x63 bytes<br>\n System.Web.dll!System.Web.HttpRuntime.ProcessRequest(System.Web.HttpWorkerRequest\n wr) + 0x47 bytes<br>\n WebDev.WebHost.dll!Microsoft.VisualStudio.WebHost.Request.Process()\n + 0xf1 bytes WebDev.WebHost.dll!Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Microsoft.VisualStudio.WebHost.Connection\n conn) + 0x4e bytes</p>\n </blockquote>\n</blockquote>\n\n<p>It seems that only url with \".mvc\" suffix can make asynchronous API invoked.</p>\n"
},
{
"answer_id": 490003,
"author": "LaserJesus",
"author_id": 45207,
"author_profile": "https://Stackoverflow.com/users/45207",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, however I found that it was because my catch all route handler:</p>\n\n<pre><code>routes.MapRoute(\n \"Default\", \n \"{controller}/{action}\", \n new { controller = \"Home\", action = \"Index\" } \n);\n</code></pre>\n\n<p>Was picking up the request, not the custom route I added that dealt with the async route handler. Perhaps by using the .mvc in your custom route defintion you created a distinction so that it was used rather than the synchronous catch-all.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
In this [question & answer](https://stackoverflow.com/questions/275545/does-aspnet-mvc-framework-support-asynchronous-page-execution), I found one way to make ASP.NET MVC support asynchronous processing. However, I cannot make it work.
Basically, the idea is to create a new implementation of IRouteHandler which has only one method ***GetHttpHandler***. The ***GetHttpHandler*** method should return an `IHttpAsyncHandler` implementation instead of just `IHttpHandler`, because `IHttpAsyncHandler` has Begin/EndXXXX pattern API.
```
public class AsyncMvcRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new AsyncMvcHandler(requestContext);
}
class AsyncMvcHandler : IHttpAsyncHandler, IRequiresSessionState
{
public AsyncMvcHandler(RequestContext context)
{
}
// IHttpHandler members
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext httpContext) { throw new NotImplementedException(); }
// IHttpAsyncHandler members
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
throw new NotImplementedException();
}
public void EndProcessRequest(IAsyncResult result)
{
throw new NotImplementedException();
}
}
}
```
Then, in the RegisterRoutes method of file Global.asax.cs, register this class ***AsyncMvcRouteHandler***.
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new Route("{controller}/{action}/{id}", new AsyncMvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
});
}
```
I set breakpoint at ***ProcessRequest***, ***BeginProcessRequest*** and ***EndProcessRequest***. Only ***ProcessRequest*** is executed. In another word, even though ***AsyncMvcHandler*** implements ***IHttpAsyncHandler***. ASP.NET MVC doesn't know that and just handle it as an `IHttpHandler` implementation.
How to make ASP.NET MVC treat ***AsyncMvcHandler*** as ***IHttpAsyncHandler*** so we can have asynchronous page processing?
|
After hours of hassle with the code, I found out the issue.
In my Visual Studio 2008, when I press Ctrl+F5, the Application Development Server is launched and IE is popped up to access "<http://localhost:3573/>". In this case, the sync API ***ProcessRequest*** is invoked. The stack trace is like this.
>
>
> >
> > MyMvcApplication.DLL!MyMvcApplication.AsyncMvcRouteHandler.AsyncMvcHandler.ProcessRequest(System.Web.HttpContext
> > httpContext =
> > {System.Web.HttpContext}) Line 59 C#
> > System.Web.Mvc.dll!System.Web.Mvc.MvcHttpHandler.VerifyAndProcessRequest(System.Web.IHttpHandler
> > httpHandler,
> > System.Web.HttpContextBase
> > httpContext) + 0x19 bytes
> >
> > System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.ProcessRequest(System.Web.HttpContextBase
> > httpContext) + 0x66 bytes
> >
> > System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.ProcessRequest(System.Web.HttpContext
> > httpContext) + 0x28 bytes
> >
> > System.Web.Routing.dll!System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext
> > context) + 0x8 bytes
> >
> > MyMvcApplication.DLL!MyMvcApplication.\_Default.Page\_Load(object
> > sender = {ASP.default\_aspx},
> > System.EventArgs e =
> > {System.EventArgs}) Line 13 + 0x1a
> > bytes C#
> >
> >
> >
>
>
>
However, when I change the URL in IE to be "<http://localhost:3573/whatever.mvc>", it hits the ***BeginProcessRequest***. The stack trace is like this.
>
>
> >
> > MyMvcApplication.DLL!MyMvcApplication.AsyncMvcRouteHandler.AsyncMvcHandler.BeginProcessRequest(System.Web.HttpContext
> > context = {System.Web.HttpContext},
> > System.AsyncCallback cb = {Method =
> > {Void
> > OnAsyncHandlerCompletion(System.IAsyncResult)}},
> > object extraData = null) Line 66 C#
> > System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
> > + 0x249 bytes System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep
> > step =
> > {System.Web.HttpApplication.CallHandlerExecutionStep},
> > ref bool completedSynchronously =
> > true) + 0x9c bytes
> >
> > System.Web.dll!System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(System.Exception
> > error) + 0x133 bytes
> >
> > System.Web.dll!System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext
> > context, System.AsyncCallback cb,
> > object extraData) + 0x7c bytes
> >
> > System.Web.dll!System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest
> > wr =
> > {Microsoft.VisualStudio.WebHost.Request})
> > + 0x17c bytes System.Web.dll!System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest
> > wr) + 0x63 bytes
> >
> > System.Web.dll!System.Web.HttpRuntime.ProcessRequest(System.Web.HttpWorkerRequest
> > wr) + 0x47 bytes
> >
> > WebDev.WebHost.dll!Microsoft.VisualStudio.WebHost.Request.Process()
> > + 0xf1 bytes WebDev.WebHost.dll!Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Microsoft.VisualStudio.WebHost.Connection
> > conn) + 0x4e bytes
> >
> >
> >
>
>
>
It seems that only url with ".mvc" suffix can make asynchronous API invoked.
|
276,891 |
<p>I'm trying to figure out how to drop/discard a request, I'm basically trying to implement a blocked list of IPs in my app to block spammers and I don't want to return any response (just ignore the request), is this possible in ASP.NET?</p>
<p>Edit: Some of the answers suggest that I could add them in the firewall, while this will certainly be better it's not suitable in my case. To make a long story short, I'm adding a moderation section to my website where moderators will check the posts awaiting moderation for spam (filtered by a spam fitler), I want the IP of the sender of some post to be added to the list of blocked IPs once a post is marked as spam by the moderator, this is why I wan to do it in the application.</p>
<p>Edit: Calling Response.End() returns a response to the user (even though it's empty), the whole purpose of my question was how not to return any response. Is this possible (even out of curiosity)? There's also Response.Close() which closes the socket but it sends notification (in TCP/IP) when it does this, I just wan to ignore as it if was never received (i.e. send nothing to the user)</p>
<p>Thanks</p>
|
[
{
"answer_id": 276894,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you could use </p>\n\n<pre><code>Response.Clear();\nResponse.End();\n</code></pre>\n"
},
{
"answer_id": 276899,
"author": "Austin",
"author_id": 32854,
"author_profile": "https://Stackoverflow.com/users/32854",
"pm_score": 2,
"selected": false,
"text": "<p>My first thought was what John suggested. The most ideal solution would be to add those IPs to the list of blocked IPs in your firewall if you have access to it, that way your application isn't having to do any processing at all.</p>\n"
},
{
"answer_id": 276939,
"author": "Kyle Trauberman",
"author_id": 21461,
"author_profile": "https://Stackoverflow.com/users/21461",
"pm_score": 2,
"selected": false,
"text": "<p><strong>EDIT:</strong> This might be better implemented as an HTTPModule instead of a handler, but the basic idea holds true. See <a href=\"http://www.kowitz.net/archive/2006/03/08/ihttpmodule-vs-ihttphandler.aspx\" rel=\"nofollow noreferrer\">http://www.kowitz.net/archive/2006/03/08/ihttpmodule-vs-ihttphandler.aspx</a> for more details</p>\n\n<hr>\n\n<p>You could probably do this using an httphandler, that way you won't have to worry about checking for this in your application code - its handled before your application is even executed.</p>\n\n<p><strong>Psudo code - not tested</strong></p>\n\n<pre><code>class IgnoreHandler : IHttpHandler\n{\n #region IHttpHandler Members\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n public void ProcessRequest(HttpContext context)\n {\n context.Response.Clear();\n context.Response.StatusCode = 401;\n context.Response.Status = \"Unauthorized\";\n context.Response.End();\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Obviously, if you want it to return HTTP 200 (OK) and a blank page, just remove the two lines referring to the StatusCode and Status.</p>\n\n<p>And then register it in web.config</p>\n\n<pre><code><httpHandlers>\n <add verb=\"*\" \n path=\"*\" \n validate=\"false\" \n type=\"MyNamespace.IgnoreHandler, MyAssembly\" />\n</httpHandlers>\n</code></pre>\n"
},
{
"answer_id": 276961,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 2,
"selected": false,
"text": "<p>For this type of thing, I would go with an <strong><a href=\"http://msdn.microsoft.com/en-us/library/t2yzs44b.aspx\" rel=\"nofollow noreferrer\">HTTP Module</a></strong> as opposed to doing this with a handler or a page. </p>\n\n<p>Why use a module instead of a handler? An HTTP Module is called earlier in the request pipeline. For these type of blacklisted requests, you want to drop the request as early and fast as possible. This means the earlier in the request you can drop the request, the better.</p>\n\n<p>You can read a little more about Modules vs Handlers <a href=\"http://msdn.microsoft.com/en-us/library/bb398986.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 277005,
"author": "JackCorn",
"author_id": 14919,
"author_profile": "https://Stackoverflow.com/users/14919",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest the best solution is not to give a specific \"no response\" but to give a more discouraging standard http error message. Whenever I am attempting to discourage unauthorised users I issue a page/url not found message as follows:</p>\n\n<pre><code>throw new HttpException(404, \"File not found - \" + Request.AppRelativeCurrentExecutionFilePath);</code></pre>\n\n<p>I think that this is very effective at convincing the person at the other end to give up and go away.</p>\n"
},
{
"answer_id": 277039,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to have a look at this <a href=\"http://www.angrypets.com/tools/rdos/\" rel=\"nofollow noreferrer\">http://www.angrypets.com/tools/rdos/</a>, which does a similar thing to what you are talking about, for similar reasons, and is implemented as a module.</p>\n"
},
{
"answer_id": 277866,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 0,
"selected": false,
"text": "<p>An other annoying but easy way to do it would be to Sleep the request for a discouraging amount of time before closing it.</p>\n"
},
{
"answer_id": 419841,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK there is no way to outright drop a request without a response. You can keep the request spinning in ASP.NET with whatever thread sleeping technique you like but you're not making life better for your server that way.</p>\n\n<p>The best way that I know of to achieve what you want is having a traffic manager like <a href=\"http://www.zeus.com/\" rel=\"nofollow noreferrer\">ZXTM</a> close the request before it gets to the webserver at all.</p>\n"
},
{
"answer_id": 42387199,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>public class RequestDropper : IHttpModule\n{\n public void Dispose()\n {\n throw new NotImplementedException();\n }\n\n public void Init(HttpApplication context)\n {\n context.BeginRequest += Context_BeginRequest;\n }\n\n public void Context_BeginRequest(object sender, EventArgs e)\n {\n var request = ((HttpApplication)sender).Context.Request;\n\n if (todayIAmNotInAMoodToProcessRequests)\n {\n request.Abort();\n }\n }\n}\n</code></pre>\n\n<p>Hope this saves you some time</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/676066/"
] |
I'm trying to figure out how to drop/discard a request, I'm basically trying to implement a blocked list of IPs in my app to block spammers and I don't want to return any response (just ignore the request), is this possible in ASP.NET?
Edit: Some of the answers suggest that I could add them in the firewall, while this will certainly be better it's not suitable in my case. To make a long story short, I'm adding a moderation section to my website where moderators will check the posts awaiting moderation for spam (filtered by a spam fitler), I want the IP of the sender of some post to be added to the list of blocked IPs once a post is marked as spam by the moderator, this is why I wan to do it in the application.
Edit: Calling Response.End() returns a response to the user (even though it's empty), the whole purpose of my question was how not to return any response. Is this possible (even out of curiosity)? There's also Response.Close() which closes the socket but it sends notification (in TCP/IP) when it does this, I just wan to ignore as it if was never received (i.e. send nothing to the user)
Thanks
|
Maybe you could use
```
Response.Clear();
Response.End();
```
|
276,927 |
<p>Using <code>MySQL</code>, I can do something like:</p>
<pre><code>SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
</code></pre>
<p><strong>My Output:</strong></p>
<pre><code>shopping
fishing
coding
</code></pre>
<p>but instead I just want 1 row, 1 col:</p>
<p><strong>Expected Output:</strong></p>
<pre><code>shopping, fishing, coding
</code></pre>
<p>The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.</p>
<p>I've looked for a function on <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws" rel="noreferrer">MySQL Doc</a> and it doesn't look like the <code>CONCAT</code> or <code>CONCAT_WS</code> functions accept result sets.</p>
<p>So does anyone here know how to do this?</p>
|
[
{
"answer_id": 276949,
"author": "che",
"author_id": 7806,
"author_profile": "https://Stackoverflow.com/users/7806",
"pm_score": 12,
"selected": true,
"text": "<p>You can use <a href=\"https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat\" rel=\"noreferrer\"><code>GROUP_CONCAT</code></a>:</p>\n<pre><code>SELECT person_id,\n GROUP_CONCAT(hobbies SEPARATOR ', ')\nFROM peoples_hobbies\nGROUP BY person_id;\n</code></pre>\n<p>As Ludwig stated in <a href=\"https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment14513101_276949\">his comment,</a> you can add the <code>DISTINCT</code> operator to avoid duplicates:</p>\n<pre><code>SELECT person_id,\n GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')\nFROM peoples_hobbies\nGROUP BY person_id;\n</code></pre>\n<p>As Jan stated in <a href=\"https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment72475644_276949\">their comment,</a> you can also sort the values before imploding it using <code>ORDER BY</code>:</p>\n<pre><code>SELECT person_id, \n GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')\nFROM peoples_hobbies\nGROUP BY person_id;\n</code></pre>\n<p>As Dag stated in <a href=\"https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field/276949#comment12638055_276949\">his comment,</a> there is a 1024 byte limit on the result. To solve this, run this query before your query:</p>\n<pre><code>SET group_concat_max_len = 2048;\n</code></pre>\n<p>Of course, you can change <code>2048</code> according to your needs. To calculate and assign the value:</p>\n<pre><code>SET group_concat_max_len = CAST(\n (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')\n FROM peoples_hobbies\n GROUP BY person_id) AS UNSIGNED);\n</code></pre>\n"
},
{
"answer_id": 276950,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 5,
"selected": false,
"text": "<p>There's a GROUP Aggregate function, <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">GROUP_CONCAT</a>.</p>\n"
},
{
"answer_id": 276951,
"author": "lpfavreau",
"author_id": 35935,
"author_profile": "https://Stackoverflow.com/users/35935",
"pm_score": 7,
"selected": false,
"text": "<p>Have a look at <code>GROUP_CONCAT</code> if your MySQL version (4.1) supports it. See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">the documentation</a> for more details.</p>\n\n<p>It would look something like:</p>\n\n<pre><code> SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') \n FROM peoples_hobbies \n WHERE person_id = 5 \n GROUP BY 'all';\n</code></pre>\n"
},
{
"answer_id": 2599426,
"author": "pau.moreno",
"author_id": 154922,
"author_profile": "https://Stackoverflow.com/users/154922",
"pm_score": 5,
"selected": false,
"text": "<p>You can change the max length of the <code>GROUP_CONCAT</code> value by setting the <code>group_concat_max_len</code> parameter.</p>\n\n<p>See details in the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">MySQL documantation</a>.</p>\n"
},
{
"answer_id": 19057956,
"author": "Shen liang",
"author_id": 1765981,
"author_profile": "https://Stackoverflow.com/users/1765981",
"pm_score": 4,
"selected": false,
"text": "<p>Use MySQL(5.6.13) session variable and assignment operator like the following</p>\n\n<pre><code>SELECT @logmsg := CONCAT_ws(',',@logmsg,items) FROM temp_SplitFields a;\n</code></pre>\n\n<p>then you can get </p>\n\n<pre><code>test1,test11\n</code></pre>\n"
},
{
"answer_id": 24137378,
"author": "Fedir RYKHTIK",
"author_id": 634275,
"author_profile": "https://Stackoverflow.com/users/634275",
"pm_score": 5,
"selected": false,
"text": "<p>In my case I had a row of Ids, and it was neccessary to cast it to char, otherwise, the result was encoded into binary format :</p>\n\n<pre><code>SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table\n</code></pre>\n"
},
{
"answer_id": 26004156,
"author": "elbowlobstercowstand",
"author_id": 3965565,
"author_profile": "https://Stackoverflow.com/users/3965565",
"pm_score": 6,
"selected": false,
"text": "<h1>Alternate syntax to concatenate <em>multiple, individual rows</em></h1>\n<p><em>WARNING: This post will make you hungry.</em></p>\n<h2>Given:</h2>\n<p>I found myself wanting to <strong>select multiple, individual rows</strong>—instead of a group—and concatenate on a certain field.</p>\n<p>Let's say you have a table of product ids and their names and prices:</p>\n<pre><code>+------------+--------------------+-------+\n| product_id | name | price |\n+------------+--------------------+-------+\n| 13 | Double Double | 5 |\n| 14 | Neapolitan Shake | 2 |\n| 15 | Animal Style Fries | 3 |\n| 16 | Root Beer | 2 |\n| 17 | Lame T-Shirt | 15 |\n+------------+--------------------+-------+\n</code></pre>\n<p>Then you have some fancy-schmancy ajax that lists these puppies off as checkboxes.</p>\n<p>Your hungry-hippo user selects <code>13, 15, 16</code>. No dessert for her today...</p>\n<h2>Find:</h2>\n<p>A way to summarize your user's order in one line, with pure mysql.</p>\n<h2>Solution:</h2>\n<p>Use <code>GROUP_CONCAT</code> with the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in\" rel=\"noreferrer\">the <code>IN</code> clause</a>:</p>\n<pre><code>mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);\n</code></pre>\n<p>Which outputs:</p>\n<pre><code>+------------------------------------------------+\n| order_summary |\n+------------------------------------------------+\n| Double Double + Animal Style Fries + Root Beer |\n+------------------------------------------------+\n</code></pre>\n<h2>Bonus Solution:</h2>\n<p>If you want the total price too, toss in <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum\" rel=\"noreferrer\"><code>SUM()</code></a>:</p>\n<pre><code>mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);\n+------------------------------------------------+-------+\n| order_summary | total |\n+------------------------------------------------+-------+\n| Double Double + Animal Style Fries + Root Beer | 10 |\n+------------------------------------------------+-------+\n</code></pre>\n"
},
{
"answer_id": 28746324,
"author": "thejustv",
"author_id": 2466310,
"author_profile": "https://Stackoverflow.com/users/2466310",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n<pre><code>DECLARE @Hobbies NVARCHAR(200) = ' '\n\nSELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;\n</code></pre>\n<p>TL;DR;</p>\n<pre><code>set @sql='';\nset @result='';\nset @separator=' union \\r\\n';\nSELECT \n@sql:=concat('select ''',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME ,''' as col_name,',\nINFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH ,' as def_len ,' ,\n'MAX(CHAR_LENGTH(',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME , '))as max_char_len',\n' FROM ',\nINFORMATION_SCHEMA.COLUMNS.TABLE_NAME\n) as sql_piece, if(@result:=if(@result='',@sql,concat(@result,@separator,@sql)),'','') as dummy\nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE \nINFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'\nand INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx' \nand INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';\nselect @result;\n</code></pre>\n"
},
{
"answer_id": 29949607,
"author": "Alex Bowyer",
"author_id": 971500,
"author_profile": "https://Stackoverflow.com/users/971500",
"pm_score": 4,
"selected": false,
"text": "<p>I had a more complicated query, and found that I had to use <code>GROUP_CONCAT</code> in an outer query to get it to work:</p>\n\n<h2>Original Query:</h2>\n\n<pre><code>SELECT DISTINCT userID \nFROM event GROUP BY userID \nHAVING count(distinct(cohort))=2);\n</code></pre>\n\n<h2>Imploded:</h2>\n\n<pre><code>SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ') \nFROM (SELECT DISTINCT userID FROM event \nGROUP BY userID HAVING count(distinct(cohort))=2) as sub;\n</code></pre>\n\n<p>Hope this might help someone.</p>\n"
},
{
"answer_id": 53282268,
"author": "raghavendra",
"author_id": 2648000,
"author_profile": "https://Stackoverflow.com/users/2648000",
"pm_score": 2,
"selected": false,
"text": "<p>we have two way to concatenate columns in MySql</p>\n\n<pre><code>select concat(hobbies) as `Hobbies` from people_hobbies where 1\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>select group_concat(hobbies) as `Hobbies` from people_hobbies where 1\n</code></pre>\n"
},
{
"answer_id": 55864579,
"author": "Oleg Abrazhaev",
"author_id": 1074834,
"author_profile": "https://Stackoverflow.com/users/1074834",
"pm_score": 4,
"selected": false,
"text": "<p>For somebody looking here how to use <code>GROUP_CONCAT</code> with subquery - posting this example</p>\n\n<pre><code>SELECT i.*,\n(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist\nFROM items i\nWHERE i.id = $someid\n</code></pre>\n\n<p>So <code>GROUP_CONCAT</code> must be used inside the subquery, not wrapping it.</p>\n"
},
{
"answer_id": 68357409,
"author": "Muhammad Shahzad",
"author_id": 2138791,
"author_profile": "https://Stackoverflow.com/users/2138791",
"pm_score": 2,
"selected": false,
"text": "<p>It is late but will helpfull for those who are searching "concatenate multiple MySQL rows into one field using pivot table" :)</p>\n<p>Query:</p>\n<pre><code>SELECT pm.id, pm.name, GROUP_CONCAT(c.name) as channel_names\nFROM payment_methods pm\nLEFT JOIN payment_methods_channels_pivot pmcp ON pmcp.payment_method_id = pm.id\nLEFT JOIN channels c ON c.id = pmcp.channel_id\nGROUP BY pm.id\n</code></pre>\n<p>Tables</p>\n<pre><code>payment_methods \n id | name\n 1 | PayPal\n\nchannels\n id | name\n 1 | Google\n 2 | Faceook\n\npayment_methods_channels_pivot\n payment_method_id | channel_id\n 1 | 1\n 1 | 2\n</code></pre>\n<p>Output:</p>\n<p><a href=\"https://i.stack.imgur.com/TCxjv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TCxjv.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 68776458,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": "<p>In sql server use string_agg to pivot a row field values into a column:</p>\n<pre><code>select string_agg(field1, ', ') a FROM mytable \n\nor\n\nselect string_agg(field1, ', ') within group (order by field1 dsc) a FROM mytable group by field2\n</code></pre>\n"
},
{
"answer_id": 69433740,
"author": "Payel Senapati",
"author_id": 12118888,
"author_profile": "https://Stackoverflow.com/users/12118888",
"pm_score": 0,
"selected": false,
"text": "<p>Another interesting example in this case -</p>\n<p>Following is the structure of the sample table <code>people_hobbies</code> -</p>\n<pre><code>DESCRIBE people_hobbies;\n+---------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+--------------+------+-----+---------+----------------+\n| id | int unsigned | NO | PRI | NULL | auto_increment |\n| ppl_id | int unsigned | YES | MUL | NULL | |\n| name | varchar(200) | YES | | NULL | |\n| hby_id | int unsigned | YES | MUL | NULL | |\n| hobbies | varchar(50) | YES | | NULL | |\n+---------+--------------+------+-----+---------+----------------+\n\n</code></pre>\n<p>The table is populated as follows -</p>\n<pre><code>SELECT * FROM people_hobbies;\n+----+--------+-----------------+--------+-----------+\n| id | ppl_id | name | hby_id | hobbies |\n+----+--------+-----------------+--------+-----------+\n| 1 | 1 | Shriya Jain | 1 | reading |\n| 2 | 4 | Shirley Setia | 4 | coding |\n| 3 | 2 | Varsha Tripathi | 7 | gardening |\n| 4 | 3 | Diya Ghosh | 2 | fishing |\n| 5 | 4 | Shirley Setia | 3 | gaming |\n| 6 | 1 | Shriya Jain | 6 | cycling |\n| 7 | 2 | Varsha Tripathi | 1 | reading |\n| 8 | 3 | Diya Ghosh | 5 | shopping |\n| 9 | 3 | Diya Ghosh | 4 | coding |\n| 10 | 4 | Shirley Setia | 1 | reading |\n| 11 | 1 | Shriya Jain | 4 | coding |\n| 12 | 1 | Shriya Jain | 3 | gaming |\n| 13 | 4 | Shirley Setia | 2 | fishing |\n| 14 | 4 | Shirley Setia | 7 | gardening |\n| 15 | 2 | Varsha Tripathi | 3 | gaming |\n| 16 | 2 | Varsha Tripathi | 2 | fishing |\n| 17 | 1 | Shriya Jain | 5 | shopping |\n| 18 | 1 | Shriya Jain | 7 | gardening |\n| 19 | 3 | Diya Ghosh | 1 | reading |\n| 20 | 4 | Shirley Setia | 5 | shopping |\n+----+--------+-----------------+--------+-----------+\n</code></pre>\n<p>Now, a table <code>hobby_list</code> is generated having the list of all people and a list of each person's hobbies with each hobby in a new line -</p>\n<pre><code>CREATE TABLE hobby_list AS\n -> SELECT ppl_id, name,\n -> GROUP_CONCAT(hobbies ORDER BY hby_id SEPARATOR "\\n")\n -> AS hobbies\n -> FROM people_hobbies\n -> GROUP BY ppl_id\n -> ORDER BY ppl_id;\n</code></pre>\n<pre><code>SELECT * FROM hobby_list;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/yBqzm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yBqzm.png\" alt=\"CONCAT_GROUP()\" /></a></p>\n"
},
{
"answer_id": 69888644,
"author": "Md. Tarikul Islam Soikot",
"author_id": 15078671,
"author_profile": "https://Stackoverflow.com/users/15078671",
"pm_score": 2,
"selected": false,
"text": "<p>Here, my intension was to apply string concatenation without using group_concat() function:</p>\n<pre><code>Set @concatHobbies = '';\nSELECT TRIM(LEADING ', ' FROM T.hobbies ) FROM \n(\n select \n Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies\n from peoples_hobbies\n)T\nOrder by Id DESC\nLIMIT 1\n</code></pre>\n<p>Here</p>\n<pre><code> select \n Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies\n from peoples_hobbies\n</code></pre>\n<p>will return</p>\n<pre><code> Id hobbies\n 1 , shopping\n 2 , shopping, fishing\n 3 , shopping, fishing, coding\n</code></pre>\n<p>Now our expected result is at third position. So I am taking the Last row by using</p>\n<pre><code> Order by Id DESC \n LIMIT 1\n \n</code></pre>\n<p>Then I am also removing the First ', ' from my string</p>\n<pre><code> TRIM(LEADING ', ' FROM T.hobbies )\n</code></pre>\n"
},
{
"answer_id": 72904124,
"author": "Haddock-san",
"author_id": 1499769,
"author_profile": "https://Stackoverflow.com/users/1499769",
"pm_score": 0,
"selected": false,
"text": "<p>Use <strong>GROUP_CONCAT</strong>:</p>\n<pre><code>SELECT GROUP_CONCAT(hobbies) FROM peoples_hobbies WHERE person_id = 5;\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14966/"
] |
Using `MySQL`, I can do something like:
```
SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
```
**My Output:**
```
shopping
fishing
coding
```
but instead I just want 1 row, 1 col:
**Expected Output:**
```
shopping, fishing, coding
```
The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.
I've looked for a function on [MySQL Doc](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws) and it doesn't look like the `CONCAT` or `CONCAT_WS` functions accept result sets.
So does anyone here know how to do this?
|
You can use [`GROUP_CONCAT`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat):
```
SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
As Ludwig stated in [his comment,](https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment14513101_276949) you can add the `DISTINCT` operator to avoid duplicates:
```
SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
As Jan stated in [their comment,](https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment72475644_276949) you can also sort the values before imploding it using `ORDER BY`:
```
SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
As Dag stated in [his comment,](https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field/276949#comment12638055_276949) there is a 1024 byte limit on the result. To solve this, run this query before your query:
```
SET group_concat_max_len = 2048;
```
Of course, you can change `2048` according to your needs. To calculate and assign the value:
```
SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
```
|
276,965 |
<p>I have noticed that our VMWare VMs often have the incorrect time on them. No matter how many times I reset the time they keep on desyncing.</p>
<p>Has anyone else noticed this? What do other people do to keep their VM time in sync?</p>
<p><strong>Edit:</strong> These are CLI linux VMs btw..</p>
|
[
{
"answer_id": 276981,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 1,
"selected": false,
"text": "<p>The CPU speed varies due to power saving. I originally noticed this because VMware gave me a helpful tip on my laptop, but this page mentions the same thing:</p>\n\n<p>Quote from : <a href=\"http://maple.rsvs.ulaval.ca/mediawiki/index.php/VMWare_tips_and_tricks\" rel=\"nofollow noreferrer\">VMWare tips and tricks</a>\nPower saving (SpeedStep, C-states, P-States,...)</p>\n\n<p>Your power saving settings may interfere significantly with vmware's performance. There are several levels of power saving.</p>\n\n<p>CPU frequency</p>\n\n<p>This should not lead to performance degradation, outside of having the obvious lower performance when running the CPU at a lower frequency (either manually of via governors like \"ondemand\" or \"conservative\"). The only problem with varying the CPU speed while vmware is running is that the Windows clock will gain of lose time. To prevent this, specify your full CPU speed in kHz in /etc/vmware/config</p>\n\n<p>host.cpukHz = 2167000</p>\n"
},
{
"answer_id": 276985,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 2,
"selected": false,
"text": "<p>I'll answer for Windows guests. If you have VMware Tools installed, then the taskbar's notification area (near the clock) has an icon for VMware Tools. Double-click that and set your options.</p>\n\n<p>If you don't have VMware Tools installed, you can still set the clock's option for internet time to sync with some NTP server. If your physical machine serves the NTP protocol to your guest machines then you can get that done with host-only networking. Otherwise you'll have to let your guests sync with a genuine NTP server out on the internet, for example time.windows.com.</p>\n"
},
{
"answer_id": 278070,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>VMware experiences a lot of clock drift. This <a href=\"http://www.google.com/search?q=vmware+clock+drift\" rel=\"nofollow noreferrer\">Google search</a> for 'vmware clock drift' links to several articles.</p>\n\n<p>The first hit may be the most useful for you: <a href=\"http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues\" rel=\"nofollow noreferrer\">http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues</a></p>\n"
},
{
"answer_id": 278125,
"author": "bernie",
"author_id": 21141,
"author_profile": "https://Stackoverflow.com/users/21141",
"pm_score": 7,
"selected": true,
"text": "<p>If your host time is correct, you can set the following .vmx configuration file option to enable periodic synchronization:</p>\n\n<pre><code>tools.syncTime = true\n</code></pre>\n\n<p>By default, this synchronizes the time every minute. To change the periodic rate, set the following option to the desired synch time in seconds:</p>\n\n<pre><code>tools.syncTime.period = 60\n</code></pre>\n\n<p>For this to work you need to have VMWare tools installed in your guest OS.</p>\n\n<p>See <a href=\"http://www.vmware.com/pdf/vmware_timekeeping.pdf\" rel=\"noreferrer\">http://www.vmware.com/pdf/vmware_timekeeping.pdf</a> for more information</p>\n"
},
{
"answer_id": 1070336,
"author": "twistedstream",
"author_id": 96707,
"author_profile": "https://Stackoverflow.com/users/96707",
"pm_score": 2,
"selected": false,
"text": "<p>Something to note here. We had the same issue with Windows VM's running on an ESXi host. The time sync was turned on in VMWare Tools on the guest, but the guest clocks were consistently off (by about 30 seconds) from the host clock. The ESXi host was configured to get time updates from an internal time server.</p>\n\n<p>It turns out we had the Internet Time setting turned on in the Windows VM's (Control Panel > Date and Time > Internet Time tab) so the guest was getting time updates from two places and the internet time was winning. We turned that off and now the guest clocks are good, getting their time exclusively from the ESXi host.</p>\n"
},
{
"answer_id": 2609321,
"author": "gusruiz",
"author_id": 312995,
"author_profile": "https://Stackoverflow.com/users/312995",
"pm_score": 3,
"selected": false,
"text": "<p>according to VMware's knowledge base, the actual solution depends on the Linux distro and release, in RHEL 5.3 I usually edit /etc/grub.conf and append this parameters to the kernel entry: divider=10 clocksource=acpi_pm</p>\n\n<p>Then enable NTP, disable VMware time synchronization from vmware-toolbox and finally reboot the VM</p>\n\n<p>A complete table with guidelines for each Linux distro can be found here:</p>\n\n<p>TIMEKEEPING BEST PRACTICES FOR LINUX GUESTS\n<a href=\"http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1006427\" rel=\"noreferrer\">http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1006427</a></p>\n"
},
{
"answer_id": 5860257,
"author": "AdminIMGE",
"author_id": 734828,
"author_profile": "https://Stackoverflow.com/users/734828",
"pm_score": 2,
"selected": false,
"text": "<p>In my case we are running VMWare Server 2.02 on Windows Server 2003 R2 Standard. The Host is also Windows Server 2003 R2 Standard. I had the VMware Tools installed and set to sync the time. I did everything imaginable that I found on various internet sites. We still had horrendous drift, although it had shrunk from 15 minutes or more down to the 3 or 4 minute range.</p>\n\n<p>Finally in the vmware.log I found this entry (resides in the folder as the .vmx file):\n\"Your host system does not guarantee synchronized TSCs across different CPUs, so please set the /usepmtimer option in your Windows Boot.ini file to ensure that timekeeping is reliable. See Microsoft KB <a href=\"http://support.microsoft.com/kb\" rel=\"nofollow\">http://support.microsoft.com/kb</a>... for details and Microsoft KB <a href=\"http://support.microsoft.com/kb\" rel=\"nofollow\">http://support.microsoft.com/kb</a>... for additional information.\"</p>\n\n<p>Cause: This problem occurs when the computer has the AMD Cool'n'Quiet technology (AMD dual cores) enabled in the BIOS or some Intel multi core processors. Multi core or multiprocessor systems may encounter Time Stamp Counter (TSC) drift when the time between different cores is not synchronized. The operating systems which use TSC as a timekeeping resource may experience the issue. Newer operating systems typically do not use the TSC by default if other timers are available in the system which can be used as a timekeeping source. Other available timers include the PM_Timer and the High Precision Event Timer (HPET).\nResolution: To resolve this problem check with the hardware vendor to see if a new driver/firmware update is available to fix the issue.</p>\n\n<p>Note The driver installation may add the /usepmtimer switch in the Boot.ini file.</p>\n\n<p>Once this (/usepmtimer switch) was done the clock was dead on time.</p>\n"
},
{
"answer_id": 7157566,
"author": "Nirav Shah",
"author_id": 907216,
"author_profile": "https://Stackoverflow.com/users/907216",
"pm_score": 1,
"selected": false,
"text": "<p>When installing VMware Tools on a Windows Guest, “Time Synchronisation” is not enabled by default.\nHowever – “best practise” is to enable time synch on Windows Guests.</p>\n\n<p>There a several ways to do this from outside the VM, but I wanted to find a way to enable time sync from within the guest itself either on or after tools install.</p>\n\n<p>Surprisingly, this wasn’t quite as straightforward as I expected.\n(I assumed it would be posible to set this as a parameter / config option during tools install)</p>\n\n<p>After a bit of searching I found a way to do this in a VMware article called “Using the VMware Tools Command-Line Interface“.</p>\n\n<p>So, if time sync is disabled, you can enable it by running the following command line in the guest:</p>\n\n<pre><code> VMwareService.exe –cmd “vmx.set_option synctime 0 1″\n</code></pre>\n\n<p>Additional Notes</p>\n\n<p>For some (IMHO stupid) reason, this utility requires you to specify the current as well as the new value</p>\n\n<p>0 = disabled\n1 = enabled</p>\n\n<p>So – if you run this command on a machine which has this already set, you will get an error saying – “Invalid old value“.\nObviously you can “ignore” this error when run (so not a huge deal) but the current design seems a bit dumb.\nIMHO it would be much more sensible if you could simply specify the value you want to set and not require the current value to be specified.</p>\n\n<p>i.e.\n VMwareService.exe –cmd “vmx.set_option synctime <0|1>”</p>\n"
},
{
"answer_id": 24445175,
"author": "dksh",
"author_id": 609304,
"author_profile": "https://Stackoverflow.com/users/609304",
"pm_score": -1,
"selected": false,
"text": "<p>I added the following job to crontab. It is hacky but i think should work. </p>\n\n<p>*/5 * * * * service ntpd stop && ntpdate pool.ntp.org && service ntpd start</p>\n\n<p>It stops ntpd service updates from service and starts ntpd again</p>\n"
},
{
"answer_id": 26034119,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.vmtools.install.doc%2FGUID-C0D8326A-B6E7-4E61-8470-6C173FDDF656.html\" rel=\"nofollow\">This documentation</a> solved this problem for me.</p>\n"
},
{
"answer_id": 41167666,
"author": "Francesc Layret",
"author_id": 7302775,
"author_profile": "https://Stackoverflow.com/users/7302775",
"pm_score": 0,
"selected": false,
"text": "<p>In Active Directory environment, it's important to know:</p>\n\n<ul>\n<li><p>All member machines synchronizes with any domain controller.</p></li>\n<li><p>In a domain, all domain controllers synchronize from the PDC Emulator (PDCe) of that domain.</p></li>\n<li><p>The PDC Emulator of a domain should synchronize with local or NTP.</p></li>\n</ul>\n\n<p>It's important to consider this when setting the time in vmware or configuring the time sync.</p>\n\n<p>Extracted from: <a href=\"http://www.sysadmit.com/2016/12/vmware-esxi-configurar-hora.html\" rel=\"nofollow noreferrer\">http://www.sysadmit.com/2016/12/vmware-esxi-configurar-hora.html</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
I have noticed that our VMWare VMs often have the incorrect time on them. No matter how many times I reset the time they keep on desyncing.
Has anyone else noticed this? What do other people do to keep their VM time in sync?
**Edit:** These are CLI linux VMs btw..
|
If your host time is correct, you can set the following .vmx configuration file option to enable periodic synchronization:
```
tools.syncTime = true
```
By default, this synchronizes the time every minute. To change the periodic rate, set the following option to the desired synch time in seconds:
```
tools.syncTime.period = 60
```
For this to work you need to have VMWare tools installed in your guest OS.
See <http://www.vmware.com/pdf/vmware_timekeeping.pdf> for more information
|
276,986 |
<p>When the program runs, there is a series of ListView forms. We populated one of them with items (as strings) and we check whether the state of selection has changed. Once it's changed, we grab the text of the selected item using FocusedItem.Text. The first time works just fine but when another selection is made, the selected item returns as null.</p>
<p>The only way we can temporarily get around this issue is to clear and repopulate the form. The disadvantage is that we lose the highlighted item. There got to be another way around this. Maybe we're not clear on how ListView really works?</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 277179,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>I have run a test program and see no instance where FocusedItem could be nulls.</p>\n\n<p>Could you post some code?</p>\n\n<p>Here is what I got after I selects the item 'a' then selects the item 'b' and then click on an empty space:</p>\n\n<pre><code>ItemSelectionChanged\n Item : ListViewItem: {a}\n IsSelected : True\n SelectedItem : ListViewItem: {a}\n FocusedItem : ListViewItem: {a}\nSelectedIndexChanged\n SelectedItem : ListViewItem: {a}\n FocusedItem : ListViewItem: {a}\nItemSelectionChanged\n Item : ListViewItem: {a}\n IsSelected : False\n SelectedItem : null\n FocusedItem : ListViewItem: {a}\nSelectedIndexChanged\n SelectedItem : null\n FocusedItem : ListViewItem: {a}\nItemSelectionChanged\n Item : ListViewItem: {b}\n IsSelected : True\n SelectedItem : ListViewItem: {b}\n FocusedItem : ListViewItem: {b}\nSelectedIndexChanged\n SelectedItem : ListViewItem: {b}\n FocusedItem : ListViewItem: {b}\nItemSelectionChanged\n Item : ListViewItem: {b}\n IsSelected : False\n SelectedItem : null\n FocusedItem : ListViewItem: {b}\nSelectedIndexChanged\n SelectedItem : null\n FocusedItem : ListViewItem: {b}\n</code></pre>\n\n<p>Noticed that <code>FocusedItem</code> is never null.</p>\n\n<p>Is it the same in your case?</p>\n\n<p>Would a simple <code>if (listView.FocusedItem == null)</code> check do for your case?</p>\n"
},
{
"answer_id": 277553,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 1,
"selected": false,
"text": "<p>If you're after the item the user has selected, you should be using the first item in the <code>SelectedItems</code> collection. <code>FocusedItem</code> is the item that currently has the keyboard focus (and hence is showing the dotted focus rectangle); if the control doesn't have the focus, neither can an item.</p>\n"
},
{
"answer_id": 2473723,
"author": "mukunda",
"author_id": 296969,
"author_profile": "https://Stackoverflow.com/users/296969",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem while using listview. There seems to be some problem with respect to the event fired upon selection. </p>\n\n<ol>\n<li><code>SelectedIndexChanged</code> event where the focused item, selected items and selected indices become null. This is the reason for the above problem.</li>\n<li><code>ItemActivate</code> event can be alternatively used without any glitches where the focused item, selected items or selected indices are not null in the second or any other time.</li>\n</ol>\n\n<p>While creating a listview with details, the <code>SelectedIndexChanged</code> event is fired by default. So a change in the respective Designer class and a related event handler in the main class would do the job.</p>\n\n<p>In the designer class, see the event that is subscribed. Example:</p>\n\n<pre><code>this.TaskslistView.SelectedIndexChanged\n += new System.EventHandler(TaskslistView_SelectedIndexChanged);\n</code></pre>\n\n<p>for which the respective <code>TaskslistView_SelectedIndexChanged</code> event handler method is present in the main class. Replace this event with</p>\n\n<pre><code>this.TaskslistView.ItemActivate\n += new System.EventHandler(this.TaskslistView_ItemActivate);\n</code></pre>\n\n<p>and replace the respective <code>TaskslistView_SelectedIndexChanged</code> with <code>TaskslistView_ItemActivate</code>. </p>\n\n<p>This ought to solve the problem.</p>\n"
},
{
"answer_id": 4548830,
"author": "Nana Kofi",
"author_id": 555109,
"author_profile": "https://Stackoverflow.com/users/555109",
"pm_score": 2,
"selected": false,
"text": "<p>Put the following condition around in the <code>OnSelectedIndexHandler</code>:</p>\n\n<pre><code>if(listViewObject.SelectedItems!=null&& listViewObject.SelectedItems.Count>0)\n{\n //....your code here\n}\n</code></pre>\n"
},
{
"answer_id": 41473298,
"author": "dubucha",
"author_id": 2754828,
"author_profile": "https://Stackoverflow.com/users/2754828",
"pm_score": 0,
"selected": false,
"text": "<p>You can use ListViewItemSelectionChangedEventHandler.</p>\n\n<pre><code>ListView.ItemSelectionChanged += \nnew ListViewItemSelectionChangedEventHandler(ListView_ItemSelectionChanged);\n\nprivate void ListView_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e)\n{\n var x = e.IsSelected;\n}\n</code></pre>\n\n<p>ListView_ItemSelectionChanged gets called twice. You can ignore the first one by using </p>\n\n<pre><code>if (e.IsSelected == true)\n</code></pre>\n\n<p>edit:\nTry this:</p>\n\n<pre><code>ListView.Select();\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/276986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When the program runs, there is a series of ListView forms. We populated one of them with items (as strings) and we check whether the state of selection has changed. Once it's changed, we grab the text of the selected item using FocusedItem.Text. The first time works just fine but when another selection is made, the selected item returns as null.
The only way we can temporarily get around this issue is to clear and repopulate the form. The disadvantage is that we lose the highlighted item. There got to be another way around this. Maybe we're not clear on how ListView really works?
Any ideas?
|
Put the following condition around in the `OnSelectedIndexHandler`:
```
if(listViewObject.SelectedItems!=null&& listViewObject.SelectedItems.Count>0)
{
//....your code here
}
```
|
277,007 |
<p>I need to load a bunch of words (about 70,000) from a text file, add it to a hashtable (using soundex as a key) and sort the values. While doing all these I want to show a progress bar using JProgressBar. Articles such as <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html" rel="noreferrer">this</a> and <a href="http://www.dreamincode.net/forums/showtopic27952.htm" rel="noreferrer">this</a>, only gives a non-real example (a while loop). Can anyone suggest me how should I proceed. How can I get a number from above condition to set the value for the progress bar? Also it seems that there are different ways to do it - using thread, timer etc. Which could be the best method for the situation such as above?</p>
|
[
{
"answer_id": 277048,
"author": "Zach Scrivena",
"author_id": 20029,
"author_profile": "https://Stackoverflow.com/users/20029",
"pm_score": 3,
"selected": false,
"text": "<p>I would read the text file in a loop on a dedicated work thread, not the event-dispatch thread (EDT). If I know the total number of words to be read, then I can compute the percentage completed at each iteration of the loop and update the progress bar accordingly.</p>\n\n<p><strong>Sample Code</strong></p>\n\n<p>The following code puts the progress bar in indeterminate mode during preprocessing and postprocessing, displaying an animation that indicates work is occurring. Determinate mode is used when reading iteratively from the input file.</p>\n\n<pre><code>// INITIALIZATION ON EDT \n\n// JProgressBar progress = new JProgressBar();\n// progress.setStringPainted(true);\n\n// PREPROCESSING\n\n// update progress bar (indeterminate mode)\nSwingUtilities.invokeLater(new Runnable()\n{\n @Override\n public void run()\n {\n progress.setIndeterminate(true);\n progress.setString(\"Preprocessing...\");\n }\n});\n\n// perform preprocessing (open input file, determine total number of words, etc)\n\n// PROCESSING \n\n// update progress bar (switch to determinate mode)\nSwingUtilities.invokeLater(new Runnable()\n{\n @Override\n public void run()\n {\n progress.setIndeterminate(false);\n }\n});\n\nint count = 0;\n\nwhile (true)\n{\n // read a word from the input file; exit loop if EOF\n\n // compute soundex representation\n\n // add entry to map (hash table)\n\n // compute percentage completed\n count++;\n final int percent = count * 100 / total;\n\n // update progress bar on the EDT\n SwingUtilities.invokeLater(new Runnable()\n {\n @Override\n public void run()\n {\n progress.setString(\"Processing \" + percent + \"%\");\n progress.setValue(percent);\n }\n });\n}\n\n// POSTPROCESSING \n\n// update progress bar (switch to indeterminate mode)\nSwingUtilities.invokeLater(new Runnable()\n{\n @Override\n public void run()\n {\n progress.setIndeterminate(true);\n progress.setString(\"Postprocessing...\");\n }\n});\n\n// perform postprocessing (close input file, etc)\n\n// DONE! \n\nSwingUtilities.invokeLater(new Runnable()\n{\n @Override\n public void run()\n {\n progress.setIndeterminate(false);\n progress.setString(\"Done!\");\n progress.setValue(100);\n }\n});\n</code></pre>\n\n<p><strong>Suggestions</strong></p>\n\n<ul>\n<li>Consider writing a convenience method to update the progress bar on the EDT, so as to reduce clutter in your code (<code>SwingUtilities.invokeLater... public void run()...</code>)</li>\n</ul>\n"
},
{
"answer_id": 569047,
"author": "yanchenko",
"author_id": 15187,
"author_profile": "https://Stackoverflow.com/users/15187",
"pm_score": 1,
"selected": false,
"text": "<p>Use SwingWorker: <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/concurrency/interim.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/uiswing/concurrency/interim.html</a></p>\n"
},
{
"answer_id": 4228745,
"author": "Sean Anderson",
"author_id": 513905,
"author_profile": "https://Stackoverflow.com/users/513905",
"pm_score": 0,
"selected": false,
"text": "<p>Get the file size and count the bytes processed on each iteration. That way, you don't have to cycle through the file twice.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35307/"
] |
I need to load a bunch of words (about 70,000) from a text file, add it to a hashtable (using soundex as a key) and sort the values. While doing all these I want to show a progress bar using JProgressBar. Articles such as [this](http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html) and [this](http://www.dreamincode.net/forums/showtopic27952.htm), only gives a non-real example (a while loop). Can anyone suggest me how should I proceed. How can I get a number from above condition to set the value for the progress bar? Also it seems that there are different ways to do it - using thread, timer etc. Which could be the best method for the situation such as above?
|
I would read the text file in a loop on a dedicated work thread, not the event-dispatch thread (EDT). If I know the total number of words to be read, then I can compute the percentage completed at each iteration of the loop and update the progress bar accordingly.
**Sample Code**
The following code puts the progress bar in indeterminate mode during preprocessing and postprocessing, displaying an animation that indicates work is occurring. Determinate mode is used when reading iteratively from the input file.
```
// INITIALIZATION ON EDT
// JProgressBar progress = new JProgressBar();
// progress.setStringPainted(true);
// PREPROCESSING
// update progress bar (indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(true);
progress.setString("Preprocessing...");
}
});
// perform preprocessing (open input file, determine total number of words, etc)
// PROCESSING
// update progress bar (switch to determinate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(false);
}
});
int count = 0;
while (true)
{
// read a word from the input file; exit loop if EOF
// compute soundex representation
// add entry to map (hash table)
// compute percentage completed
count++;
final int percent = count * 100 / total;
// update progress bar on the EDT
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setString("Processing " + percent + "%");
progress.setValue(percent);
}
});
}
// POSTPROCESSING
// update progress bar (switch to indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(true);
progress.setString("Postprocessing...");
}
});
// perform postprocessing (close input file, etc)
// DONE!
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
progress.setIndeterminate(false);
progress.setString("Done!");
progress.setValue(100);
}
});
```
**Suggestions**
* Consider writing a convenience method to update the progress bar on the EDT, so as to reduce clutter in your code (`SwingUtilities.invokeLater... public void run()...`)
|
277,018 |
<p>I have a class storing the name of a WS method to call and the type and value of the only parameter that service receives (it will be a collection of parameters but lets keep it simple for the example):</p>
<pre><code>public class MethodCall
{
public string Method { get; set; }
public Type ParType { get; set; }
public string ParValue { get; set; }
public T CastedValue<T>()
{
return (T)Convert.ChangeType(ParValue, ParType);
}
}
</code></pre>
<p>I have a method that takes the method name and the parameters and using reflection calls the method and returns the result. That one works fine when i use it like this:</p>
<pre><code>callingclass.URL = url;
callingclass.Service = serviceName;
object[] Params = { (decimal)1 };
callingclass.CallMethod("Hello", Params);
</code></pre>
<p>But my type, decimal in the example, is given in the instance of MethodCall. So if i have this code:</p>
<pre><code>MethodCall call = new MethodCall();
call.Method = "Hello";
call.ParType = typeof(decimal);
call.ParValue = "1";
</code></pre>
<p>Option 1, doesn't compile:</p>
<pre><code>object[] Params = { (call.ParType)call.ParValue }; //Compilation error: The type or namespace name 'call' could not be found (are you missing a using directive or an assembly reference?)
</code></pre>
<p>Option 2, doesn't compile neither:</p>
<pre><code>object[] Params = { call.CastedValue<call.ParType>() }; //Compilation error: Cannot implicitly convert type 'call.ParType' to 'object'
</code></pre>
<p>Option 3, using reflection, compiles but doesn't work when calling the service:</p>
<pre><code>object[] Params = { typeof(MethodCall).GetMethod("CastedValue").MakeGenericMethod(call.ParType).Invoke(this, null) };
callingclass.CallMethod(call.Method, Params);
</code></pre>
<p>The exception is:
ConnectionLib.WsProxyParameterExeption: The parameters for the method 'TestService.Hello' in URL '<a href="http://localhost/MyTestingService/" rel="nofollow noreferrer">http://localhost/MyTestingService/</a>' are wrong.</p>
<p>So can someone point me the right way to make this work?</p>
<p>Thanks</p>
|
[
{
"answer_id": 277023,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 9,
"selected": true,
"text": "<p>The <code>readonly</code> keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the <code>const</code> modifier, which must have its value set at compile time. Using <code>readonly</code> you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.</p>\n\n<p>Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).</p>\n"
},
{
"answer_id": 277075,
"author": "Xiaofu",
"author_id": 31967,
"author_profile": "https://Stackoverflow.com/users/31967",
"pm_score": 6,
"selected": false,
"text": "<p>There are no apparent performance benefits to using <code>readonly</code>, at least none that I've ever seen mentioned anywhere. It's just for doing exactly as you suggest, for preventing modification once it has been initialised.</p>\n\n<p>So it's beneficial in that it helps you write more robust, more readable code. The real benefit of things like this come when you're working in a team or for maintenance. Declaring something as <code>readonly</code> is akin to putting a contract for that variable's usage in the code. Think of it as adding documentation in the same way as other keywords like <code>internal</code> or <code>private</code>, you're saying \"this variable should not be modified after initialisation\", and moreover you're <em>enforcing</em> it.</p>\n\n<p>So if you create a class and mark some member variables <code>readonly</code> by design, then you prevent yourself or another team member making a mistake later on when they're expanding upon or modifying your class. In my opinion, that's a benefit worth having (at the small expense of extra language complexity as doofledorfer mentions in the comments).</p>\n"
},
{
"answer_id": 277117,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 8,
"selected": false,
"text": "<p>I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value.</p>\n<p>However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR.</p>\n<p>The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure.</p>\n<p>Robert Pickering has written a good blog post about the benefits of immutability. The post can be found <a href=\"https://dzone.com/articles/getting-know-immutable-data-st\" rel=\"noreferrer\">here</a> or at the <a href=\"https://web.archive.org/web/20190910111734/http://strangelights.com/blog/archive/2008/05/18/1617.aspx\" rel=\"noreferrer\">archive.org backup</a>.</p>\n"
},
{
"answer_id": 312840,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 6,
"selected": false,
"text": "<p>To put it in very practical terms:</p>\n\n<p>If you use a const in dll A and dll B references that const, the value of that const will be compiled into dll B. If you redeploy dll A with a new value for that const, dll B will still be using the original value.</p>\n\n<p>If you use a readonly in dll A and dll B references that readonly, that readonly will always be looked up at runtime. This means if you redeploy dll A with a new value for that readonly, dll B will use that new value. </p>\n"
},
{
"answer_id": 312845,
"author": "Brian Rasmussen",
"author_id": 38206,
"author_profile": "https://Stackoverflow.com/users/38206",
"pm_score": 4,
"selected": false,
"text": "<p>Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly. </p>\n"
},
{
"answer_id": 2236598,
"author": "Michael",
"author_id": 193111,
"author_profile": "https://Stackoverflow.com/users/193111",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful with private readonly arrays. If these are exposed a client as an object (you might do this for COM interop as I did) the client can manipulate array values. Use the Clone() method when returning an array as an object.</p>\n"
},
{
"answer_id": 6122251,
"author": "Kristof Verbiest",
"author_id": 268661,
"author_profile": "https://Stackoverflow.com/users/268661",
"pm_score": 4,
"selected": false,
"text": "<p>There is a potential case where the compiler can make a performance optimization based on the presence of the readonly keyword.</p>\n<p>This only applies if the read-only field is also marked as <em>static</em>. In that case, the JIT compiler can assume that this static field will never change. The JIT compiler can take this into account when compiling the methods of the class.</p>\n<p>A typical example: your class could have a static read-only <em>IsDebugLoggingEnabled</em> field that is initialized in the constructor (e.g. based on a configuration file). Once the actual methods are JIT-compiled, the compiler may omit whole parts of the code when debug logging is not enabled.</p>\n<p>I have not checked if this optimization is actually implemented in the current version of the JIT compiler, so this is just speculation.</p>\n"
},
{
"answer_id": 14491251,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 2,
"selected": false,
"text": "<p>Don't forget there is a workaround to get the <code>readonly</code> fields set outside of any constructors using <code>out</code> params. </p>\n\n<p>A little messy but:</p>\n\n<pre><code>private readonly int _someNumber;\nprivate readonly string _someText;\n\npublic MyClass(int someNumber) : this(data, null)\n{ }\n\npublic MyClass(int someNumber, string someText)\n{\n Initialise(out _someNumber, someNumber, out _someText, someText);\n}\n\nprivate void Initialise(out int _someNumber, int someNumber, out string _someText, string someText)\n{\n //some logic\n}\n</code></pre>\n\n<p>Further discussion here: <a href=\"http://www.adamjamesnaylor.com/2013/01/23/Setting-Readonly-Fields-From-Chained-Constructors.aspx\" rel=\"nofollow noreferrer\">http://www.adamjamesnaylor.com/2013/01/23/Setting-Readonly-Fields-From-Chained-Constructors.aspx</a></p>\n"
},
{
"answer_id": 15536994,
"author": "Shane",
"author_id": 314641,
"author_profile": "https://Stackoverflow.com/users/314641",
"pm_score": -1,
"selected": false,
"text": "<p>There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections</p>\n"
},
{
"answer_id": 37733928,
"author": "Yuriy Zaletskyy",
"author_id": 677824,
"author_profile": "https://Stackoverflow.com/users/677824",
"pm_score": 0,
"selected": false,
"text": "<p>Another interesting part of usage of readonly marking can be protecting field from initialization in singleton. </p>\n\n<p>for example in code from <a href=\"http://csharpindepth.com/Articles/General/Singleton.aspx\" rel=\"nofollow\">csharpindepth</a>:</p>\n\n<pre><code>public sealed class Singleton\n{\n private static readonly Lazy<Singleton> lazy =\n new Lazy<Singleton>(() => new Singleton());\n\n public static Singleton Instance { get { return lazy.Value; } }\n\n private Singleton()\n {\n }\n}\n</code></pre>\n\n<p>readonly plays small role of protecting field Singleton from being initialized twice. Another detail is that for mentioned scenario you can't use const because const forces creation during compile time, but singleton makes creation at run time.</p>\n"
},
{
"answer_id": 38074357,
"author": "waqar ahmed",
"author_id": 4898702,
"author_profile": "https://Stackoverflow.com/users/4898702",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a pre defined or pre calculated value that needs to remain same through out the program then you should use constant but if you have a value that needs to be provided at the runtime but once assigned should remain same throughout the program u should use readonly. for example if you have to assign the program start time or you have to store a user provided value at the object initialization and you have to restrict it from further changes you should use readonly.</p>\n"
},
{
"answer_id": 43941195,
"author": "Mina Gabriel",
"author_id": 1410185,
"author_profile": "https://Stackoverflow.com/users/1410185",
"pm_score": 0,
"selected": false,
"text": "<p><code>readonly</code> can be initialized at declaration or get its value from the constructor only. Unlike <code>const</code> it has to be initialized and declare at the same time.\n<code>readonly</code> <em>has everything</em> <code>const</code> <em>has, plus constructor initialization</em></p>\n\n<p><strong>code</strong> <a href=\"https://repl.it/HvRU/1\" rel=\"nofollow noreferrer\">https://repl.it/HvRU/1</a></p>\n\n<pre><code>using System;\n\nclass MainClass {\n public static void Main (string[] args) {\n\n Console.WriteLine(new Test().c);\n Console.WriteLine(new Test(\"Constructor\").c);\n Console.WriteLine(new Test().ChangeC()); //Error A readonly field \n // `MainClass.Test.c' cannot be assigned to (except in a constructor or a \n // variable initializer)\n }\n\n\n public class Test {\n public readonly string c = \"Hello World\";\n public Test() {\n\n }\n\n public Test(string val) {\n c = val;\n }\n\n public string ChangeC() {\n c = \"Method\";\n return c ;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50090050,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 2,
"selected": false,
"text": "<p>Surprisingly, readonly can actually result in slower code, as Jon Skeet found when testing his Noda Time library. In this case, a test that ran in 20 seconds took only 4 seconds after removing readonly.</p>\n\n<p><a href=\"https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/\" rel=\"nofollow noreferrer\">https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/</a></p>\n"
},
{
"answer_id": 50897195,
"author": "code14214",
"author_id": 9775301,
"author_profile": "https://Stackoverflow.com/users/9775301",
"pm_score": 1,
"selected": false,
"text": "<p><em>Adding a basic aspect to answer this question:</em></p>\n\n<p>Properties can be expressed as readonly by leaving out the <code>set</code> operator. So in most cases you will not need to add the <code>readonly</code> keyword to properties:</p>\n\n<pre><code>public int Foo { get; } // a readonly property\n</code></pre>\n\n<p>In contrast to that: Fields need the <code>readonly</code> keyword to achieve a similar effect:</p>\n\n<pre><code>public readonly int Foo; // a readonly field\n</code></pre>\n\n<p>So, one benefit of marking a field as <code>readonly</code> can be to achieve a similar write protection level as a property without <code>set</code> operator - without having to change the field to a property, if for any reason, that is desired.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a class storing the name of a WS method to call and the type and value of the only parameter that service receives (it will be a collection of parameters but lets keep it simple for the example):
```
public class MethodCall
{
public string Method { get; set; }
public Type ParType { get; set; }
public string ParValue { get; set; }
public T CastedValue<T>()
{
return (T)Convert.ChangeType(ParValue, ParType);
}
}
```
I have a method that takes the method name and the parameters and using reflection calls the method and returns the result. That one works fine when i use it like this:
```
callingclass.URL = url;
callingclass.Service = serviceName;
object[] Params = { (decimal)1 };
callingclass.CallMethod("Hello", Params);
```
But my type, decimal in the example, is given in the instance of MethodCall. So if i have this code:
```
MethodCall call = new MethodCall();
call.Method = "Hello";
call.ParType = typeof(decimal);
call.ParValue = "1";
```
Option 1, doesn't compile:
```
object[] Params = { (call.ParType)call.ParValue }; //Compilation error: The type or namespace name 'call' could not be found (are you missing a using directive or an assembly reference?)
```
Option 2, doesn't compile neither:
```
object[] Params = { call.CastedValue<call.ParType>() }; //Compilation error: Cannot implicitly convert type 'call.ParType' to 'object'
```
Option 3, using reflection, compiles but doesn't work when calling the service:
```
object[] Params = { typeof(MethodCall).GetMethod("CastedValue").MakeGenericMethod(call.ParType).Invoke(this, null) };
callingclass.CallMethod(call.Method, Params);
```
The exception is:
ConnectionLib.WsProxyParameterExeption: The parameters for the method 'TestService.Hello' in URL '<http://localhost/MyTestingService/>' are wrong.
So can someone point me the right way to make this work?
Thanks
|
The `readonly` keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the `const` modifier, which must have its value set at compile time. Using `readonly` you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.
Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).
|
277,029 |
<p>Let's say I've got a setup that look something like</p>
<pre><code>phd/code/
phd/figures/
phd/thesis/
</code></pre>
<p>For historical reasons, these all have their own git repositories. But I'd like to combine them into a single one to simplify things a little. For example, right now I might make two sets of changes and have to do something like</p>
<pre><code>cd phd/code
git commit
cd ../figures
git commit
</code></pre>
<p>It'd be (now) nice to just to perform</p>
<pre><code>cd phd
git commit
</code></pre>
<p>There seems to be a couple of ways of doing this using submodules or pulling from my sub-repositories, but that's a little more complex than I'm looking for. At the very least, I'd be happy with</p>
<pre><code>cd phd
git init
git add [[everything that's already in my other repositories]]
</code></pre>
<p>but that doesn't seem like a one-liner. Is there anything in <code>git</code> that can help me out?</p>
|
[
{
"answer_id": 277068,
"author": "Patrick_O",
"author_id": 11084,
"author_profile": "https://Stackoverflow.com/users/11084",
"pm_score": 2,
"selected": false,
"text": "<p>The sequence you suggested</p>\n\n<pre><code>git init\ngit add *\ngit commit -a -m \"import everything\"\n</code></pre>\n\n<p>will work, but you will lose your commit history.</p>\n"
},
{
"answer_id": 277089,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p><a href=\"https://metacpan.org/pod/distribution/Git-FastExport/script/git-stitch-repo\" rel=\"noreferrer\"><code>git-stitch-repo</code></a> will process the output of <code>git-fast-export --all --date-order</code> on the git repositories given on the command-line, and create a stream suitable for <code>git-fast-import</code> that will create a new repository containing all the commits in a new commit tree that respects the history of all the source repositories.</p>\n</blockquote>\n"
},
{
"answer_id": 618113,
"author": "MiniQuark",
"author_id": 38626,
"author_profile": "https://Stackoverflow.com/users/38626",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a solution I gave <a href=\"https://stackoverflow.com/questions/614229/can-i-move-the-git-directory-for-a-repo-to-its-parent-directory/614254\">here</a>:</p>\n\n<ol>\n<li><p>First do a complete backup of your phd directory: I don't want to be held responsible for your losing years of hard work! ;-)</p>\n\n<pre><code>$ cp -r phd phd-backup\n</code></pre></li>\n<li><p>Move the content of <code>phd/code</code> to <code>phd/code/code</code>, and fix the history so that it looks like it has always been there (this uses git's <a href=\"http://git-scm.com/docs/git-filter-branch\" rel=\"noreferrer\">filter-branch</a> command):</p>\n\n<pre><code>$ cd phd/code\n$ git filter-branch --index-filter \\\n 'git ls-files -s | sed \"s#\\t#&code/#\" |\n GIT_INDEX_FILE=$GIT_INDEX_FILE.new \\\n git update-index --index-info &&\n mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE' HEAD\n</code></pre></li>\n<li><p>Same for the content of <code>phd/figures</code> and <code>phd/thesis</code> (just replace <code>code</code> with <code>figures</code> and <code>thesis</code>).</p>\n\n<p>Now your directory structure should look like this:</p>\n\n<pre><code>phd\n |_code\n | |_.git\n | |_code\n | |_(your code...)\n |_figures\n | |_.git\n | |_figures\n | |_(your figures...)\n |_thesis\n |_.git\n |_thesis\n |_(your thesis...)\n</code></pre></li>\n<li><p>Then create a git repository in the root directory, pull everything into it and remove the old repositories:</p>\n\n<pre><code>$ cd phd\n$ git init\n\n$ git pull code\n$ rm -rf code/code\n$ rm -rf code/.git\n\n$ git pull figures --allow-unrelated-histories\n$ rm -rf figures/figures\n$ rm -rf figures/.git\n\n$ git pull thesis --allow-unrelated-histories\n$ rm -rf thesis/thesis\n$ rm -rf thesis/.git\n</code></pre>\n\n<p>Finally, you should now have what you wanted:</p>\n\n<pre><code>phd\n |_.git\n |_code\n | |_(your code...)\n |_figures\n | |_(your figures...)\n |_thesis\n |_(your thesis...)\n</code></pre></li>\n</ol>\n\n<p>One nice side to this procedure is that it will leave <strong>non-versioned</strong> files and directories in place.</p>\n\n<p>Hope this helps.</p>\n\n<hr>\n\n<p>Just one word of warning though: if your <code>code</code> directory already has a <code>code</code> subdirectory or file, things might go very wrong (same for <code>figures</code> and <code>thesis</code> of course). If that's the case, just rename that directory or file before going through this whole procedure:</p>\n\n<pre><code>$ cd phd/code\n$ git mv code code-repository-migration\n$ git commit -m \"preparing the code directory for migration\"\n</code></pre>\n\n<p>And when the procedure is finished, add this final step:</p>\n\n<pre><code>$ cd phd\n$ git mv code/code-repository-migration code/code\n$ git commit -m \"final step for code directory migration\"\n</code></pre>\n\n<p>Of course, if the <code>code</code> subdirectory or file is not versioned, just use <code>mv</code> instead of <code>git mv</code>, and forget about the <code>git commit</code>s.</p>\n"
},
{
"answer_id": 779834,
"author": "imz -- Ivan Zakharyaschev",
"author_id": 94687,
"author_profile": "https://Stackoverflow.com/users/94687",
"pm_score": 4,
"selected": false,
"text": "<p>Perhaps, simply (similarly to the previous answer, but using simpler commands) making in each of the separate old repositories a commit that moves the content into a suitably named subdir, e.g.:</p>\n\n<pre><code>$ cd phd/code\n$ mkdir code\n# This won't work literally, because * would also match the new code/ subdir, but you understand what I mean:\n$ git mv * code/\n$ git commit -m \"preparing the code directory for migration\"\n</code></pre>\n\n<p>and then merging the three separate repos into one new, by doing smth like:</p>\n\n<pre><code>$ cd ../..\n$ mkdir phd.all\n$ cd phd.all\n$ git init\n$ git pull ../phd/code\n...\n</code></pre>\n\n<p>Then you'll save your histories, but will go on with a single repo.</p>\n"
},
{
"answer_id": 3336302,
"author": "Gareth",
"author_id": 98476,
"author_profile": "https://Stackoverflow.com/users/98476",
"pm_score": 3,
"selected": false,
"text": "<p>The git-filter-branch solution works well, but note that if your git repo comes from a SVN import it may fail with a message like:</p>\n\n<pre><code>Rewrite 422a38a0e9d2c61098b98e6c56213ac83b7bacc2 (1/42)mv: cannot stat `/home/.../wikis/nodows/.git-rewrite/t/../index.new': No such file or directory\n</code></pre>\n\n<p>In this case you need to exclude the initial revision from the filter-branch - i.e. change the <code>HEAD</code> at the end to <code>[SHA of 2nd revision]..HEAD</code> - see:</p>\n\n<p><a href=\"http://www.git.code-experiments.com/blog/2010/03/merging-git-repositories.html\" rel=\"noreferrer\">http://www.git.code-experiments.com/blog/2010/03/merging-git-repositories.html</a></p>\n"
},
{
"answer_id": 4950742,
"author": "Leif Gruenwoldt",
"author_id": 52176,
"author_profile": "https://Stackoverflow.com/users/52176",
"pm_score": 4,
"selected": false,
"text": "<p>You could try the <a href=\"http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html\" rel=\"nofollow noreferrer\">subtree merge strategy</a>. It will let you merge repo B into repo A. The advantage over <code>git-filter-branch</code> is it doesn't require you to rewrite your history of repo A (breaking SHA1 sums).</p>\n"
},
{
"answer_id": 6209656,
"author": "Giuseppe Monteleone",
"author_id": 3177235,
"author_profile": "https://Stackoverflow.com/users/3177235",
"pm_score": 2,
"selected": false,
"text": "<p>I have created a tool that make this task. The method used is similar (internally make some things like --filter-branch) but is more friendly. Is GPL 2.0 </p>\n\n<p><a href=\"http://github.com/geppo12/GitCombineRepo\" rel=\"nofollow\">http://github.com/geppo12/GitCombineRepo</a></p>\n"
},
{
"answer_id": 15606083,
"author": "MichK",
"author_id": 729156,
"author_profile": "https://Stackoverflow.com/users/729156",
"pm_score": 3,
"selected": false,
"text": "<p>@MiniQuark solution helped me a lot, but unfortunately it doesn't take into account tags which are in source repositories (At least in my case). Below is my improvement to @MiniQuark answer.</p>\n\n<ol>\n<li><p>First create directory which will contain composed repo and merged repos, create directory for each merged one.</p>\n\n<blockquote>\n <p>$ mkdir new_phd<br>\n $ mkdir new_phd/code<br>\n $ mkdir new_phd/figures<br>\n $ mkdir new_phd/thesis<br></p>\n</blockquote></li>\n<li><p>Do a pull of each repository and fetch all tags. (Presenting instructions only for <code>code</code> sub-directory)</p>\n\n<blockquote>\n <p>$ cd new_phd/code<br> \n $ git init<br>\n $ git pull ../../original_phd/code master<br>\n $ git fetch ../../original_phd/code refs/tags/*:refs/tags/*<br></p>\n</blockquote></li>\n<li><p>(This is improvement to point 2 in MiniQuark answer) Move the content of <code>new_phd/code</code> to <code>new_phd/code/code</code> and add <code>code_</code> prefeix before each <strong>tag</strong></p>\n\n<blockquote>\n <p>$ git filter-branch --index-filter 'git ls-files -s | sed \"s-\\t\\\"*-&code/-\" | GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info && mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE' --tag-name-filter 'sed \"s-.*-code_&-\"' HEAD</p>\n</blockquote></li>\n<li><p>After doing so there will be twice as many tags as it was before doing filter-branch. Old tags remain in repo and new tags with <code>code_</code> prefix are added. </p>\n\n<blockquote>\n <p>$ git tag<br>\n mytag1<br>\n code_mytag1<br></p>\n</blockquote>\n\n<p>Remove old tags manually:</p>\n\n<blockquote>\n <p>$ ls .git/refs/tags/* | grep -v \"/code_\" | xargs rm</p>\n</blockquote>\n\n<p>Repeat point 2,3,4 for other subdirectories</p></li>\n<li><p>Now we have structure of directories as in @MiniQuark anwser point 3. </p></li>\n<li><p>Do as in point 4 of MiniQuark anwser, but after doing a pull and before removing <code>.git</code> dir, fetch tags:</p>\n\n<blockquote>\n <p>$ git fetch catalog refs/tags/*:refs/tags/*</p>\n</blockquote>\n\n<p>Continue..</p></li>\n</ol>\n\n<p>This is just another solution. Hope it helps someone, it helped me :)</p>\n"
},
{
"answer_id": 20198026,
"author": "robinst",
"author_id": 305973,
"author_profile": "https://Stackoverflow.com/users/305973",
"pm_score": 3,
"selected": false,
"text": "<p>git-stitch-repo from <a href=\"https://stackoverflow.com/a/277089/305973\">Aristotle Pagaltzis' answer</a> only works for repositories with simple, linear history.</p>\n\n<p><a href=\"https://stackoverflow.com/a/618113/305973\">MiniQuark's answer</a> works for all repositories, but it does not handle tags and branches.</p>\n\n<p>I created a program that works the same way as MiniQuark describes, but it uses one merge commit (with N parents) and also recreates all tags and branches to point to these merge commits.</p>\n\n<p>See the <a href=\"https://github.com/robinst/git-merge-repos#readme\" rel=\"nofollow noreferrer\">git-merge-repos repository</a> for examples how to use it.</p>\n"
},
{
"answer_id": 23576353,
"author": "user3622356",
"author_id": 3622356,
"author_profile": "https://Stackoverflow.com/users/3622356",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, git-stitch-repo now supports branches and tags, including annotated tags (I found there was a bug which I reported, and it got fixed). What i found useful is with tags. Since tags are attached to commits, and some of the solutions (like Eric Lee's approach) fails to deal with tags. You try to create a branch off an imported tag, and it will undo any git merges/moves and sends you back like the consolidated repository being near identical to the repository that the tag came from. Also, there are issues if you use the same tag across multiple repositories that you 'merged/consolidated'. For example, if you have repo's A ad B, both having tag rel_1.0. You merge repo A and repo B into repo AB. Since rel_1.0 tags are on two different commits (one for A and one for B), which tag will be visible in AB? Either the tag from the imported repo A or from imported repo B, but not both.</p>\n\n<p>git-stitch-repo helps to address that problem by creating rel_1.0-A and rel_1.0-B tags. You may not be able to checkout rel_1.0 tag and expect both, but at least you can see both, and theoretically, you can merge them into a common local branch then create a rel_1.0 tag on that merged branch (assuming you just merge and not change source code). It's better to work with branches, as you can merge like branches from each repo into local branches. (dev-a and dev-b can be merged into a local dev branch which can then be pushed to origin). </p>\n"
},
{
"answer_id": 31682404,
"author": "user123568943685",
"author_id": 4953123,
"author_profile": "https://Stackoverflow.com/users/4953123",
"pm_score": 1,
"selected": false,
"text": "<p>To merge a secondProject within a mainProject:</p>\n\n<p>A) In the secondProject</p>\n\n<pre><code>git fast-export --all --date-order > /tmp/secondProjectExport\n</code></pre>\n\n<p>B) In the mainProject:</p>\n\n<pre><code>git checkout -b secondProject\ngit fast-import --force < /tmp/secondProjectExport\n</code></pre>\n\n<p>In this branch do all heavy transformation you need to do and commit them.</p>\n\n<p>C) Then back to the master and a classical merge between the two branches:</p>\n\n<pre><code>git checkout master\ngit merge secondProject\n</code></pre>\n"
},
{
"answer_id": 33181772,
"author": "chrishiestand",
"author_id": 324651,
"author_profile": "https://Stackoverflow.com/users/324651",
"pm_score": 0,
"selected": false,
"text": "<p>I'll throw my solution in here too. It's basically a fairly simple bash script wrapper around <code>git filter-branch</code>. Like other solutions it only migrates master branches and doesn't migrate tags. But the full master commit histories are migrated and it is a short bash script so it should be relatively easy for users to review or tweak.</p>\n\n<p><a href=\"https://github.com/Oakleon/git-join-repos\" rel=\"nofollow\">https://github.com/Oakleon/git-join-repos</a></p>\n"
},
{
"answer_id": 56788263,
"author": "bue",
"author_id": 8480811,
"author_profile": "https://Stackoverflow.com/users/8480811",
"pm_score": 0,
"selected": false,
"text": "<p>This bash script works around the <a href=\"https://unix.stackexchange.com/questions/145299/simple-sed-replacement-of-tabs-mysteriously-failing\">sed tab character</a> issue (on MacOS for example) and the issue of missing files.</p>\n\n<pre><code>export SUBREPO=\"subrepo\"; # <= your subrepository name here\nexport TABULATOR=`printf '\\t'`;\nFILTER='git ls-files -s | sed \"s#${TABULATOR}#&${SUBREPO}/#\" |\n GIT_INDEX_FILE=$GIT_INDEX_FILE.new \\\n git update-index --index-info &&\n if [ -f \"$GIT_INDEX_FILE.new\" ]; then mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE; else echo \"git filter skipped missing file: $GIT_INXEX_FILE.new\"; fi'\n\ngit filter-branch --index-filter \"$FILTER\" HEAD\n</code></pre>\n\n<p>This is a combination of <a href=\"https://stackoverflow.com/users/38626/miniquark\">miniquark</a>, <a href=\"https://stackoverflow.com/users/341929/marius-butuc\">marius-butuc</a> and <a href=\"https://stackoverflow.com/users/850830/ryan\">ryan</a>'s posts. Cheers to them!</p>\n"
},
{
"answer_id": 71854109,
"author": "Abelardo",
"author_id": 11043489,
"author_profile": "https://Stackoverflow.com/users/11043489",
"pm_score": 0,
"selected": false,
"text": "<p>I combined 3 git repositories into one manually with the help of Git integration in IntelliJ IDEA Community Edition.</p>\n<ol>\n<li>Create a new repo, add a new commit to the master branch with an empty README.md file.</li>\n<li>Add three remotes for the new repo, using the name of the 3 repositories and the remote URL of them respectively. Run Git Fetch.</li>\n<li>Create a new local branch named <code>temp</code> based on the master branch, so we can start over without pollute the master branch. Checkout the <code>temp</code> branch.</li>\n<li>Select to only show commits of one remote branch(one repository).</li>\n<li>Select all the commits and right click to Cherry-Pick them.</li>\n<li>Create directory structure for this repository, then move the files into it and commit.</li>\n<li>Repeat the step 4 to 6 for the other 2 remote branch(repository).</li>\n<li>When everything is OK, merge all the changes in the <code>temp</code> branch into master branch.</li>\n</ol>\n<p>Then add the origin remote URL for master branch and push to it.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] |
Let's say I've got a setup that look something like
```
phd/code/
phd/figures/
phd/thesis/
```
For historical reasons, these all have their own git repositories. But I'd like to combine them into a single one to simplify things a little. For example, right now I might make two sets of changes and have to do something like
```
cd phd/code
git commit
cd ../figures
git commit
```
It'd be (now) nice to just to perform
```
cd phd
git commit
```
There seems to be a couple of ways of doing this using submodules or pulling from my sub-repositories, but that's a little more complex than I'm looking for. At the very least, I'd be happy with
```
cd phd
git init
git add [[everything that's already in my other repositories]]
```
but that doesn't seem like a one-liner. Is there anything in `git` that can help me out?
|
Here's a solution I gave [here](https://stackoverflow.com/questions/614229/can-i-move-the-git-directory-for-a-repo-to-its-parent-directory/614254):
1. First do a complete backup of your phd directory: I don't want to be held responsible for your losing years of hard work! ;-)
```
$ cp -r phd phd-backup
```
2. Move the content of `phd/code` to `phd/code/code`, and fix the history so that it looks like it has always been there (this uses git's [filter-branch](http://git-scm.com/docs/git-filter-branch) command):
```
$ cd phd/code
$ git filter-branch --index-filter \
'git ls-files -s | sed "s#\t#&code/#" |
GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
git update-index --index-info &&
mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE' HEAD
```
3. Same for the content of `phd/figures` and `phd/thesis` (just replace `code` with `figures` and `thesis`).
Now your directory structure should look like this:
```
phd
|_code
| |_.git
| |_code
| |_(your code...)
|_figures
| |_.git
| |_figures
| |_(your figures...)
|_thesis
|_.git
|_thesis
|_(your thesis...)
```
4. Then create a git repository in the root directory, pull everything into it and remove the old repositories:
```
$ cd phd
$ git init
$ git pull code
$ rm -rf code/code
$ rm -rf code/.git
$ git pull figures --allow-unrelated-histories
$ rm -rf figures/figures
$ rm -rf figures/.git
$ git pull thesis --allow-unrelated-histories
$ rm -rf thesis/thesis
$ rm -rf thesis/.git
```
Finally, you should now have what you wanted:
```
phd
|_.git
|_code
| |_(your code...)
|_figures
| |_(your figures...)
|_thesis
|_(your thesis...)
```
One nice side to this procedure is that it will leave **non-versioned** files and directories in place.
Hope this helps.
---
Just one word of warning though: if your `code` directory already has a `code` subdirectory or file, things might go very wrong (same for `figures` and `thesis` of course). If that's the case, just rename that directory or file before going through this whole procedure:
```
$ cd phd/code
$ git mv code code-repository-migration
$ git commit -m "preparing the code directory for migration"
```
And when the procedure is finished, add this final step:
```
$ cd phd
$ git mv code/code-repository-migration code/code
$ git commit -m "final step for code directory migration"
```
Of course, if the `code` subdirectory or file is not versioned, just use `mv` instead of `git mv`, and forget about the `git commit`s.
|
277,055 |
<p>There are a couple of different ways to remove <code>HTML tags</code> from an <code>NSString</code> in <code>Cocoa</code>.</p>
<p><a href="http://cocoa.karelia.com/Foundation_Categories/NSString/_Flatten__a_string_.m" rel="noreferrer">One way</a> is to render the string into an <code>NSAttributedString</code> and then grab the rendered text.</p>
<p><a href="http://sugarmaplesoftware.com/25/strip-html-tags/#comment-71" rel="noreferrer">Another way</a> is to use <code>NSXMLDocument's</code> -<code>objectByApplyingXSLTString</code> method to apply an <code>XSLT</code> transform that does it.</p>
<p>Unfortunately, the iPhone doesn't support <code>NSAttributedString</code> or <code>NSXMLDocument</code>. There are too many edge cases and malformed <code>HTML</code> documents for me to feel comfortable using regex or <code>NSScanner</code>. Does anyone have a solution to this?</p>
<p>One suggestion has been to simply look for opening and closing tag characters, this method won't work except for very trivial cases. </p>
<p>For example these cases (from the Perl Cookbook chapter on the same subject) would break this method:</p>
<pre><code><IMG SRC = "foo.gif" ALT = "A > B">
<!-- <A comment> -->
<script>if (a<b && a>c)</script>
<![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
</code></pre>
|
[
{
"answer_id": 277083,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "<p>I would imagine the safest way would just be to parse for <>s, no? Loop through the entire string, and copy anything not enclosed in <>s to a new string. </p>\n"
},
{
"answer_id": 278917,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.</p>\n"
},
{
"answer_id": 287719,
"author": "micco",
"author_id": 37395,
"author_profile": "https://Stackoverflow.com/users/37395",
"pm_score": -1,
"selected": false,
"text": "<p>Here's a blog post that discusses a couple of libraries available for stripping HTML\n<a href=\"http://sugarmaplesoftware.com/25/strip-html-tags/\" rel=\"nofollow noreferrer\">http://sugarmaplesoftware.com/25/strip-html-tags/</a>\nNote the comments where others solutions are offered.</p>\n"
},
{
"answer_id": 1519230,
"author": "Biranchi",
"author_id": 97651,
"author_profile": "https://Stackoverflow.com/users/97651",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to get the content without the html tags from the web page (HTML document) , then use this code inside the <code>UIWebViewDidfinishLoading</code> <strong>delegate</strong> method.</p>\n\n<pre><code> NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@\"document.documentElement.textContent\"];\n</code></pre>\n"
},
{
"answer_id": 3855114,
"author": "jarnoan",
"author_id": 109351,
"author_profile": "https://Stackoverflow.com/users/109351",
"pm_score": 0,
"selected": false,
"text": "<p>If you are willing to use <a href=\"http://three20.info/\" rel=\"nofollow\">Three20 framework</a>, it has a category on NSString that adds stringByRemovingHTMLTags method. See NSStringAdditions.h in Three20Core subproject.</p>\n"
},
{
"answer_id": 4164041,
"author": "Mohamed AHDIDOU",
"author_id": 480643,
"author_profile": "https://Stackoverflow.com/users/480643",
"pm_score": 3,
"selected": false,
"text": "<p>use this </p>\n\n<pre><code>NSString *myregex = @\"<[^>]*>\"; //regex to remove any html tag\n\nNSString *htmlString = @\"<html>bla bla</html>\";\nNSString *stringWithoutHTML = [hstmString stringByReplacingOccurrencesOfRegex:myregex withString:@\"\"];\n</code></pre>\n\n<p>don't forget to include this in your code : #import \"RegexKitLite.h\"\nhere is the link to download this API : <a href=\"http://regexkit.sourceforge.net/#Downloads\" rel=\"nofollow noreferrer\">http://regexkit.sourceforge.net/#Downloads</a></p>\n"
},
{
"answer_id": 4886998,
"author": "m.kocikowski",
"author_id": 469997,
"author_profile": "https://Stackoverflow.com/users/469997",
"pm_score": 9,
"selected": true,
"text": "<p>A quick and \"dirty\" (removes everything between < and >) solution, works with iOS >= 3.2: </p>\n\n<pre><code>-(NSString *) stringByStrippingHTML {\n NSRange r;\n NSString *s = [[self copy] autorelease];\n while ((r = [s rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n s = [s stringByReplacingCharactersInRange:r withString:@\"\"];\n return s;\n}\n</code></pre>\n\n<p>I have this declared as a category os NSString. </p>\n"
},
{
"answer_id": 7034551,
"author": "Jim Liu",
"author_id": 888639,
"author_profile": "https://Stackoverflow.com/users/888639",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#import \"RegexKitLite.h\"\n\nstring text = [html stringByReplacingOccurrencesOfRegex:@\"<[^>]+>\" withString:@\"\"]\n</code></pre>\n"
},
{
"answer_id": 7341993,
"author": "Leigh McCulloch",
"author_id": 159762,
"author_profile": "https://Stackoverflow.com/users/159762",
"pm_score": 5,
"selected": false,
"text": "<p>This <code>NSString</code> category uses the <code>NSXMLParser</code> to accurately remove any <code>HTML</code> tags from an <code>NSString</code>. This is a single <code>.m</code> and <code>.h</code> file that can be included into your project easily.</p>\n\n<p><a href=\"https://gist.github.com/leighmcculloch/1202238\" rel=\"noreferrer\">https://gist.github.com/leighmcculloch/1202238</a></p>\n\n<p>You then strip <code>html</code> by doing the following:</p>\n\n<p>Import the header:</p>\n\n<pre><code>#import \"NSString_stripHtml.h\"\n</code></pre>\n\n<p>And then call stripHtml:</p>\n\n<pre><code>NSString* mystring = @\"<b>Hello</b> World!!\";\nNSString* stripped = [mystring stripHtml];\n// stripped will be = Hello World!!\n</code></pre>\n\n<p>This also works with malformed <code>HTML</code> that technically isn't <code>XML</code>.</p>\n"
},
{
"answer_id": 12115786,
"author": "Dan J",
"author_id": 112705,
"author_profile": "https://Stackoverflow.com/users/112705",
"pm_score": 2,
"selected": false,
"text": "<p>I've extended the answer by m.kocikowski and tried to make it a bit more efficient by using an NSMutableString. I've also structured it for use in a static Utils class (I know a Category is probably the best design though), and removed the autorelease so it compiles in an ARC project.</p>\n\n<p>Included here in case anybody finds it useful.</p>\n\n<p><strong>.h</strong></p>\n\n<pre><code>+ (NSString *)stringByStrippingHTML:(NSString *)inputString;\n</code></pre>\n\n<p><strong>.m</strong></p>\n\n<pre><code>+ (NSString *)stringByStrippingHTML:(NSString *)inputString \n{\n NSMutableString *outString;\n\n if (inputString)\n {\n outString = [[NSMutableString alloc] initWithString:inputString];\n\n if ([inputString length] > 0)\n {\n NSRange r;\n\n while ((r = [outString rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n {\n [outString deleteCharactersInRange:r];\n } \n }\n }\n\n return outString; \n}\n</code></pre>\n"
},
{
"answer_id": 17081186,
"author": "MANCHIKANTI KRISHNAKISHORE",
"author_id": 2131470,
"author_profile": "https://Stackoverflow.com/users/2131470",
"pm_score": 4,
"selected": false,
"text": "<pre><code>UITextView *textview= [[UITextView alloc]initWithFrame:CGRectMake(10, 130, 250, 170)];\nNSString *str = @\"This is <font color='red'>simple</font>\";\n[textview setValue:str forKey:@\"contentToHTMLString\"];\ntextview.textAlignment = NSTextAlignmentLeft;\ntextview.editable = NO;\ntextview.font = [UIFont fontWithName:@\"vardana\" size:20.0];\n[UIView addSubview:textview];\n</code></pre>\n\n<p>work fine for me</p>\n"
},
{
"answer_id": 17868362,
"author": "Ashoor",
"author_id": 1448370,
"author_profile": "https://Stackoverflow.com/users/1448370",
"pm_score": 0,
"selected": false,
"text": "<p>Extending this more from m.kocikowski's and Dan J's answers with more explanation for newbies</p>\n\n<p>1# First you have to create <a href=\"http://mobile.tutsplus.com/tutorials/iphone/objective-c-categories/\" rel=\"nofollow\">objective-c-categories</a> to make the code useable in any class.</p>\n\n<p><strong>.h</strong></p>\n\n<pre><code>@interface NSString (NAME_OF_CATEGORY)\n\n- (NSString *)stringByStrippingHTML;\n\n@end\n</code></pre>\n\n<p><strong>.m</strong></p>\n\n<pre><code>@implementation NSString (NAME_OF_CATEGORY)\n\n- (NSString *)stringByStrippingHTML\n{\nNSMutableString *outString;\nNSString *inputString = self;\n\nif (inputString)\n{\n outString = [[NSMutableString alloc] initWithString:inputString];\n\n if ([inputString length] > 0)\n {\n NSRange r;\n\n while ((r = [outString rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n {\n [outString deleteCharactersInRange:r];\n }\n }\n}\n\nreturn outString;\n}\n\n@end\n</code></pre>\n\n<p>2# Then just import the <strong>.h</strong> file of the category class you've just created e.g.</p>\n\n<pre><code>#import \"NSString+NAME_OF_CATEGORY.h\"\n</code></pre>\n\n<p>3# Calling the Method.</p>\n\n<pre><code>NSString* sub = [result stringByStrippingHTML];\nNSLog(@\"%@\", sub);\n</code></pre>\n\n<p><em>result</em> is NSString I want to strip the tags from.</p>\n"
},
{
"answer_id": 18969560,
"author": "digipeople",
"author_id": 1571878,
"author_profile": "https://Stackoverflow.com/users/1571878",
"pm_score": 2,
"selected": false,
"text": "<p>This is the modernization of <strong>m.kocikowski</strong> answer which removes whitespaces:</p>\n\n<pre><code>@implementation NSString (StripXMLTags)\n\n- (NSString *)stripXMLTags\n{\n NSRange r;\n NSString *s = [self copy];\n while ((r = [s rangeOfString:@\"<[^>]+>\\\\s*\" options:NSRegularExpressionSearch]).location != NSNotFound)\n s = [s stringByReplacingCharactersInRange:r withString:@\"\"];\n return s;\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 19291394,
"author": "Kirtikumar A.",
"author_id": 1376496,
"author_profile": "https://Stackoverflow.com/users/1376496",
"pm_score": 3,
"selected": false,
"text": "<p>You can use like below</p>\n\n<pre><code>-(void)myMethod\n {\n\n NSString* htmlStr = @\"<some>html</string>\";\n NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];\n\n }\n\n -(NSString *)stringByStrippingHTML:(NSString*)str\n {\n NSRange r;\n while ((r = [str rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n {\n str = [str stringByReplacingCharactersInRange:r withString:@\"\"];\n }\n return str;\n }\n</code></pre>\n"
},
{
"answer_id": 22382214,
"author": "hpique",
"author_id": 143378,
"author_profile": "https://Stackoverflow.com/users/143378",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a more efficient solution than the accepted answer:</p>\n\n<pre><code>- (NSString*)hp_stringByRemovingTags\n{\n static NSRegularExpression *regex = nil;\n static dispatch_once_t onceToken;\n dispatch_once(&onceToken, ^{\n regex = [NSRegularExpression regularExpressionWithPattern:@\"<[^>]+>\" options:kNilOptions error:nil];\n });\n\n // Use reverse enumerator to delete characters without affecting indexes\n NSArray *matches =[regex matchesInString:self options:kNilOptions range:NSMakeRange(0, self.length)];\n NSEnumerator *enumerator = matches.reverseObjectEnumerator;\n\n NSTextCheckingResult *match = nil;\n NSMutableString *modifiedString = self.mutableCopy;\n while ((match = [enumerator nextObject]))\n {\n [modifiedString deleteCharactersInRange:match.range];\n }\n return modifiedString;\n}\n</code></pre>\n\n<p>The above <code>NSString</code> category uses a regular expression to find all the matching tags, makes a copy of the original string and finally removes all the tags in place by iterating over them in reverse order. It's more efficient because:</p>\n\n<ul>\n<li>The regular expression is initialised only once.</li>\n<li>A single copy of the original string is used.</li>\n</ul>\n\n<p>This performed well enough for me but a solution using <code>NSScanner</code> might be more efficient.</p>\n\n<p>Like the accepted answer, this solution doesn't address all the border cases requested by @lfalin. Those would be require much more expensive parsing which the average use case most likely doesn't need.</p>\n"
},
{
"answer_id": 23861119,
"author": "Rémy",
"author_id": 87988,
"author_profile": "https://Stackoverflow.com/users/87988",
"pm_score": 3,
"selected": false,
"text": "<p>Without a loop (at least on our side) :</p>\n\n<pre><code>- (NSString *)removeHTML {\n\n static NSRegularExpression *regexp;\n static dispatch_once_t onceToken;\n dispatch_once(&onceToken, ^{\n regexp = [NSRegularExpression regularExpressionWithPattern:@\"<[^>]+>\" options:kNilOptions error:nil];\n });\n\n return [regexp stringByReplacingMatchesInString:self\n options:kNilOptions\n range:NSMakeRange(0, self.length)\n withTemplate:@\"\"];\n}\n</code></pre>\n"
},
{
"answer_id": 28596272,
"author": "tmr",
"author_id": 3120387,
"author_profile": "https://Stackoverflow.com/users/3120387",
"pm_score": 1,
"selected": false,
"text": "<p>following is the accepted answer, but instead of category, it is simple helper method with string passed into it. (thank you m.kocikowski)</p>\n\n<pre><code>-(NSString *) stringByStrippingHTML:(NSString*)originalString {\n NSRange r;\n NSString *s = [originalString copy];\n while ((r = [s rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n s = [s stringByReplacingCharactersInRange:r withString:@\"\"];\n return s;\n}\n</code></pre>\n"
},
{
"answer_id": 29207038,
"author": "Pavan Sisode",
"author_id": 4107865,
"author_profile": "https://Stackoverflow.com/users/4107865",
"pm_score": 3,
"selected": false,
"text": "<pre><code>NSAttributedString *str=[[NSAttributedString alloc] initWithData:[trimmedString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];\n</code></pre>\n"
},
{
"answer_id": 29806531,
"author": "jcpennypincher",
"author_id": 407379,
"author_profile": "https://Stackoverflow.com/users/407379",
"pm_score": 0,
"selected": false,
"text": "<p>I have following the accepted answer by m.kocikowski and modified is slightly to make use of an autoreleasepool to cleanup all of the temporary strings that are created by stringByReplacingCharactersInRange</p>\n\n<p>In the comment for this method it states, /* Replace characters in range with the specified string, returning new string.\n*/</p>\n\n<p>So, depending on the length of your XML you may be creating a huge pile of new autorelease strings which are not cleaned up until the end of the next @autoreleasepool. If you are unsure when that may happen or if a user action could repeatedly trigger many calls to this method before then you can just wrap this up in an @autoreleasepool. These can even be nested and used within loops where possible.</p>\n\n<p>Apple's reference on @autoreleasepool states this... \"If you write a loop that creates many temporary objects. You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.\" I have not used it in the loop, but at least this method cleans up after itself now.</p>\n\n<pre><code>- (NSString *) stringByStrippingHTML {\n NSString *retVal;\n @autoreleasepool {\n NSRange r;\n NSString *s = [[self copy] autorelease];\n while ((r = [s rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound) {\n s = [s stringByReplacingCharactersInRange:r withString:@\"\"];\n }\n retVal = [s copy];\n } \n // pool is drained, release s and all temp \n // strings created by stringByReplacingCharactersInRange\n return retVal;\n}\n</code></pre>\n"
},
{
"answer_id": 33594101,
"author": "JohnVanDijk",
"author_id": 2426994,
"author_profile": "https://Stackoverflow.com/users/2426994",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the swift version :</p>\n\n<pre><code>func stripHTMLFromString(string: String) -> String {\n var copy = string\n while let range = copy.rangeOfString(\"<[^>]+>\", options: .RegularExpressionSearch) {\n copy = copy.stringByReplacingCharactersInRange(range, withString: \"\")\n }\n copy = copy.stringByReplacingOccurrencesOfString(\"&nbsp;\", withString: \" \")\n copy = copy.stringByReplacingOccurrencesOfString(\"&amp;\", withString: \"&\")\n return copy\n}\n</code></pre>\n"
},
{
"answer_id": 35034929,
"author": "Nike Kov",
"author_id": 5790492,
"author_profile": "https://Stackoverflow.com/users/5790492",
"pm_score": 0,
"selected": false,
"text": "<p>Another one way:</p>\n\n<p><strong>Interface:</strong></p>\n\n<p><code>-(NSString *) stringByStrippingHTML:(NSString*)inputString;</code></p>\n\n<p><strong>Implementation</strong></p>\n\n<pre><code>(NSString *) stringByStrippingHTML:(NSString*)inputString\n{ \nNSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[inputString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];\nNSString *str= [attrString string]; \n\n//you can add here replacements as your needs:\n [str stringByReplacingOccurrencesOfString:@\"[\" withString:@\"\"];\n [str stringByReplacingOccurrencesOfString:@\"]\" withString:@\"\"];\n [str stringByReplacingOccurrencesOfString:@\"\\n\" withString:@\"\"];\n\n return str;\n}\n</code></pre>\n\n<p><strong>Realization</strong></p>\n\n<p><code>cell.exampleClass.text = [self stringByStrippingHTML:[exampleJSONParsingArray valueForKey: @\"key\"]];</code></p>\n\n<p>or simple</p>\n\n<p><code>NSString *myClearStr = [self stringByStrippingHTML:rudeStr];</code></p>\n"
},
{
"answer_id": 46582739,
"author": "Ahmed Awad",
"author_id": 1043006,
"author_profile": "https://Stackoverflow.com/users/1043006",
"pm_score": 0,
"selected": false,
"text": "<p>An updated answer for @m.kocikowski that works on recent iOS versions.</p>\n\n<pre><code>-(NSString *) stringByStrippingHTMLFromString:(NSString *)str {\nNSRange range;\nwhile ((range = [str rangeOfString:@\"<[^>]+>\" options:NSRegularExpressionSearch]).location != NSNotFound)\n str = [str stringByReplacingCharactersInRange:range withString:@\"\"];\nreturn str;\n</code></pre>\n\n<p>}</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28106/"
] |
There are a couple of different ways to remove `HTML tags` from an `NSString` in `Cocoa`.
[One way](http://cocoa.karelia.com/Foundation_Categories/NSString/_Flatten__a_string_.m) is to render the string into an `NSAttributedString` and then grab the rendered text.
[Another way](http://sugarmaplesoftware.com/25/strip-html-tags/#comment-71) is to use `NSXMLDocument's` -`objectByApplyingXSLTString` method to apply an `XSLT` transform that does it.
Unfortunately, the iPhone doesn't support `NSAttributedString` or `NSXMLDocument`. There are too many edge cases and malformed `HTML` documents for me to feel comfortable using regex or `NSScanner`. Does anyone have a solution to this?
One suggestion has been to simply look for opening and closing tag characters, this method won't work except for very trivial cases.
For example these cases (from the Perl Cookbook chapter on the same subject) would break this method:
```
<IMG SRC = "foo.gif" ALT = "A > B">
<!-- <A comment> -->
<script>if (a<b && a>c)</script>
<![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
```
|
A quick and "dirty" (removes everything between < and >) solution, works with iOS >= 3.2:
```
-(NSString *) stringByStrippingHTML {
NSRange r;
NSString *s = [[self copy] autorelease];
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}
```
I have this declared as a category os NSString.
|
277,077 |
<p>I'm a Git newbie. I recently moved a Rails project from Subversion to Git. I followed the tutorial here: <a href="http://www.simplisticcomplexity.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/" rel="noreferrer">http://www.simplisticcomplexity.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/</a></p>
<p>I am also using unfuddle.com to store my code. I make changes on my Mac laptop on the train to/from work and then push them to unfuddle when I have a network connection using the following command:</p>
<pre><code>git push unfuddle master
</code></pre>
<p>I use Capistrano for deployments and pull code from the unfuddle repository using the master branch.</p>
<p>Lately I've noticed the following message when I run "git status" on my laptop:</p>
<pre><code># On branch master
# Your branch is ahead of 'origin/master' by 11 commits.
#
nothing to commit (working directory clean)
</code></pre>
<p>And I'm confused as to why. I thought my laptop was the origin... but don't know if either the fact that I originally pulled from Subversion or push to Unfuddle is what's causing the message to show up. How can I:</p>
<ol>
<li>Find out where Git thinks 'origin/master' is?</li>
<li>If it's somewhere else, how do I turn my laptop into the 'origin/master'?</li>
<li>Get this message to go away. It makes me think Git is unhappy about something.</li>
</ol>
<p>My mac is running Git version 1.6.0.1.</p>
<hr>
<p>When I run <code>git remote show origin</code> as suggested by dbr, I get the following:</p>
<pre><code>~/Projects/GeekFor/geekfor 10:47 AM $ git remote show origin
fatal: '/Users/brian/Projects/GeekFor/gf/.git': unable to chdir or not a git archive
fatal: The remote end hung up unexpectedly
</code></pre>
<p>When I run <code>git remote -v</code> as suggested by Aristotle Pagaltzis, I get the following:</p>
<pre><code>~/Projects/GeekFor/geekfor 10:33 AM $ git remote -v
origin /Users/brian/Projects/GeekFor/gf/.git
unfuddle [email protected]:spilth/geekfor.git
</code></pre>
<p>Now, interestingly, I'm working on my project in the <code>geekfor</code> directory but it says my origin is my local machine in the <code>gf</code> directory. I believe <code>gf</code> was the temporary directory I used when converting my project from Subversion to Git and probably where I pushed to unfuddle from. Then I believe I checked out a fresh copy from unfuddle to the <code>geekfor</code> directory.</p>
<p>So it looks like I should follow dbr's advice and do:</p>
<pre><code>git remote rm origin
git remote add origin [email protected]:spilth/geekfor.git
</code></pre>
|
[
{
"answer_id": 277098,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I thought my laptop was the origin…</p>\n</blockquote>\n\n<p>That’s kind of nonsensical: <code>origin</code> refers to the default remote repository – the one you usually fetch/pull other people’s changes from.</p>\n\n<blockquote>\n <p>How can I:</p>\n</blockquote>\n\n<ol>\n<li><p><code>git remote -v</code> will show you what <code>origin</code> is; <code>origin/master</code> is your “bookmark” for the last known state of the <code>master</code> branch of the <code>origin</code> repository, and your own <code>master</code> is a <a href=\"http://book.git-scm.com/4_tracking_branches.html\" rel=\"noreferrer\">tracking branch</a> for <code>origin/master</code>. <a href=\"http://book.git-scm.com/3_distributed_workflows.html\" rel=\"noreferrer\">This is all as it should be</a>.</p></li>\n<li><p>You don’t. At least it makes no sense for a repository to be the default remote repository for itself.</p></li>\n<li><p>It isn’t. It’s merely telling you that you have made so-and-so many commits locally which aren’t in the remote repository (according to the last known state of that repository).</p></li>\n</ol>\n"
},
{
"answer_id": 277186,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 9,
"selected": true,
"text": "<blockquote>\n <p><code>1.</code> Find out where Git thinks 'origin/master' is using <a href=\"http://schacon.github.com/git/git-remote.html#_commands\" rel=\"noreferrer\"><code>git-remote</code></a></p>\n</blockquote>\n\n<pre><code>git remote show origin\n</code></pre>\n\n<p>..which will return something like..</p>\n\n<pre><code>* remote origin\n URL: [email protected]:~/something.git\n Remote branch merged with 'git pull' while on branch master\n master\n Tracked remote branch\n master\n</code></pre>\n\n<p>A remote is basically a link to a remote repository. When you do..</p>\n\n<pre><code>git remote add unfuddle [email protected]/myrepo.git\ngit push unfuddle\n</code></pre>\n\n<p>..git will push changes to that address you added. It's like a bookmark, for remote repositories.</p>\n\n<p>When you run <code>git status</code>, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to \"origin\", both will be in sync, so you wont get that message.</p>\n\n<blockquote>\n <p><code>2.</code> If it's somewhere else, how do I turn my laptop into the 'origin/master'?</p>\n</blockquote>\n\n<p>There is no point in doing this. Say \"origin\" is renamed to \"laptop\" - you never want to do <code>git push laptop</code> from your laptop.</p>\n\n<p>If you want to remove the origin remote, you do..</p>\n\n<pre><code>git remote rm origin\n</code></pre>\n\n<p>This wont delete anything (in terms of file-content/revisions-history). This will stop the \"your branch is ahead by..\" message, as it will no longer compare your repository with the remote (because it's gone!)</p>\n\n<p>One thing to remember is that there is nothing special about <code>origin</code>, it's just a default name git uses.</p>\n\n<p>Git does use <code>origin</code> by default when you do things like <code>git push</code> or <code>git pull</code>. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as \"origin\":</p>\n\n<pre><code>git remote rm origin\ngit remote add origin [email protected]:subdomain/abbreviation.git\n</code></pre>\n\n<p>or do the above in one command using set-url:</p>\n\n<pre><code>git remote set-url origin [email protected]:subdomain/abbreviation.git\n</code></pre>\n\n<p>Then you can simply do <code>git push</code> or <code>git pull</code> to update, instead of <code>git push unfuddle master</code></p>\n"
},
{
"answer_id": 2586716,
"author": "Earl Jenkins",
"author_id": 305306,
"author_profile": "https://Stackoverflow.com/users/305306",
"pm_score": 8,
"selected": false,
"text": "<p>I came to this question looking for an explanation about what the message \"your branch is ahead by...\" means, in the general scheme of git. There was no answer to that here, but since this question currently shows up at the top of Google when you search for the phrase \"Your branch is ahead of 'origin/master'\", and I have since figured out what the message really means, I thought I'd post the info here.</p>\n\n<p>So, being a git newbie, I can see that the answer I needed was a distinctly newbie answer. Specifically, what the \"your branch is ahead by...\" phrase means is that there are files you've added and committed to your local repository, but have never pushed to the origin. The intent of this message is further obfuscated by the fact that \"git diff\", at least for me, showed no differences. It wasn't until I ran \"git diff origin/master\" that I was told that there were differences between my local repository, and the remote master.</p>\n\n<p>So, to be clear:</p>\n\n<hr>\n\n<p><strong>\"your branch is ahead by...\"</strong> => You need to push to the remote master. Run <strong>\"git diff origin/master\"</strong> to see what the differences are between your local repository and the remote master repository.</p>\n\n<hr>\n\n<p>Hope this helps other newbies.</p>\n\n<p>(Also, I recognize that there are configuration subtleties that may partially invalidate this solution, such as the fact that the master may not actually be \"remote\", and that \"origin\" is a reconfigurable name used by convention, etc. But newbies do not care about that sort of thing. We want simple, straightforward answers. We can read about the subtleties later, once we've solved the pressing problem.)</p>\n\n<p>Earl</p>\n"
},
{
"answer_id": 3365668,
"author": "Steve Hindmarch",
"author_id": 406023,
"author_profile": "https://Stackoverflow.com/users/406023",
"pm_score": 1,
"selected": false,
"text": "<p>I am struggling with this problem and none of the previous answers tackle the question as I see it. I have stripped the problem back down to its basics to see if I can make my problem clear.</p>\n\n<p>I create a new repository (rep1), put one file in it and commit it.</p>\n\n<pre><code>mkdir rep1\ncd rep1\ngit init\necho \"Line1\" > README\ngit add README\ngit commit -m \"Commit 1\"\n</code></pre>\n\n<p>I create a clone of rep1 and call it rep2. I look inside rep2 and see the file is correct.</p>\n\n<pre><code>cd ~\ngit clone ~/rep1 rep2\ncat ~/rep2/README\n</code></pre>\n\n<p>In rep1 I make a single change to the file and commit it. Then in rep1 I create a remote to point to rep2 and push the changes.</p>\n\n<pre><code>cd ~/rep1\n<change file and commit>\ngit remote add rep2 ~/rep2\ngit push rep2 master\n</code></pre>\n\n<p>Now when I go into rep2 and do a 'git status' I get told I am ahead of origin.</p>\n\n<pre><code># On branch master\n# Your branch is ahead of 'origin/master' by 1 commit.\n#\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n# modified: README\n#\n</code></pre>\n\n<p>README in rep2 is as it was originally, before the second commit. The only modifications I have done are to rep1 and all I wanted to do was push them out to rep2. What is it I am not grasping?</p>\n"
},
{
"answer_id": 5480767,
"author": "Mims H. Wright",
"author_id": 168665,
"author_profile": "https://Stackoverflow.com/users/168665",
"pm_score": 5,
"selected": false,
"text": "<p>I had a problem that was similar to this where my working directory was <code>ahead of origin by X commits</code> but the <code>git pull</code> was resulting in <code>Everything up-to-date</code>. I did manage to fix it by following <a href=\"http://fvue.nl/wiki/Git:_Your_branch_is_ahead_of_the_tracked_remote_branch\" rel=\"noreferrer\">this advice</a>. I'm posting this here in case it helps someone else with a similar problem.</p>\n\n<p>The basic fix is as follows:</p>\n\n<pre><code>$ git push {remote} {localbranch}:{remotebranch}\n</code></pre>\n\n<p>Where the words in brackets should be replaced by your remote name, your local branch name and your remote branch name. e.g.</p>\n\n<pre><code>$ git push origin master:master\n</code></pre>\n"
},
{
"answer_id": 5725070,
"author": "Vino",
"author_id": 716351,
"author_profile": "https://Stackoverflow.com/users/716351",
"pm_score": 1,
"selected": false,
"text": "<p>It's waiting for you to \"push\". Try:</p>\n\n<p><code>$ git push</code></p>\n"
},
{
"answer_id": 6206582,
"author": "Chris",
"author_id": 733839,
"author_profile": "https://Stackoverflow.com/users/733839",
"pm_score": 2,
"selected": false,
"text": "<p><strong>[ Solution ]</strong></p>\n\n<pre><code>$ git push origin\n</code></pre>\n\n<p>^ this solved it for me. \nWhat it did, it synchronized my master (on laptop) with \"origin\" that's on the remote server.</p>\n"
},
{
"answer_id": 6300652,
"author": "Jason Rikard",
"author_id": 116316,
"author_profile": "https://Stackoverflow.com/users/116316",
"pm_score": 0,
"selected": false,
"text": "<p>I was wondering the same thing about my repo. In my case I had an old remote that I wasn't pushing to anymore so I needed to remove it.</p>\n\n<p>Get list of remotes:</p>\n\n<pre><code>git remote\n</code></pre>\n\n<p>Remove the one that you don't need</p>\n\n<pre><code>git remote rm {insert remote to remove}\n</code></pre>\n"
},
{
"answer_id": 6823099,
"author": "looneydoodle",
"author_id": 604556,
"author_profile": "https://Stackoverflow.com/users/604556",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem recently and I figured it was because I had deleted some files that I did not need anymore. The problem is that git does not know that the files have been deleted and it sees that the server still has it. (server = origin)</p>\n\n<p>So I ran </p>\n\n<pre><code>git rm $(git ls-files --deleted)\n</code></pre>\n\n<p>And then ran a commit and push. </p>\n\n<p>That solved the issue.</p>\n"
},
{
"answer_id": 7163484,
"author": "RobLoach",
"author_id": 689971,
"author_profile": "https://Stackoverflow.com/users/689971",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to reset to a specific commit before your own commits take place.</p>\n\n<pre><code>$ git status\n# On branch master\n# Your branch is ahead of 'origin/master' by 2 commits.\n#\nnothing to commit (working directory clean)\n</code></pre>\n\n<p>Use <code>git log</code> to find what commit was the commit you had before the local changes took place.</p>\n\n<pre><code>$ git log\ncommit 3368e1c5b8a47135a34169c885e8dd5ba01af5bb\n...\ncommit baf8d5e7da9e41fcd37d63ae9483ee0b10bfac8e\n...\n</code></pre>\n\n<p>Take note of the local commits and reset directly to the previous commit:</p>\n\n<pre><code>git reset --hard baf8d5e7da9e41fcd37d63ae9483ee0b10bfac8e\n</code></pre>\n"
},
{
"answer_id": 8720030,
"author": "Nara Narasimhan",
"author_id": 1128864,
"author_profile": "https://Stackoverflow.com/users/1128864",
"pm_score": 1,
"selected": false,
"text": "<p>I am a git newbie as well. I had the same problem with 'your branch is ahead of origin/master by N commits' messages. Doing the suggested 'git diff origin/master' did show some diffs that I did not care to keep. So ...</p>\n\n<p>Since my git clone was for hosting, and I wanted an exact copy of the master repo, and did not care to keep any local changes, I decided to save off my entire repo, and create a new one:</p>\n\n<p>(on the hosting machine)</p>\n\n<pre><code>mv myrepo myrepo\ngit clone USER@MASTER_HOST:/REPO_DIR myrepo\n</code></pre>\n\n<p>For expediency, I used to make changes to the clone on my hosting machine. No more. I will make those changes to the master, git commit there, and do a git pull. Hopefully, this should keep my git clone on the hosting machine in complete sync.</p>\n\n<p>/Nara</p>\n"
},
{
"answer_id": 8894082,
"author": "noob",
"author_id": 1153819,
"author_profile": "https://Stackoverflow.com/users/1153819",
"pm_score": -1,
"selected": false,
"text": "<p>I had the problem \"Your branch is ahead of 'origin/master' by nn commits.\" when i pushed to a remote repository with:</p>\n\n<pre><code>git push ssh://[email protected]/yyy/zzz.git\n</code></pre>\n\n<p>When i found that my remote adress was in the file .git/FETCH_HEAD and used:</p>\n\n<pre><code>git push\n</code></pre>\n\n<p>the problem disappeared.</p>\n"
},
{
"answer_id": 10949152,
"author": "chim",
"author_id": 673282,
"author_profile": "https://Stackoverflow.com/users/673282",
"pm_score": 5,
"selected": false,
"text": "<p>sometimes there's a difference between the local cached version of origin master (origin/master) and the true origin master.</p>\n\n<p>If you run <code>git remote update</code> this will resynch origin master with origin/master</p>\n\n<p>see the accepted answer to this question</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2883840/differences-between-git-pull-origin-master-git-pull-origin-master\">Differences between git pull origin master & git pull origin/master</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8252/"
] |
I'm a Git newbie. I recently moved a Rails project from Subversion to Git. I followed the tutorial here: <http://www.simplisticcomplexity.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/>
I am also using unfuddle.com to store my code. I make changes on my Mac laptop on the train to/from work and then push them to unfuddle when I have a network connection using the following command:
```
git push unfuddle master
```
I use Capistrano for deployments and pull code from the unfuddle repository using the master branch.
Lately I've noticed the following message when I run "git status" on my laptop:
```
# On branch master
# Your branch is ahead of 'origin/master' by 11 commits.
#
nothing to commit (working directory clean)
```
And I'm confused as to why. I thought my laptop was the origin... but don't know if either the fact that I originally pulled from Subversion or push to Unfuddle is what's causing the message to show up. How can I:
1. Find out where Git thinks 'origin/master' is?
2. If it's somewhere else, how do I turn my laptop into the 'origin/master'?
3. Get this message to go away. It makes me think Git is unhappy about something.
My mac is running Git version 1.6.0.1.
---
When I run `git remote show origin` as suggested by dbr, I get the following:
```
~/Projects/GeekFor/geekfor 10:47 AM $ git remote show origin
fatal: '/Users/brian/Projects/GeekFor/gf/.git': unable to chdir or not a git archive
fatal: The remote end hung up unexpectedly
```
When I run `git remote -v` as suggested by Aristotle Pagaltzis, I get the following:
```
~/Projects/GeekFor/geekfor 10:33 AM $ git remote -v
origin /Users/brian/Projects/GeekFor/gf/.git
unfuddle [email protected]:spilth/geekfor.git
```
Now, interestingly, I'm working on my project in the `geekfor` directory but it says my origin is my local machine in the `gf` directory. I believe `gf` was the temporary directory I used when converting my project from Subversion to Git and probably where I pushed to unfuddle from. Then I believe I checked out a fresh copy from unfuddle to the `geekfor` directory.
So it looks like I should follow dbr's advice and do:
```
git remote rm origin
git remote add origin [email protected]:spilth/geekfor.git
```
|
>
> `1.` Find out where Git thinks 'origin/master' is using [`git-remote`](http://schacon.github.com/git/git-remote.html#_commands)
>
>
>
```
git remote show origin
```
..which will return something like..
```
* remote origin
URL: [email protected]:~/something.git
Remote branch merged with 'git pull' while on branch master
master
Tracked remote branch
master
```
A remote is basically a link to a remote repository. When you do..
```
git remote add unfuddle [email protected]/myrepo.git
git push unfuddle
```
..git will push changes to that address you added. It's like a bookmark, for remote repositories.
When you run `git status`, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to "origin", both will be in sync, so you wont get that message.
>
> `2.` If it's somewhere else, how do I turn my laptop into the 'origin/master'?
>
>
>
There is no point in doing this. Say "origin" is renamed to "laptop" - you never want to do `git push laptop` from your laptop.
If you want to remove the origin remote, you do..
```
git remote rm origin
```
This wont delete anything (in terms of file-content/revisions-history). This will stop the "your branch is ahead by.." message, as it will no longer compare your repository with the remote (because it's gone!)
One thing to remember is that there is nothing special about `origin`, it's just a default name git uses.
Git does use `origin` by default when you do things like `git push` or `git pull`. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as "origin":
```
git remote rm origin
git remote add origin [email protected]:subdomain/abbreviation.git
```
or do the above in one command using set-url:
```
git remote set-url origin [email protected]:subdomain/abbreviation.git
```
Then you can simply do `git push` or `git pull` to update, instead of `git push unfuddle master`
|
277,085 |
<p>I'm trying to get the name of the executable of a window that is outside my C# 2.0 application. My app currently gets a window handle (hWnd) using the GetForegroundWindow() call from "user32.dll".</p>
<p>From the digging that I've been able to do, I think I want to use the GetModuleFileNameEx() function (from PSAPI) to obtain the name, but GetModuleFileNameEx() requires a handle to a Process, not a Window. </p>
<p>Is it possible to get a process handle from a window handle? (Do I need to get the thread handle of the window first?)</p>
<p>EDITED the first sentence to make it clearer what I'm trying to do.</p>
<p><strong>UPDATE!</strong> Here's the C# code that I found worked for me. The only caveat is <em>occasionally</em> it returns a file/path where the drive letter is a "?" instead of the actual drive letter (like "C"). -- Haven't figured out why yet.</p>
<pre><code>[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
[DllImport("psapi.dll")]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In] [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
private string GetWindowModuleFileName(IntPtr hWnd)
{
uint processId = 0;
const int nChars = 1024;
StringBuilder filename = new StringBuilder(nChars);
GetWindowThreadProcessId(hWnd, out processId);
IntPtr hProcess = OpenProcess(1040, 0, processId);
GetModuleFileNameEx(hProcess,IntPtr.Zero,filename,nChars);
CloseHandle(hProcess);
return (filename.ToString());
}
</code></pre>
|
[
{
"answer_id": 277095,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>You can call <a href=\"http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx\" rel=\"nofollow noreferrer\">GetWindowThreadProcessId</a> and that will return you the process associated with the window.</p>\n\n<p>From that, you can call <a href=\"http://msdn.microsoft.com/en-us/library/ms684320.aspx\" rel=\"nofollow noreferrer\">OpenProcess</a> to open the process and get the handle to the process.</p>\n"
},
{
"answer_id": 277099,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>What exactly is it that you're trying to do? You can get the process ID of the the process which created a window with <a href=\"http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx\" rel=\"nofollow noreferrer\">GetWindowThreadProcessId()</a>, followed by <a href=\"http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx\" rel=\"nofollow noreferrer\">OpenProcess()</a> to get the process handle. But this seems very kludgy, and I feel like there's a more elegant way to do what you want to do.</p>\n"
},
{
"answer_id": 321343,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Been struggling with the same problem for an hour now, also got the first letter replaced by a <strong>?</strong> by using GetModuleFileNameEx.\nFinaly came up with this solution using the <strong>System.Diagnostics.Process</strong> class.</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\npublic static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);\n\nvoid GetProcessPathFromWindowHandle(IntPtr hwnd)\n{\n uint pid = 0;\n Win32.GetWindowThreadProcessId(hwnd, out pid);\n Process p = Process.GetProcessById((int)pid);\n return p.MainModule.FileName;\n}\n</code></pre>\n"
},
{
"answer_id": 535207,
"author": "Greg Domjan",
"author_id": 37558,
"author_profile": "https://Stackoverflow.com/users/37558",
"pm_score": 2,
"selected": false,
"text": "<p>If you are running on a windows 64 bit platform, you may need to use QueryFullProcessImageName instead. This returns a user style path, compared to GetProcessImageFileName which returns a system style path that would need to be converted using NtQuerySymbolicLinkObject or ZwQuerySymbolicLinkObject.</p>\n\n<p>One mammoth example function - recommend breaking up into re usable bits.</p>\n\n<pre><code>typedef DWORD (__stdcall *PfnQueryFullProcessImageName)(HANDLE hProcess, DWORD dwFlags, LPTSTR lpImageFileName, PDWORD nSize);\ntypedef DWORD (__stdcall *PfnGetModuleFileNameEx)(HANDLE hProcess, HMODULE hModule, LPTSTR lpImageFileName, DWORD nSize);\n\nstd::wstring GetExeName( HWND hWnd ){\n// Convert from Window to Process ID\nDWORD dwProcessID = 0;\n::GetWindowThreadProcessId(hWnd, &dwProcessID);\n\n// Get a handle to the process from the Process ID\nHANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessID);\n\n// Get the process name\nif (NULL != hProcess) {\n TCHAR szEXEName[MAX_PATH*2] = {L'\\0'};\n DWORD nExeName = sizeof(szEXEName)/sizeof(TCHAR);\n\n // the QueryFullProcessImageNameW does not exist on W2K\n HINSTANCE hKernal32dll = LoadLibrary(L\"kernel32.dll\");\n PfnQueryFullProcessImageName pfnQueryFullProcessImageName = NULL;\n if(hKernal32dll != NULL) {\n pfnQueryFullProcessImageName = (PfnQueryFullProcessImageName)GetProcAddress(hKernal32dll, \"QueryFullProcessImageNameW\");\n if (pfnQueryFullProcessImageName != NULL) \n pfnQueryFullProcessImageName(hProcess, 0, szEXEName, &nExeName);\n ::FreeLibrary(hKernal32dll);\n } \n\n // The following was not working from 32 querying of 64 bit processes\n // Use as backup for when function above is not available \n if( pfnQueryFullProcessImageName == NULL ){ \n HINSTANCE hPsapidll = LoadLibrary(L\"Psapi.dll\");\n PfnGetModuleFileNameEx pfnGetModuleFileNameEx = (PfnGetModuleFileNameEx)GetProcAddress(hPsapidll, \"GetModuleFileNameExW\");\n if( pfnGetModuleFileNameEx != NULL ) \n pfnGetModuleFileNameEx(hProcess, NULL, szEXEName, sizeof(szEXEName)/sizeof(TCHAR));\n ::FreeLibrary(hPsapidll);\n }\n\n ::CloseHandle(hProcess);\n\n return( szEXEName );\n} \nreturn std::wstring();\n}\n</code></pre>\n"
},
{
"answer_id": 2942146,
"author": "muh",
"author_id": 354388,
"author_profile": "https://Stackoverflow.com/users/354388",
"pm_score": 0,
"selected": false,
"text": "<p>try this to get the file name of the executable :</p>\n\n<p>C#:</p>\n\n<pre><code>string file = System.Windows.Forms.Application.ExecutablePath;\n</code></pre>\n\n<p>mfg</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21244/"
] |
I'm trying to get the name of the executable of a window that is outside my C# 2.0 application. My app currently gets a window handle (hWnd) using the GetForegroundWindow() call from "user32.dll".
From the digging that I've been able to do, I think I want to use the GetModuleFileNameEx() function (from PSAPI) to obtain the name, but GetModuleFileNameEx() requires a handle to a Process, not a Window.
Is it possible to get a process handle from a window handle? (Do I need to get the thread handle of the window first?)
EDITED the first sentence to make it clearer what I'm trying to do.
**UPDATE!** Here's the C# code that I found worked for me. The only caveat is *occasionally* it returns a file/path where the drive letter is a "?" instead of the actual drive letter (like "C"). -- Haven't figured out why yet.
```
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
[DllImport("psapi.dll")]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In] [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
private string GetWindowModuleFileName(IntPtr hWnd)
{
uint processId = 0;
const int nChars = 1024;
StringBuilder filename = new StringBuilder(nChars);
GetWindowThreadProcessId(hWnd, out processId);
IntPtr hProcess = OpenProcess(1040, 0, processId);
GetModuleFileNameEx(hProcess,IntPtr.Zero,filename,nChars);
CloseHandle(hProcess);
return (filename.ToString());
}
```
|
You can call [GetWindowThreadProcessId](http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx) and that will return you the process associated with the window.
From that, you can call [OpenProcess](http://msdn.microsoft.com/en-us/library/ms684320.aspx) to open the process and get the handle to the process.
|
277,092 |
<p>How can I refer a custom function in xml? Suppose that I have a function written in Java and want it to refer by the xml tag, how is this possible?</p>
<p>Current senario: I am using XACML2.0 which contains xml tags and I want to refer some function in Java that will talk to the backend data, I'm unable to refer a function in xacml. Could you help me please?</p>
|
[
{
"answer_id": 352783,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You should read up on Reflection in Java.</p>\n\n<p>The following example would invoke the method </p>\n\n<p>myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)</p>\n\n<pre><code>Integer[] params = {new Integer(123),new Integer(567)}; \nClass cl=Class.forName(\"stringParsedFromYourXML\"); \nClass[] par=new Class[2]; \npar[0]=Integer.TYPE; \npar[1]=Integer.TYPE; \nMethod mthd=cl.getMethod(\"methodNameAsString\", parameterTypes); \nmthd.invoke(new myObjectThatContainsMethod(), params);\n</code></pre>\n\n<p>hope that helps..</p>\n"
},
{
"answer_id": 3028013,
"author": "Roland Illig",
"author_id": 225757,
"author_profile": "https://Stackoverflow.com/users/225757",
"pm_score": 0,
"selected": false,
"text": "<p>First, you need to choose an implementation of XACML. You should take one that is written in Java, to make things simpler.</p>\n\n<p>Everything else depends on the chosen implementation. The implementation should document how to add custom functions. If it's not documented, ask the authors.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I refer a custom function in xml? Suppose that I have a function written in Java and want it to refer by the xml tag, how is this possible?
Current senario: I am using XACML2.0 which contains xml tags and I want to refer some function in Java that will talk to the backend data, I'm unable to refer a function in xacml. Could you help me please?
|
You should read up on Reflection in Java.
The following example would invoke the method
myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)
```
Integer[] params = {new Integer(123),new Integer(567)};
Class cl=Class.forName("stringParsedFromYourXML");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("methodNameAsString", parameterTypes);
mthd.invoke(new myObjectThatContainsMethod(), params);
```
hope that helps..
|
277,102 |
<p>I'm working on a System Preferences Pane. It opens fine on some computers, but on other Macs (all running 10.5.5), the preference pane refuses to load and simply hangs, spitting the following into the console:</p>
<pre><code>11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: CGWindowContextCreate: failed to create context delegate.
11/9/08 8:38:55 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:55 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
</code></pre>
<p>Any ideas why this is happening?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 352783,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You should read up on Reflection in Java.</p>\n\n<p>The following example would invoke the method </p>\n\n<p>myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)</p>\n\n<pre><code>Integer[] params = {new Integer(123),new Integer(567)}; \nClass cl=Class.forName(\"stringParsedFromYourXML\"); \nClass[] par=new Class[2]; \npar[0]=Integer.TYPE; \npar[1]=Integer.TYPE; \nMethod mthd=cl.getMethod(\"methodNameAsString\", parameterTypes); \nmthd.invoke(new myObjectThatContainsMethod(), params);\n</code></pre>\n\n<p>hope that helps..</p>\n"
},
{
"answer_id": 3028013,
"author": "Roland Illig",
"author_id": 225757,
"author_profile": "https://Stackoverflow.com/users/225757",
"pm_score": 0,
"selected": false,
"text": "<p>First, you need to choose an implementation of XACML. You should take one that is written in Java, to make things simpler.</p>\n\n<p>Everything else depends on the chosen implementation. The implementation should document how to add custom functions. If it's not documented, ask the authors.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4103/"
] |
I'm working on a System Preferences Pane. It opens fine on some computers, but on other Macs (all running 10.5.5), the preference pane refuses to load and simply hangs, spitting the following into the console:
```
11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: CGWindowContextCreate: failed to create context delegate.
11/9/08 8:38:55 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:55 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
```
Any ideas why this is happening?
Thanks.
|
You should read up on Reflection in Java.
The following example would invoke the method
myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)
```
Integer[] params = {new Integer(123),new Integer(567)};
Class cl=Class.forName("stringParsedFromYourXML");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("methodNameAsString", parameterTypes);
mthd.invoke(new myObjectThatContainsMethod(), params);
```
hope that helps..
|
277,149 |
<p>I have an ASP.NET MVC project and I have a single action that accepts GET, POST, and DELETE requests. Each type of request is filtered via attributes on my controllers <code>Action</code> methods.</p>
<pre><code>[ActionName(Constants.AdministrationGraphDashboardAction),
AcceptVerbs(HttpVerbs.Post)]
public ActionResult GraphAdd([ModelBinder(typeof (GraphDescriptorBinder))] GraphDescriptor details);
[ActionName(Constants.AdministrationGraphDashboardAction),
AcceptVerbs(HttpVerbs.Delete)]
public ActionResult GraphDelete([ModelBinder(typeof (RdfUriBinder))] RdfUri graphUri)
</code></pre>
<p>I have my <code>GraphAdd</code> method working very well. What I'm trying to figure out is how I can create an HTML <code><form /></code> or <code><a /></code> (link) that will cause the browser to perform an HTTP Delete request and trigger my GraphDelete method.</p>
<p>If there is a way to do this can someone post some sample HTML and if available the MVC HtmlHelper method I should be using?</p>
|
[
{
"answer_id": 277218,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<p>i don't believe this is possible. the method attribute of form elements in HTML4 & XHTML 1.0 will only accept GET or POST. in addition, standard configs of most webservers will deny DELETE and PUT requests. assuming you have configured your webserver to allow methods like PUT / DELETE (such as WebDav does), you could then create your own HTTP request:</p>\n\n<pre><code>DELETE /resource.html HTTP/1.1\nHost: domain.com\n</code></pre>\n\n<p>and handle it appropriately. however, there's no way to do this via a current HTML form. for interest's sake, there is <a href=\"http://www.whatwg.org/specs/web-forms/current-work/#for-http\" rel=\"noreferrer\">some discussion</a> for DELETE support in HTML5.</p>\n"
},
{
"answer_id": 927494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Using XMLHttpRequest, it's not only the \"best practice\", it's really the only way.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
I have an ASP.NET MVC project and I have a single action that accepts GET, POST, and DELETE requests. Each type of request is filtered via attributes on my controllers `Action` methods.
```
[ActionName(Constants.AdministrationGraphDashboardAction),
AcceptVerbs(HttpVerbs.Post)]
public ActionResult GraphAdd([ModelBinder(typeof (GraphDescriptorBinder))] GraphDescriptor details);
[ActionName(Constants.AdministrationGraphDashboardAction),
AcceptVerbs(HttpVerbs.Delete)]
public ActionResult GraphDelete([ModelBinder(typeof (RdfUriBinder))] RdfUri graphUri)
```
I have my `GraphAdd` method working very well. What I'm trying to figure out is how I can create an HTML `<form />` or `<a />` (link) that will cause the browser to perform an HTTP Delete request and trigger my GraphDelete method.
If there is a way to do this can someone post some sample HTML and if available the MVC HtmlHelper method I should be using?
|
i don't believe this is possible. the method attribute of form elements in HTML4 & XHTML 1.0 will only accept GET or POST. in addition, standard configs of most webservers will deny DELETE and PUT requests. assuming you have configured your webserver to allow methods like PUT / DELETE (such as WebDav does), you could then create your own HTTP request:
```
DELETE /resource.html HTTP/1.1
Host: domain.com
```
and handle it appropriately. however, there's no way to do this via a current HTML form. for interest's sake, there is [some discussion](http://www.whatwg.org/specs/web-forms/current-work/#for-http) for DELETE support in HTML5.
|
277,150 |
<p>How do I define an Extension Method for <code>IEnumerable<T></code> which returns <code>IEnumerable<T></code>?
The goal is to make the Extension Method available for all <code>IEnumerable</code> and <code>IEnumerable<T></code> where <code>T</code> can be an anonymous type.</p>
|
[
{
"answer_id": 277172,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 0,
"selected": false,
"text": "<p>This post may help you to get started:<a href=\"https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772\">How do you write a C# Extension Method for a Generically Typed Class</a>. I'm not sure if it is exactly what you are looking for but it might get you started.</p>\n"
},
{
"answer_id": 277198,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "<p>The easiest way to write any iterator is with an iterator block, for example:</p>\n\n<pre><code>static IEnumerable<T> Where<T>(this IEnumerable<T> data, Func<T, bool> predicate)\n{\n foreach(T value in data)\n {\n if(predicate(value)) yield return value;\n }\n}\n</code></pre>\n\n<p>The key here is the \"<code>yield return</code>\", which turns the method into an iterator block, with the compiler generating an enumerator (<code>IEnumerator<T></code>) that does the same. When called, generic type inference handles the <code>T</code> automatically, so you just need:</p>\n\n<pre><code>int[] data = {1,2,3,4,5};\nvar odd = data.Where(i=>i%2 != 0);\n</code></pre>\n\n<p>The above can be used with anonymous types just fine.</p>\n\n<p>You can, of coure, specify the <code>T</code> if you want (as long as it isn't anonymous):</p>\n\n<pre><code>var odd = data.Where<int>(i=>i%2 != 0);\n</code></pre>\n\n<p>Re <code>IEnumerable</code> (non-generic), well, the simplest approach is for the caller to use <code>.Cast<T>(...)</code> or <code>.OfType<T>(...)</code> to get an <code>IEnumerable<T></code> first. You can pass in <code>this IEnumerable</code> in the above, but the caller will have to specify <code>T</code> themselves, rather than having the compiler infer it. You can't use this with <code>T</code> being an anonymous type, so the moral here is: don't use the non-generic form of <code>IEnumerable</code> with anonymous types.</p>\n\n<p>There are some slightly more complex scenarios where the method signature is such that the compiler can't identify the <code>T</code> (and of course you can't specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler <em>can</em> use with inference (perhaps via a pass-thru method), but you'd need to post actual code to provide an answer here.</p>\n\n<hr>\n\n<p>(updated)</p>\n\n<p>Following discussion, here's a way to leverage <code>Cast<T></code> with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example:</p>\n\n<pre><code>static void Main()\n{\n IEnumerable data = new[] { new { Foo = \"abc\" }, new { Foo = \"def\" }, new { Foo = \"ghi\" } };\n var typed = data.Cast(() => new { Foo = \"never used\" });\n foreach (var item in typed)\n {\n Console.WriteLine(item.Foo);\n }\n}\n\n// note that the template is not used, and we never need to pass one in...\npublic static IEnumerable<T> Cast<T>(this IEnumerable source, Func<T> template)\n{\n return Enumerable.Cast<T>(source);\n}\n</code></pre>\n"
},
{
"answer_id": 277203,
"author": "Howard Pinsley",
"author_id": 7961,
"author_profile": "https://Stackoverflow.com/users/7961",
"pm_score": 3,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace ExtentionTest {\n class Program {\n static void Main(string[] args) {\n\n List<int> BigList = new List<int>() { 1,2,3,4,5,11,12,13,14,15};\n IEnumerable<int> Smalllist = BigList.MyMethod();\n foreach (int v in Smalllist) {\n Console.WriteLine(v);\n }\n }\n\n }\n\n static class EnumExtentions {\n public static IEnumerable<T> MyMethod<T>(this IEnumerable<T> Container) {\n int Count = 1;\n foreach (T Element in Container) {\n if ((Count++ % 2) == 0)\n yield return Element;\n }\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21586/"
] |
How do I define an Extension Method for `IEnumerable<T>` which returns `IEnumerable<T>`?
The goal is to make the Extension Method available for all `IEnumerable` and `IEnumerable<T>` where `T` can be an anonymous type.
|
The easiest way to write any iterator is with an iterator block, for example:
```
static IEnumerable<T> Where<T>(this IEnumerable<T> data, Func<T, bool> predicate)
{
foreach(T value in data)
{
if(predicate(value)) yield return value;
}
}
```
The key here is the "`yield return`", which turns the method into an iterator block, with the compiler generating an enumerator (`IEnumerator<T>`) that does the same. When called, generic type inference handles the `T` automatically, so you just need:
```
int[] data = {1,2,3,4,5};
var odd = data.Where(i=>i%2 != 0);
```
The above can be used with anonymous types just fine.
You can, of coure, specify the `T` if you want (as long as it isn't anonymous):
```
var odd = data.Where<int>(i=>i%2 != 0);
```
Re `IEnumerable` (non-generic), well, the simplest approach is for the caller to use `.Cast<T>(...)` or `.OfType<T>(...)` to get an `IEnumerable<T>` first. You can pass in `this IEnumerable` in the above, but the caller will have to specify `T` themselves, rather than having the compiler infer it. You can't use this with `T` being an anonymous type, so the moral here is: don't use the non-generic form of `IEnumerable` with anonymous types.
There are some slightly more complex scenarios where the method signature is such that the compiler can't identify the `T` (and of course you can't specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler *can* use with inference (perhaps via a pass-thru method), but you'd need to post actual code to provide an answer here.
---
(updated)
Following discussion, here's a way to leverage `Cast<T>` with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example:
```
static void Main()
{
IEnumerable data = new[] { new { Foo = "abc" }, new { Foo = "def" }, new { Foo = "ghi" } };
var typed = data.Cast(() => new { Foo = "never used" });
foreach (var item in typed)
{
Console.WriteLine(item.Foo);
}
}
// note that the template is not used, and we never need to pass one in...
public static IEnumerable<T> Cast<T>(this IEnumerable source, Func<T> template)
{
return Enumerable.Cast<T>(source);
}
```
|
277,187 |
<p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
|
[
{
"answer_id": 277280,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe look at the zip function for parts of the problem:</p>\n\n<pre><code>>>> execfile('so_ques.py')\n[[' '], [' '], ['bananas bunches'], [' '], [' cars'], [' cars'], [' cars'], [' '], [' trucks'], [' trucks'], [' trucks'], [' '], ['trains freight'], [' '], ['planes cargo'], [' '], [' all other'], [' '], [' ']]\n\n>>> zip(long_header, short_header)\n[('', ''), ('', ''), ('bananas', 'bunches'), ('', ''), ('', 'cars'), ('', ''), ('', 'trucks'), ('', ''), ('', 'freight'), ('', ''), ('', 'cargo'), ('', ''), ('trains', 'all other'), ('', ''), ('planes', '')]\n>>> \n</code></pre>\n\n<p><code>enumerate</code> can help avoid some of the complex indexing with counters:</p>\n\n<pre><code>>>> diff_list = []\n>>> for place, header in enumerate(short_header):\n diff_list.append(abs(span_short[place] - span_long[place]))\n\n>>> for place, num in enumerate(diff_list):\n if num:\n new_shortlist.extend(short_header[place] for item in range(num+1))\n else:\n new_shortlist.append(short_header[place])\n\n\n>>> new_shortlist\n['', '', 'bunches', '', 'cars', 'cars', 'cars', '', 'trucks', 'trucks', 'trucks', '',... \n>>> z = zip(new_shortlist, long_header)\n>>> z\n[('', ''), ('', ''), ('bunches', 'bananas'), ('', ''), ('cars', ''), ('cars', ''), ('cars', '')...\n</code></pre>\n\n<p>Also more pythonic naming may add clarity:</p>\n\n<pre><code> for each in range(len(short_header)):\n sum_span_long += span_long[long_header_count]\n sum_span_short += span_short[each]\n span_diff = sum_span_short - sum_span_long\n if not span_diff:\n combined_header.append...\n</code></pre>\n"
},
{
"answer_id": 277390,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a modified version of your algorithm. <em>zip</em> is used to iterate over <strong>short</strong> lengths and headers and a <em>class object</em> is used to count and iterate the <strong>long</strong> items, as well as combine the headers. <em>while</em> is more appropriate for the inner loop.\n(forgive the too short names).</p>\n\n<pre><code>class collector(object):\n def __init__(self, header):\n self.longHeader = header\n self.combinedHeader = []\n self.longHeaderCount = 0\n def combine(self, shortValue):\n self.combinedHeader.append(\n [self.longHeader[self.longHeaderCount]+' '+shortValue] )\n self.longHeaderCount += 1\n return self.longHeaderCount\n\ndef main():\n longHeader = [ \n '','','bananas','','','','','','','','','','trains','','planes','','','','']\n shortHeader = [\n '','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']\n spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]\n spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]\n sumSpanLong=0\n sumSpanShort=0\n\n combiner = collector(longHeader)\n for sLen,sHead in zip(spanShort,shortHeader):\n sumSpanLong += spanLong[combiner.longHeaderCount]\n sumSpanShort += sLen\n while sumSpanShort - sumSpanLong > 0:\n combiner.combine(sHead)\n sumSpanLong += spanLong[combiner.longHeaderCount]\n combiner.combine(sHead)\n\n return combiner.combinedHeader\n</code></pre>\n"
},
{
"answer_id": 277837,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": true,
"text": "<p>You've actually got a lot going on in this example.</p>\n\n<ol>\n<li><p>You've \"over-processed\" the Beautiful Soup Tag objects to make lists. Leave them as Tags.</p></li>\n<li><p>All of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically.</p></li>\n</ol>\n\n<p>Here's a version that should work directly with the Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows.</p>\n\n<pre><code>def merge3( row1, row2 ):\n i1= 0\n i2= 0\n result= []\n while i1 != len(row1) or i2 != len(row2):\n if i1 == len(row1):\n result.append( ' '.join(row1[i1].contents) )\n i2 += 1\n elif i2 == len(row2):\n result.append( ' '.join(row2[i2].contents) )\n i1 += 1\n else:\n if row1[i1]['colspan'] < row2[i2]['colspan']:\n # Fill extra cols from row1\n c1= row1[i1]['colspan']\n while c1 != row2[i2]['colspan']:\n result.append( ' '.join(row2[i2].contents) )\n c1 += 1\n elif row1[i1]['colspan'] > row2[i2]['colspan']:\n # Fill extra cols from row2\n c2= row2[i2]['colspan']\n while row1[i1]['colspan'] != c2:\n result.append( ' '.join(row1[i1].contents) )\n c2 += 1\n else:\n assert row1[i1]['colspan'] == row2[i2]['colspan']\n pass\n txt1= ' '.join(row1[i1].contents)\n txt2= ' '.join(row2[i2].contents)\n result.append( txt1 + \" \" + txt2 )\n i1 += 1\n i2 += 1\n return result\n</code></pre>\n"
},
{
"answer_id": 280181,
"author": "PyNEwbie",
"author_id": 30105,
"author_profile": "https://Stackoverflow.com/users/30105",
"pm_score": 0,
"selected": false,
"text": "<p>I guess I am going to answer my own question but I did receive a lot of help. Thanks for all of the help. I made S.LOTT's answer work after a few small corrections. (They may be so small as to not be visible (inside joke)). So now the question is why is this more Pythonic? I think I see that it is less denser / works with the raw inputs instead of derivations / I cannot judge if it is easier to read ---> though it is easy to read</p>\n<h2>S.LOTT's Answer Corrected</h2>\n<pre><code>row1=headerCells[0]\nrow2=headerCells[1]\n\ni1= 0\ni2= 0\nresult= []\nwhile i1 != len(row1) or i2 != len(row2):\n if i1 == len(row1):\n result.append( ' '.join(row1[i1]) )\n i2 += 1\n elif i2 == len(row2):\n result.append( ' '.join(row2[i2]) )\n i1 += 1\n else:\n if int(row1[i1].get("colspan","1")) < int(row2[i2].get("colspan","1")):\n c1= int(row1[i1].get("colspan","1"))\n while c1 != int(row2[i2].get("colspan","1")): \n txt1= ' '.join(row1[i1]) # needed to add when working adjust opposing case\n txt2= ' '.join(row2[i2]) # needed to add when working adjust opposing case\n result.append( txt1 + " " + txt2 ) # needed to add when working adjust opposing case\n print 'stayed in middle', 'i1=',i1,'i2=',i2, ' c1=',c1\n c1 += 1\n i1 += 1 # Is this the problem it\n \n elif int(row1[i1].get("colspan","1"))> int(row2[i2].get("colspan","1")):\n # Fill extra cols from row2 Make same adjustment as above\n c2= int(row2[i2].get("colspan","1"))\n while int(row1[i1].get("colspan","1")) != c2:\n result.append( ' '.join(row1[i1]) )\n c2 += 1\n i2 += 1\n else:\n assert int(row1[i1].get("colspan","1")) == int(row2[i2].get("colspan","1"))\n pass\n \n \n txt1= ' '.join(row1[i1])\n txt2= ' '.join(row2[i2])\n result.append( txt1 + " " + txt2 )\n print 'went to bottom', 'i1=',i1,'i2=',i2\n i1 += 1\n i2 += 1\nprint result\n</code></pre>\n"
},
{
"answer_id": 283026,
"author": "PyNEwbie",
"author_id": 30105,
"author_profile": "https://Stackoverflow.com/users/30105",
"pm_score": 0,
"selected": false,
"text": "<p>Well I have an answer now. I was thinking through this and decided that I needed to use parts of every answer. I still need to figure out if I want a class or a function. But I have the algorithm that I think is probably more Pythonic than any of the others. But, it borrows heavily from the answers that some very generous people provided. I appreciate those a lot because I have learned quite a bit.</p>\n\n<p>To save the time of having to make test cases I am going to paste the the complete code I have been banging away with in IDLE and follow that with an HTML sample file. Other than making a decision about class/function (and I need to think about how I am using this code in my program) I would be happy to see any improvements that make the code more Pythonic.</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\n\noriginal=file(r\"C:\\testheaders.htm\").read()\n\nsoupOriginal=BeautifulSoup(original)\nall_Rows=soupOriginal.findAll('tr')\n\n\nheader_Rows=[]\nfor each in range(len(all_Rows)):\n header_Rows.append(all_Rows[each])\n\n\nheader_Cells=[]\nfor each in header_Rows:\n header_Cells.append(each.findAll('td'))\n\ntemp_Header_Row=[]\nheader=[]\nfor row in range(len(header_Cells)):\n for column in range(len(header_Cells[row])):\n x=int(header_Cells[row][column].get(\"colspan\",\"1\"))\n if x==1:\n temp_Header_Row.append( ' '.join(header_Cells[row][column]) )\n\n else:\n for item in range(x):\n\n temp_Header_Row.append( ''.join(header_Cells[row][column]) )\n\n header.append(temp_Header_Row)\ntemp_Header_Row=[]\ncombined_Header=zip(*header)\n\nfor each in combined_Header:\n print each\n</code></pre>\n\n<p>Okay test file contents are below Sorry I tried to attach these but couldn't make it happen:</p>\n\n<pre><code> <TABLE style=\"font-size: 10pt\" cellspacing=\"0\" border=\"0\" cellpadding=\"0\" width=\"100%\">\n <TR valign=\"bottom\">\n <TD width=\"40%\">&nbsp;</TD>\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">FOODS WE LIKE</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">&nbsp;</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"CENTER\" colspan=\"6\">SILLY STUFF</TD>\n\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">OTHER THAN</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"CENTER\" colspan=\"6\">FAVORITE PEOPLE</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">MONTY PYTHON</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">CHERRYPY</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">APPLE PIE</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">MOTHERS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">FATHERS</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD nowrap align=\"left\">Name</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">SHOWS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">PROGRAMS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">BANANAS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">PERFUME</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">TOOLS</TD>\n <TD>&nbsp;</TD>\n </TR>\n </TABLE>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30105/"
] |
I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic.
Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.
```
longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
```
|
You've actually got a lot going on in this example.
1. You've "over-processed" the Beautiful Soup Tag objects to make lists. Leave them as Tags.
2. All of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically.
Here's a version that should work directly with the Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows.
```
def merge3( row1, row2 ):
i1= 0
i2= 0
result= []
while i1 != len(row1) or i2 != len(row2):
if i1 == len(row1):
result.append( ' '.join(row1[i1].contents) )
i2 += 1
elif i2 == len(row2):
result.append( ' '.join(row2[i2].contents) )
i1 += 1
else:
if row1[i1]['colspan'] < row2[i2]['colspan']:
# Fill extra cols from row1
c1= row1[i1]['colspan']
while c1 != row2[i2]['colspan']:
result.append( ' '.join(row2[i2].contents) )
c1 += 1
elif row1[i1]['colspan'] > row2[i2]['colspan']:
# Fill extra cols from row2
c2= row2[i2]['colspan']
while row1[i1]['colspan'] != c2:
result.append( ' '.join(row1[i1].contents) )
c2 += 1
else:
assert row1[i1]['colspan'] == row2[i2]['colspan']
pass
txt1= ' '.join(row1[i1].contents)
txt2= ' '.join(row2[i2].contents)
result.append( txt1 + " " + txt2 )
i1 += 1
i2 += 1
return result
```
|
277,197 |
<p>The site I'm working on is using a Databound asp:Menu control. When sending 1 menu item it renders HTML that is absolutely correct in Firefox (and IE), but really messed up code in Safari and Chrome. Below is the code that was sent to each browser. I've tested it a few browsers, and they are all pretty similarly rendered, so I am only posting the two variations on the rendering source. </p>
<p><strong>My question is: How do I get ASP.NET to send the same html and javascript to Chrome and Safari as it does to Firefox and IE?</strong></p>
<pre><code><!-- This is how the menu control is defined -->
<asp:Menu ID="menu" runat="server" BackColor="#cccccc"
DynamicHorizontalOffset="2" Font-Names="Verdana" StaticSubMenuIndent="10px" StaticDisplayLevels="1"
CssClass="left_menuTxt1" Font-Bold="true" ForeColor="#0066CC">
<DataBindings>
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text"
ToolTipField="ToolTip" />
</DataBindings>
<StaticSelectedStyle BackColor="#0066CC" HorizontalPadding="5px" VerticalPadding="2px"
Font-Names="Verdama" CssClass="left_menuTxt1" Font-Bold="true" />
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="8px" />
<DynamicMenuStyle BackColor="#fbfbfb" BorderColor="#989595" BorderStyle="Inset" BorderWidth="1"
Width="80px" VerticalPadding="1" />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" Font-Name="Verdama"
ForeColor="#c6c4c4" CssClass="left_menuTxt1" Font-Bold="true" />
<DynamicSelectedStyle BackColor="#cccccc" HorizontalPadding="5px" VerticalPadding="2px"
Font-Names="Verdama" CssClass="left_menuTxt1" Font-Bold="true" />
</asp:Menu>
<!-- From Safari View Page Source (Chrome source very similar) -->
<span title="Order" class="ctl00_leftNav_menu_4">
<a class="ctl00_leftNav_menu_1 ctl00_leftNav_menu_3"
href="javascript:__doPostBack('ctl00$leftNav$menu','oMy Order')">
My Order
<img src="/WWW/WebResource.axd?d=glUTEfEv7p9OrdeaMxkMzhqz2JugrMr8aE43O2XGHAA1&amp;t=633590571537099818"
alt="Expand My Order"
align="absmiddle"
style="border-width:0px;" /></a></span><br />
<!-- From Firefox View Page Source (IE View page similar) -->
<table>
<tr onmouseover="Menu_HoverStatic(this)"
onmouseout="Menu_Unhover(this)"
onkeyup="Menu_Key(event)"
title="Order"
id="ctl00_leftNav_menun0">
<td>
<table class="ctl00_leftNav_menu_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space:nowrap;width:100%;">
<a class="ctl00_leftNav_menu_1 ctl00_leftNav_menu_3"
href="../Order/OrderList.aspx">
My Order
</a>
</td>
<td style="width:0;">
<img src="/WWW/WebResource.axd?d=glUTEfEv7p9OrdeaMxkMzhqz2JugrMr8aE43O2XGHAA1&amp;t=633590571537099818"
alt="Expand My Order" style="border-style:none;vertical-align:middle;" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</code></pre>
<p>Update: My solution post is correct.. but i can't mark my own as correct... so if anyone wants to copy it so I can close this. :)</p>
|
[
{
"answer_id": 277231,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 5,
"selected": true,
"text": "<p>I found this solution from a comment on <a href=\"http://weblogs.asp.net/dannychen/archive/2005/11/21/using-device-filters-and-making-menu-work-with-safari.aspx\" rel=\"noreferrer\">weblogs.asp.net</a>.\nIt might be a hack, but it does work.</p>\n\n<p>This cross browser compatibility struggle is getting upsetting. </p>\n\n<pre><code> if (Request.UserAgent.IndexOf(\"AppleWebKit\") > 0)\n {\n\n Request.Browser.Adapters.Clear();\n\n }\n</code></pre>\n\n<p>If anyone has a better solution that's not so much a hack, I would be grateful if you posted it. And from my extensive web searches, it looks like I'm not alone with this problem with the menu control, so some good references would help out others in the same situation. </p>\n"
},
{
"answer_id": 277977,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 3,
"selected": false,
"text": "<p>I've had problems with the asp:menu control and webkit as well. Plus it's hard to style exactly the way I want. My recommendation is to use the CSS Friendly Control Adapters:</p>\n\n<ul>\n<li><a href=\"http://www.asp.net/cssadapters/\" rel=\"nofollow noreferrer\">http://www.asp.net/cssadapters/</a></li>\n<li><a href=\"http://www.asp.net/CSSAdapters/Menu.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/CSSAdapters/Menu.aspx</a></li>\n</ul>\n\n<p>This converts the menu's table into much more modern and SEO-friendly markup. Your menu will look more like this:</p>\n\n<pre><code><ul class=\"AspNet-Menu\">\n <li class=\"Leaf Selected\">\n <a href=\"Orders.aspx\" class=\"Link Selected\">Orders</a></li>\n <li class=\"ALeaf\">\n <a href=\"MyOrders.aspx\" class=\"Link\">My Orders</a></li>\n</ul>\n</code></pre>\n\n<p>In my testing, the markup is the same in all browsers.</p>\n"
},
{
"answer_id": 425989,
"author": "Seth Reno",
"author_id": 50225,
"author_profile": "https://Stackoverflow.com/users/50225",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the easiest way to fix this issue for both chrome and safari if you have multiple web apps:</p>\n\n<p><strong>Create a file named safari.browser in \"%SystemRoot%\\Microsoft.NET\\Framework[version]\\CONFIG\\Browsers\" that contains the following:</strong></p>\n\n<pre><code><browsers>\n <browser refID=\"Safari1Plus\">\n <controlAdapters>\n <adapter controlType=\"System.Web.UI.WebControls.Menu\"\n adapterType=\"\" />\n </controlAdapters>\n </browser>\n</browsers>\n</code></pre>\n\n<p>This will tell asp.net not to use an adapter when rendering the menu control for safari.\nSafari1Plus is defined at the end of the mozilla.browser file in the same directory. This works for chrome as well because they both use webkit which is how asp.net identifies Safari1Plus.</p>\n\n<p><strong>Next run %SystemRoot%\\Microsoft.NET\\Framework[version]\\aspnet_regbrowsers -i</strong></p>\n\n<p>this will compile all the browser files into an assembly and add it to the GAC.</p>\n\n<p>now the asp.net menu will render correctly in safari and chrome.</p>\n\n<p>Alternatively you can add the file the the App_Browsers directory in each of your web apps.</p>\n"
},
{
"answer_id": 894559,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Adding <code>ClientTarget=\"uplevel\"</code> to the page directive like so makes Safari work:</p>\n\n<pre><code><%@ Page ClientTarget=\"uplevel\" ... %>\n</code></pre>\n"
},
{
"answer_id": 3025301,
"author": "jball",
"author_id": 223391,
"author_profile": "https://Stackoverflow.com/users/223391",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://geekswithblogs.net/bullpit/archive/2009/07/08/aspmenu-rendering-problems-in-ie8-safari-and-chrome.aspx\" rel=\"nofollow noreferrer\">Mayank Sharma</a> found a solution that works with master pages, rather than editing individual pages. All pages that use the master page are fixed seamlessly. It's still a hack, but you do what you have to. Here's a barebones example master page code behind.</p>\n\n<pre><code>using System;\nusing System.Web.UI;\n\n/// <summary>\n/// Summary description for ExampleMasterPage\n/// </summary>\npublic class ExampleMasterPage : MasterPage\n{ \n public ExampleMasterPage() { }\n\n protected override void AddedControl(Control control, int index)\n {\n if (Request.ServerVariables[\"http_user_agent\"]\n .IndexOf(\"Safari\", StringComparison.CurrentCultureIgnoreCase) != -1)\n {\n this.Page.ClientTarget = \"uplevel\";\n }\n base.AddedControl(control, index);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3142083,
"author": "romac",
"author_id": 379150,
"author_profile": "https://Stackoverflow.com/users/379150",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the @Mayank Sharma / @jball C# version converted to VB.NET. Thanks for the fix guys, been bugging me for months. My problem was every browser on MAC and PC worked except IE8 and Chrome. But then Chrome, much as I like it, often fails to run Google Docs - work that out!!!</p>\n\n<pre><code>Protected Overrides Sub AddedControl(ByVal control As Control, ByVal index As Integer)\n If Request.ServerVariables(\"http_user_agent\").IndexOf(\"fake_user_agent\", StringComparison.CurrentCultureIgnoreCase) <> -1 Then\n Me.Page.ClientTarget = \"uplevel\"\n End If\n MyBase.AddedControl(control, index)\n End Sub\n</code></pre>\n\n<p>You'll note that I had to check for \"fake_user_agent\", not \"Safari\".</p>\n"
},
{
"answer_id": 4900577,
"author": "user603480",
"author_id": 603480,
"author_profile": "https://Stackoverflow.com/users/603480",
"pm_score": 3,
"selected": false,
"text": "<p>I just wanted to submit an alternate option. This works for ASP.NET 3.5.</p>\n\n<ul>\n<li>Add the \"App_Browsers\" ASP.NET folder to your project</li>\n<li>Create a Browser file within this folder</li>\n<li><p>In the browser file, add the following code between the <code><browsers></code> tag:</p>\n\n<p><code><browser id=\"Chrome\" parentID=\"Safari1Plus\"></code><br>\n <code><controlAdapters></code><br>\n <code><adapter controlType=\"System.Web.UI.WebControls.Menu\" adapterType=\"\" /></code><br>\n <code></controlAdapters></code><br>\n <code></browser></code> </p></li>\n</ul>\n\n<p>That should properly render the menu control in Chrome/Safari.</p>\n"
},
{
"answer_id": 5912507,
"author": "albert",
"author_id": 741896,
"author_profile": "https://Stackoverflow.com/users/741896",
"pm_score": 0,
"selected": false,
"text": "<p>The issue with Chrome and Safari not rendering the menu control properly is due to the navigation skiplink image box being rendered by Chrome and Safari.</p>\n\n<p>If you do a css <code>display: none;</code> on the image for the skiplink then the menu control positions itself like it should.</p>\n\n<p>I've tested this on a simple 1 level menu and not nested menus.</p>\n\n<p><a href=\"http://www.s-t-f-u.com/2011/05/05/asp-net-menu-control-positioning-in-safari-google-chrome/\" rel=\"nofollow\">http://www.s-t-f-u.com/2011/05/05/asp-net-menu-control-positioning-in-safari-google-chrome/</a></p>\n"
},
{
"answer_id": 7512117,
"author": "colin",
"author_id": 958680,
"author_profile": "https://Stackoverflow.com/users/958680",
"pm_score": 2,
"selected": false,
"text": "<p>Works like magic!</p>\n\n<pre><code> If Request.ServerVariables(\"http_user_agent\").IndexOf(\"Safari\", StringComparison.CurrentCultureIgnoreCase) <> -1 Or Request.UserAgent.Contains(\"AppleWebKit\") Then\n Request.Browser.Adapters.Clear()\n Page.ClientTarget = \"uplevel\"\n End If\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
The site I'm working on is using a Databound asp:Menu control. When sending 1 menu item it renders HTML that is absolutely correct in Firefox (and IE), but really messed up code in Safari and Chrome. Below is the code that was sent to each browser. I've tested it a few browsers, and they are all pretty similarly rendered, so I am only posting the two variations on the rendering source.
**My question is: How do I get ASP.NET to send the same html and javascript to Chrome and Safari as it does to Firefox and IE?**
```
<!-- This is how the menu control is defined -->
<asp:Menu ID="menu" runat="server" BackColor="#cccccc"
DynamicHorizontalOffset="2" Font-Names="Verdana" StaticSubMenuIndent="10px" StaticDisplayLevels="1"
CssClass="left_menuTxt1" Font-Bold="true" ForeColor="#0066CC">
<DataBindings>
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text"
ToolTipField="ToolTip" />
</DataBindings>
<StaticSelectedStyle BackColor="#0066CC" HorizontalPadding="5px" VerticalPadding="2px"
Font-Names="Verdama" CssClass="left_menuTxt1" Font-Bold="true" />
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="8px" />
<DynamicMenuStyle BackColor="#fbfbfb" BorderColor="#989595" BorderStyle="Inset" BorderWidth="1"
Width="80px" VerticalPadding="1" />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" Font-Name="Verdama"
ForeColor="#c6c4c4" CssClass="left_menuTxt1" Font-Bold="true" />
<DynamicSelectedStyle BackColor="#cccccc" HorizontalPadding="5px" VerticalPadding="2px"
Font-Names="Verdama" CssClass="left_menuTxt1" Font-Bold="true" />
</asp:Menu>
<!-- From Safari View Page Source (Chrome source very similar) -->
<span title="Order" class="ctl00_leftNav_menu_4">
<a class="ctl00_leftNav_menu_1 ctl00_leftNav_menu_3"
href="javascript:__doPostBack('ctl00$leftNav$menu','oMy Order')">
My Order
<img src="/WWW/WebResource.axd?d=glUTEfEv7p9OrdeaMxkMzhqz2JugrMr8aE43O2XGHAA1&t=633590571537099818"
alt="Expand My Order"
align="absmiddle"
style="border-width:0px;" /></a></span><br />
<!-- From Firefox View Page Source (IE View page similar) -->
<table>
<tr onmouseover="Menu_HoverStatic(this)"
onmouseout="Menu_Unhover(this)"
onkeyup="Menu_Key(event)"
title="Order"
id="ctl00_leftNav_menun0">
<td>
<table class="ctl00_leftNav_menu_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space:nowrap;width:100%;">
<a class="ctl00_leftNav_menu_1 ctl00_leftNav_menu_3"
href="../Order/OrderList.aspx">
My Order
</a>
</td>
<td style="width:0;">
<img src="/WWW/WebResource.axd?d=glUTEfEv7p9OrdeaMxkMzhqz2JugrMr8aE43O2XGHAA1&t=633590571537099818"
alt="Expand My Order" style="border-style:none;vertical-align:middle;" />
</td>
</tr>
</table>
</td>
</tr>
</table>
```
Update: My solution post is correct.. but i can't mark my own as correct... so if anyone wants to copy it so I can close this. :)
|
I found this solution from a comment on [weblogs.asp.net](http://weblogs.asp.net/dannychen/archive/2005/11/21/using-device-filters-and-making-menu-work-with-safari.aspx).
It might be a hack, but it does work.
This cross browser compatibility struggle is getting upsetting.
```
if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
{
Request.Browser.Adapters.Clear();
}
```
If anyone has a better solution that's not so much a hack, I would be grateful if you posted it. And from my extensive web searches, it looks like I'm not alone with this problem with the menu control, so some good references would help out others in the same situation.
|
277,207 |
<p>I am a bit confused why this code compiles. I leave out the "necessary" <code>#include <OpenGL/gl.h></code> and still the program can compile. How is this possible when my program is calling functions from the GL library, without including them.</p>
<pre><code>int main(int argc, char** argv)
{
glClearColor(1.0,1.0,1.0,1.0);
return 0;
}
</code></pre>
<p>I use this compilation command:</p>
<pre><code> gcc -framework GLUT -framework OpenGL test.c
</code></pre>
<p>I was under the assumption that adding -framework just specifies to the linker where the library is, but I thought I still need the headers?</p>
|
[
{
"answer_id": 277233,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": false,
"text": "<p>glClearColor isn't a macro so you don't <em>need</em> the headers to define it. If you add warnings:</p>\n\n<pre><code>gcc -o test -Wall -W test.c -framework GLUT -framework OpenGL\n</code></pre>\n\n<p>Then you'll get a warning about the implicit declaration of glClearColor. You also won't be able to use any macros as the compiler will give you an error that they are undefined. Since the glClearColor symbol gets properly resolved by the linker, you never get an error.</p>\n\n<p>It also occurs to me that you might have been wondering this because you thought you were compiling for C++. The example you gave actually compiles C code where it is not an error to fail to declare function prototypes. If you meant to compile this as C++ code, you would need the following command line:</p>\n\n<p>g++ -o test test.cpp -framework OpenGL</p>\n\n<p>In that case you most certainly would get an error for not including gl.h and your code would fail to compile. When executing GCC from the command line, g++ is the C++ compiler while gcc is the general C compiler.</p>\n"
},
{
"answer_id": 277239,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "<p>In C (prior to C99), you don't have to declare functions in order to use them. The compiler will assume the function takes the promoted parameter types you pass to it, and assume the function returns an <code>int</code>. This, however can be quite problematic, and behavior is undefined if the function doesn't. Let's look at this:</p>\n\n<pre><code>/* file1.c */\nvoid foo(char a, char b) {\n /* doing something ... */\n}\n\n/* main.c */\nint main(void) {\n char a = 'a', b = 'b';\n /* char variables are promoted to int \n before being passed */\n foo(b, a); \n}\n</code></pre>\n\n<p>Because the types are being promoted (<code>char -> int, float -> double</code>) if there is no declaration of the function at the time you call it, the arguments could not be passed at the right places in memory anymore.\nAccessing b can yield to a curious value of the parameter. As a side node, the same problem occurs when you pass arguments to <code>vararg functions</code> like <code>prinft</code>, or functions having no prototype (like <code>void f()</code>, where there is no information about the parameters types and count). This is the reason that you always have to access variadic arguments with <code>va_arg</code> using their promoted type. GCC will warn you if you don't.</p>\n\n<p>Always include the proper header files, so you don't run into this problems.</p>\n\n<p><strong>Edit:</strong> thanks to Chris for pointing out that <code>char literals</code> (like <code>'a'</code>) are always of type <code>int</code> in C</p>\n"
},
{
"answer_id": 277356,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 0,
"selected": false,
"text": "<p>This actually relates to the classic C&R hello world snippet:<br>\n<a href=\"http://en.wikipedia.org/wiki/Hello_world#History\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Hello_world#History</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28486/"
] |
I am a bit confused why this code compiles. I leave out the "necessary" `#include <OpenGL/gl.h>` and still the program can compile. How is this possible when my program is calling functions from the GL library, without including them.
```
int main(int argc, char** argv)
{
glClearColor(1.0,1.0,1.0,1.0);
return 0;
}
```
I use this compilation command:
```
gcc -framework GLUT -framework OpenGL test.c
```
I was under the assumption that adding -framework just specifies to the linker where the library is, but I thought I still need the headers?
|
In C (prior to C99), you don't have to declare functions in order to use them. The compiler will assume the function takes the promoted parameter types you pass to it, and assume the function returns an `int`. This, however can be quite problematic, and behavior is undefined if the function doesn't. Let's look at this:
```
/* file1.c */
void foo(char a, char b) {
/* doing something ... */
}
/* main.c */
int main(void) {
char a = 'a', b = 'b';
/* char variables are promoted to int
before being passed */
foo(b, a);
}
```
Because the types are being promoted (`char -> int, float -> double`) if there is no declaration of the function at the time you call it, the arguments could not be passed at the right places in memory anymore.
Accessing b can yield to a curious value of the parameter. As a side node, the same problem occurs when you pass arguments to `vararg functions` like `prinft`, or functions having no prototype (like `void f()`, where there is no information about the parameters types and count). This is the reason that you always have to access variadic arguments with `va_arg` using their promoted type. GCC will warn you if you don't.
Always include the proper header files, so you don't run into this problems.
**Edit:** thanks to Chris for pointing out that `char literals` (like `'a'`) are always of type `int` in C
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.