qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
347,250 | <p>I need to generate a tone that I can manipulate frequency and wave. The overall goal is to create a basic piano. Does anyone know how I can achieve this?</p>
<p>My development platform is the iPhone 2.x</p>
| [
{
"answer_id": 349037,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "sin #include <cmath>\n\ntypedef double Sample;\ntypedef double Time;\n\nclass MonoNote {\nprotected:\n Time start, duration;\n virtual void internalRender(double now, Sample *mono) = 0;\npublic:\n MonoNote(Time s, Time d) : start(s), duration(d) {}\n virtual ~MonoNote() {}\n void render(double now, Sample *mono) {\n if (start <= now && now < start + duration) {\n internalRender(now, mono);\n }\n }\n};\n\nclass MonoSinNote : public MonoNote {\n Time freq;\n Sample amplitude;\nprotected:\n void internalRender(double now, Sample *mono) {\n const double v = sin(2*M_PI*(now - start) * freq);\n *mono += amplitude*v;\n }\npublic:\n MonoSinNote(Time s, Time d, Time f, Sample a) : MonoNote(s, d), freq(f), amplitude(a) {}\n ~MonoSinNote() {}\n};\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44048/"
] |
347,254 | <p>Is there a way to log(/var/log) commands executed by users in the Unix shell?</p>
| [
{
"answer_id": 347272,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 0,
"selected": false,
"text": "script"
},
{
"answer_id": 347442,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "accton /var/account/pacct accton Start comp_t ct = ?;\nlong val = (ct & 0x1fff) << (((ct >> 13) & 0x7) * 3);\n sysconf (_SC_CLK_TCK)"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15474/"
] |
347,274 | <p>I have written a <a href="http://osirisdevelopment.com/BatteryBar" rel="nofollow noreferrer">toolbar</a> that runs on the taskbar. Unfortunately, after it is installed, the user has to enable it manually. Is there a way to tell explorer to open (or close) a given toolbar?</p>
<p>I would like for the installer, NSIS, to turn on the toolbar when the installation is complete (I realize that a plugin would be necessary).</p>
<p>I also want to know if it's possible to automatically enable a toolbar for all users, for example in a corporate environment where multiple users would share a PC.</p>
| [
{
"answer_id": 818055,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 4,
"selected": true,
"text": "[ComImport]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n[Guid(\"4CF504B0-DE96-11D0-8B3F-00A0C911E8E5\")]\npublic interface IBandSite\n{\n [PreserveSig]\n uint AddBand([In, MarshalAs(UnmanagedType.IUnknown)] Object pUnkSite);\n [PreserveSig]\n void RemoveBand(uint dwBandID);\n}\n\n\nprivate uint AddDeskbandToTray(Guid Deskband)\n{\n Guid IUnknown = new Guid(\"{00000000-0000-0000-C000-000000000046}\");\n Guid ITrayBand = new Guid(\"{F60AD0A0-E5E1-45cb-B51A-E15B9F8B2934}\"); \n Type TrayBandSiteService = Type.GetTypeFromCLSID(ITrayBand, true);\n IBandSite BandSite = Activator.CreateInstance(TrayBandSiteService) as IBandSite;\n object DeskbandObject = CoCreateInstance(Deskband, null, CLSCTX.CLSCTX_INPROC_SERVER, IUnknown);\n return BandSite.AddBand(DeskbandObject);\n}\n Guid address_toolbar_guid = new Guid(\"{01E04581-4EEE-11D0-BFE9-00AA005B4383}\");\nuint band_id = AddDeskbandToTray(address_toolbar_guid);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5982/"
] |
347,281 | <p>After trying to setup my site for Google Webmaster Tools I found that my Custom ASP.NET 404 page was not returning the 404 status code. It displayed the correct custom page and told the browser that everything is OK. This is consider a soft 404 or false 404. Google doesn't like this. So I found many articles on the issue but the solution I want didn't seem to work.</p>
<p>The solution I want to work is adding the following two lines to the code behind Page_Load method of the custom 404 page.</p>
<pre><code>Response.Status = "404 Not Found";
Response.StatusCode = 404;
</code></pre>
<p>This doesn't work. The page still returns 200 OK. I found however that if I hard code the following code into the design code it will work properly.</p>
<pre><code><asp:Content ID="ContentMain" ContentPlaceHolderID="ContentPlaceHolderMaster" runat="server">
<%
Response.Status = "404 Not Found";
Response.StatusCode = 404;
%>
... Much more code ...
</asp:content>
</code></pre>
<p>The page is using a master page. And I am configuring custom error pages in my web.config. I would really rather use the code behind option but I can't seem to make it work without putting a the hack inline code in the design / layout.</p>
| [
{
"answer_id": 347304,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 7,
"selected": true,
"text": "protected override void Render(HtmlTextWriter writer)\n{\n base.Render(writer);\n Response.StatusCode = 404;\n}\n <customErrors mode=\"On\">\n <error statusCode=\"404\" redirect=\"404.aspx\"/>\n</customErrors>\n public partial class _04 : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n Response.StatusCode = 404;\n }\n}\n HTTP/1.1 404 Not Found\nServer: Microsoft-IIS/5.1\nDate: Sun, 07 Dec 2008 06:04:13 GMT\nX-Powered-By: ASP.NET\nX-AspNet-Version: 2.0.50727\nCache-Control: private\nContent-Type: text/html; charset=utf-8\nContent-Length: 533\n HTTP/1.1 404 Not Found\nDate: Sun, 07 Dec 2008 06:21:20 GMT\n"
},
{
"answer_id": 348499,
"author": "Bobby Cannon",
"author_id": 43976,
"author_profile": "https://Stackoverflow.com/users/43976",
"pm_score": 3,
"selected": false,
"text": "<%\n// This code is required for host that do special 404 handling...\nResponse.Status = \"404 Not Found\";\nResponse.StatusCode = 404;\n%>\n"
},
{
"answer_id": 3097894,
"author": "gary",
"author_id": 57325,
"author_profile": "https://Stackoverflow.com/users/57325",
"pm_score": 5,
"selected": false,
"text": "Response.TrySkipIisCustomErrors = true;\n"
},
{
"answer_id": 3765382,
"author": "Jason Goemaat",
"author_id": 369792,
"author_profile": "https://Stackoverflow.com/users/369792",
"pm_score": 4,
"selected": false,
"text": "Response.Status = \"404 Not Found\";\nResponse.StatusCode = 404;\nResponse.End();\nreturn;\n"
},
{
"answer_id": 9989387,
"author": "Nick D",
"author_id": 1309862,
"author_profile": "https://Stackoverflow.com/users/1309862",
"pm_score": 4,
"selected": false,
"text": "<system.webServer>\n <httpErrors existingResponse=\"Replace\">\n <remove statusCode=\"500\" subStatusCode=\"-1\" />\n <remove statusCode=\"404\" subStatusCode=\"-1\" />\n <error statusCode=\"404\" prefixLanguageFilePath=\"\" path=\"404.htm\" responseMode=\"File\" />\n <error statusCode=\"500\" prefixLanguageFilePath=\"\" path=\"500.htm\" responseMode=\"File\" />\n </httpErrors>\n</system.webServer>\n"
},
{
"answer_id": 10250838,
"author": "letsgetsilly",
"author_id": 249348,
"author_profile": "https://Stackoverflow.com/users/249348",
"pm_score": 1,
"selected": false,
"text": "<customErrors mode=\"RemoteOnly\" defaultRedirect=\"~/error.htm\" />\n protected void Application_Error(object sender, EventArgs e)\n {\n HandleError();\n }\n\n private void HandleError()\n {\n var exception = Server.GetLastError();\n if (exception == null) return;\n\n var baseException = exception.GetBaseException();\n\n bool errorHandled = _applicationErrorHandler.HandleError(baseException);\n if (!errorHandled) return;\n\n\n var lastError = Server.GetLastError();\n if (null != lastError && HttpContext.Current.IsCustomErrorEnabled)\n {\n Elmah.ErrorSignal.FromCurrentContext().Raise(lastError.GetBaseException());\n Server.ClearError();\n }\n }\n public bool HandleError(Exception exception)\n {\n if (exception == null) return false;\n\n var baseException = exception.GetBaseException();\n\n Elmah.ErrorSignal.FromCurrentContext().Raise(baseException);\n\n if (!HttpContext.Current.IsCustomErrorEnabled) return false;\n\n try\n {\n\n var behavior = _responseBehaviorFactory.GetBehavior(exception);\n if (behavior != null)\n {\n behavior.ExecuteRedirect();\n return true;\n }\n }\n catch (Exception ex)\n {\n Elmah.ErrorSignal.FromCurrentContext().Raise(ex);\n }\n return false;\n }\n public ResponseBehaviorFactory()\n {\n _behaviors = new Dictionary<Type, Func<IResponseBehavior>>\n {\n {typeof(StoreException), () => new Found302StoreResponseBehavior()},\n {typeof(HttpUnhandledException), () => new HttpExceptionResponseBehavior()},\n {typeof(HttpException), () => new HttpExceptionResponseBehavior()},\n {typeof(Exception), () => new Found302DefaultResponseBehavior()}\n };\n }\n\n public IResponseBehavior GetBehavior(Exception exception)\n { \n if (exception == null) throw new ArgumentNullException(\"exception\");\n\n Func<IResponseBehavior> behavior;\n bool tryGetValue = _behaviors.TryGetValue(exception.GetType(), out behavior);\n\n //default value here:\n if (!tryGetValue)\n _behaviors.TryGetValue(typeof(Exception), out behavior);\n\n if (behavior == null)\n Elmah.ErrorSignal.FromCurrentContext().Raise(\n new Exception(\n \"Danger! No Behavior defined for this Exception, therefore the user might have received a yellow screen of death!\",\n exception));\n return behavior();\n }\n"
},
{
"answer_id": 58131107,
"author": "Rami Zebian",
"author_id": 6859050,
"author_profile": "https://Stackoverflow.com/users/6859050",
"pm_score": 0,
"selected": false,
"text": " Response.TrySkipIisCustomErrors = True\n Response.Status = \"404 Not Found\"\n Response.AddHeader(\"Location\", \"{your-path-to-your-404-page}\")\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43976/"
] |
347,286 | <p>So I'm having a path issue on OS X Leopard. It seems OS X is adding other paths that I'm not stating and it's messing with my path priority. I only have a <code>.bash_login</code> file, I don't have a <code>.bashrc</code> or a .profile file. My <code>.bash_login</code> file is as such:</p>
<pre><code>export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"
</code></pre>
<p>When I run export this is the path it returns:</p>
<pre><code>PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/local/bin:/usr/local/git/bin"
</code></pre>
<p>Any ideas on what could be putting /usr/bin in there and how I could get <code>/usr/local/bin</code> to be a higher priority.</p>
<p>I'm tagging this for Rails too because that's what I'm working on right now... it seems the Mac built-in Ruby, Rails, and Gems are taking priority over the one I have installed at <code>/usr/local/bin</code>, figured maybe you fellow Rubyists could help too.</p>
| [
{
"answer_id": 347292,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 5,
"selected": true,
"text": "/etc/paths.d/\n/etc/manpaths.d\n path_helper /etc/profile path_helper path_helper /etc/paths.d/ /etc/manpaths.d/ path_helper /etc/paths /etc/manpaths /etc/paths $ cat /etc/paths\n/usr/bin\n/bin\n/usr/sbin\n/sbin\n/usr/local/bin\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43043/"
] |
347,294 | <p>So I'm trying to take a bilinear interpolation algorithm for resizing images and add in alpha values as well. I'm using Actionscript 3 to do this, but I don't really think the language is relevant.</p>
<p>The code I have below actually works really well, but edges around "erased" regions seem to get darker. Is there an easy way for it to not include what I can only assume is black (0x00000000) when it's finding its average?</p>
<p>Code:</p>
<pre><code>x_ratio = theX - x;
y_ratio = theY - y;
x_opposite = 1 - x_ratio;
y_opposite = 1 - y_ratio;
a = getPixel32(x, y);
be =getPixel32(x + 1, y);
c = getPixel32(x, y + 1);
d = getPixel32(x + 1, y + 1);
alph = (t(a) * x_opposite + t(be) * x_ratio) * y_opposite + (t(c) * x_opposite + t(d) * x_ratio) * y_ratio;
red = (r(a) * x_opposite + r(be) * x_ratio) * y_opposite + (r(c) * x_opposite + r(d) * x_ratio) * y_ratio;
green = (g(a) * x_opposite + g(be) * x_ratio) * y_opposite + (g(c) * x_opposite + g(d) * x_ratio) * y_ratio;
blue = (b(a) * x_opposite + b(be) * x_ratio) * y_opposite + (b(c) * x_opposite + b(d) * x_ratio) * y_ratio;
</code></pre>
<p>Image of the effect: <a href="http://beta.shinyhammer.com/images/site/eraser_pixelborders.jpg" rel="nofollow noreferrer">http://beta.shinyhammer.com/images/site/eraser_pixelborders.jpg</a></p>
<p><strong>Posting code of solution!</strong></p>
<pre><code>a = getPixel32(x, y);
be =getPixel32(x + 1, y);
c = getPixel32(x, y + 1);
d = getPixel32(x + 1, y + 1);
asum = (t(a) + t(be) + t(c) + t(d)) / 4;
alph = (t(a) * x_opposite + t(be) * x_ratio) * y_opposite + (t(c) * x_opposite + t(d) * x_ratio) * y_ratio;
red = ((r(a) * t(a) * x_opposite + r(be) * t(be) * x_ratio) * y_opposite + (r(c) * t(c) * x_opposite + r(d) * t(d) * x_ratio) * y_ratio);
red = (asum > 0) ? red / asum : 0;
green = ((g(a) * t(a) * x_opposite + g(be) * t(be) * x_ratio) * y_opposite + (g(c) * t(c) * x_opposite + g(d) * t(d) * x_ratio) * y_ratio);
green = (asum > 0) ? green / asum : 0;
blue = ((b(a) * t(a) * x_opposite + b(be) * t(be) * x_ratio) * y_opposite + (b(c) * t(c) * x_opposite + b(d) * t(d) * x_ratio) * y_ratio);
blue = (asum > 0) ? blue / asum : 0;
</code></pre>
| [
{
"answer_id": 347446,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "d = Kf + (1-K)b\n d = f + (1-K)b\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10680/"
] |
347,298 | <p>I have a c++ program that is using the openMPI library to pass messages between different processors. It is a parallel program that uses a genetic algorithm to get a good solution for the traveling salesperson problem. I am trying to set up the MPI environment on my two dual processor computers at my house so that I can run it.
When I first created this program a year ago, I was able to run it fine on a cluster that was not set up by me. The problem that I am having now is that whenever I run it, all the processes are saying that they are of rank 0. If I have 3 nodes, instead of them being nodes 1, 2, and 3, they are all node 0. If anyone knows what is going on, I would sure appreciate some help. Thanks.</p>
| [
{
"answer_id": 348912,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 1,
"selected": false,
"text": "MPI_Init(&argc, &argv);\nMPI_Comm_size(MPI_COMM_WORLD, &size);\nMPI_Comm_rank(MPI_COMM_WORLD, &rank);\nprintf(\"I am process %d of %d.\\n\", rank, size);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,306 | <p>Whenever we have to update the database; we delete the values from the table first and then add the latest values. This ensures that everything is updated correctly.</p>
<p>This adds little bit overhead to the system but we haven't faced any performance issues because of this.</p>
<p>Is this always the best thing to do?</p>
| [
{
"answer_id": 347313,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "BEGIN TRAN T1\n\n-- This update is part of T1\nUPDATE Table1 SET Col1='New Value' WHERE Col2 = @Id;\n\n-- Time to commit your changes. \n-- If for any reason something fails, \n-- everything gets rolled back\nCOMMIT TRAN T1\n"
},
{
"answer_id": 347317,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 0,
"selected": false,
"text": "delete insert insert update replace"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38997/"
] |
347,311 | <p>need help in Fortran...</p>
<p>This is the main loop of the program..</p>
<pre><code>do iStep=0,nStep
write(7,*)iStep
!* Compute new temperature using FTCS scheme.
do i=1,N
if( istep==0) then !only for t=0
tt_new(i)=250
write(7,*)tt_new(i)
else
if(i==1) then
tt_new(i)=2*coeff*(tt(i+1)+35.494)-0.036*tt(i)
write(7,*)tt(i)
else
if(i==N) then
tt_new(i)=2*coeff*(tt(i-1)+35.494)-0.036*tt(i)
write(7,*)tt(i)
else
tt_new(i) = coeff*(tt(i+1) + tt(i-1)+33.333)+(1 - 2*coeff)*tt(i)
write (7,*) tt_new(i)
end if
end if
end if
end do
do i=1,N
tt(i) = tt_new(i) ! Reset temperature to new values
enddo
end do
</code></pre>
<p>this is the output....</p>
<pre><code>0
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
2.5000000E+02
1
2.5000000E+02 <--
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.6666650E+02
2.5000000E+02 <--
</code></pre>
<p>As you can see...the programm doesn't calculate the values for the first and last node...Can you tell me why???</p>
| [
{
"answer_id": 347331,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "IF ELSE if( istep==0) then !only for t=0\n tt_new(i)=250\n write(7,*)tt_new(i)\nelse if(i==1) then\n tt_new(i)=2*coeff*(tt(i+1)+35.494)-0.036*tt(i)\n write(7,*)tt(i)\nelse if(i==N) then\n tt_new(i)=2*coeff*(tt(i-1)+35.494)-0.036*tt(i)\n write(7,*)tt(i)\nelse \n tt_new(i) = coeff*(tt(i+1) + tt(i-1)+33.333)+(1 - 2*coeff)*tt(i)\n write (7,*) tt_new(i)\n\nend if\nend if //redundant\nend if //redundant\n END IF IF ELSE IF ELSE"
},
{
"answer_id": 347344,
"author": "Tim Whitcomb",
"author_id": 24895,
"author_profile": "https://Stackoverflow.com/users/24895",
"pm_score": 3,
"selected": false,
"text": "i=1 i=N tt(i) tt_new(i) if if (iStep == 0) then\n ! Perform actions for time 0\nelse\n ! Perform actions for time > 0\n if (i == 1) then\n ! Perform actions for first endpoint\n else if (i == N) then\n ! Perform actions for last endpoint\n else\n ! Perform actions for midsection\n end if\nend if\n"
},
{
"answer_id": 347350,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "if (istep==0) then !only for t=0\n tt_new(i)=250\nelse if (i==1) then\n tt_new(i) = 2*coeff*(tt(i+1)+35.494)-0.036*tt(i)\nelse if (i==N) then\n tt_new(i) = 2*coeff*(tt(i-1)+35.494)-0.036*tt(i)\nelse \n tt_new(i) = coeff*(tt(i+1) + tt(i-1)+33.333)+(1 - 2*coeff)*tt(i)\nend if\nwrite(7,*)tt_new(i)\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,316 | <p>how do you encode words using the huffman code such as NEED</p>
| [
{
"answer_id": 347321,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 1,
"selected": false,
"text": "<DIV 01 <DIV"
},
{
"answer_id": 347341,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "0 xxxxxxxx\n| +- token code for N\n+--- ESCAPE\n ESCAPE:00\nEND-STREAM:01\nN:1\n 0 xxxxxxxx 0 yyyyyyyy\n +- token code for E\n ESCAPE:00\nEND-STREAM:01\nN:10\nE:11\n 0 xxxxxxxx 0 yyyyyyyy 11 0 zzzzzzzz\n | +- token code for D\n +------ second E\n ESCAPE:00\nEND-STREAM:011\nN:010\nE:11\nD:10\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,325 | <p>I need to get a file into memory in my app from a secured web location. I have the URL of the file to capture, but can't seem to get the security issue resolved. Here's the code from the <a href="http://groovy.codehaus.org/Simple+file+download+from+URL" rel="nofollow noreferrer">Cookbook samples page</a>:</p>
<pre><code>def download(address)
{
def file = new FileOutputStream(address.tokenize("/")[-1])
def out = new BufferedOutputStream(file)
out << new URL(address).openStream()
out.close()
}
</code></pre>
<p>and here's my "memory" version of the same function which should return a byte array of the file's contents:</p>
<pre><code>def downloadIntoMem(address)
{ // btw, how frickin powerful is Groovy to do this in 3 lines (or less)
def out = new ByteArrayOutputStream()
out << new URL(address).openStream()
out.toByteArray()
}
</code></pre>
<p>When I try this against an unsecured URL (pick any image file you can find on the net), it works just fine. However, if I pick a URL that requires a user/password, no go. </p>
<p>All right, done a bit more work on this. It seems that the Authenticator method <strong>does</strong> work, but in a round-about way. The first time I access the URL, I get a 302 response with a location to a login server. If I access that location with an Authenticator set, then I get another 302 with a Cookie and the location set back to the original URL. If I then access the original, the download occurs correctly.</p>
<p>So, I have to mimic a browser a bit, but eventually it all works.</p>
<p>Making this a community wiki, so others can add other methods.</p>
<p>Thanks!</p>
| [
{
"answer_id": 347397,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 2,
"selected": false,
"text": "def address = \"http://admin:sekr1t@myhost.com\"\ndef url = new URL(address)\nassert \"admin:sekr1t\" == url.userInfo\n"
},
{
"answer_id": 5137476,
"author": "Wanderson Santos",
"author_id": 128857,
"author_profile": "https://Stackoverflow.com/users/128857",
"pm_score": 4,
"selected": true,
"text": "new File(localPath).withOutputStream { out ->\n def url = new URL(remoteUrl).openConnection()\n def remoteAuth = \"Basic \" + \"${user}:${passwd}\".bytes.encodeBase64()\n url.setRequestProperty(\"Authorization\", remoteAuth);\n out << url.inputStream\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824/"
] |
347,338 | <p>Is releasing objects on a programs exit/close needed?</p>
<p>In other words, let us say for the sake of argument, you have a button that closes your application, but right before you close you display an image, and then you close the application.</p>
<p>Do you need to release that image view before you close the application? Will the memory automatically be freed when the program exits, or if you don't release it will the memory stay somehow "active"?</p>
<p>I understand that you "should" release it, my question is about the technical side of it, and what happens behind the scenes.</p>
| [
{
"answer_id": 347349,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 6,
"selected": true,
"text": "valgrind sbrk sbrk malloc sbrk fork"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26728/"
] |
347,358 | <p>Why does this code:</p>
<pre><code>class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
</code></pre>
<p>Result in these errors:</p>
<pre>
main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note: B::B(const B&)
</pre>
<p>Shouldn't B inherit A's constructor?</p>
<p>(this is using gcc)</p>
| [
{
"answer_id": 347361,
"author": "grepsedawk",
"author_id": 14388,
"author_profile": "https://Stackoverflow.com/users/14388",
"pm_score": 4,
"selected": false,
"text": "B(int x) : A(x) { }\n B() : A(5) { }\n"
},
{
"answer_id": 347362,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 7,
"selected": false,
"text": "class A\n{\npublic: \n explicit A(int x) {}\n};\n\nclass B: public A\n{\npublic:\n explicit B(int x) : A(x) { }\n};\n"
},
{
"answer_id": 434784,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 10,
"selected": true,
"text": "using class A\n{\n public: \n explicit A(int x) {}\n};\n\nclass B: public A\n{\n using A::A;\n};\n using std::vector;\n \ntemplate<class T>\nclass my_vector : public vector<T> {\n public:\n using vector<T>::vector; ///Takes all vector's constructors\n /* */\n};\n"
},
{
"answer_id": 21901397,
"author": "Iqbal Haider",
"author_id": 3240185,
"author_profile": "https://Stackoverflow.com/users/3240185",
"pm_score": 2,
"selected": false,
"text": "class A\n{\n public: \n explicit A(int x) {}\n};\n\nclass B: public A\n{\n public:\n\n B(int a):A(a){\n }\n};\n\nmain()\n{\n B *b = new B(5);\n delete b;\n}\n"
},
{
"answer_id": 23567834,
"author": "nenchev",
"author_id": 1322108,
"author_profile": "https://Stackoverflow.com/users/1322108",
"pm_score": 4,
"selected": false,
"text": "struct B1 {\n B1(int) { }\n};\n\nstruct D1 : B1 {\n using B1::B1; // implicitly declares D1(int)\n int x;\n};\n\nvoid test()\n{\n D1 d(6); // Oops: d.x is not initialized\n D1 e; // error: D1 has no default constructor\n}\n int x = 77;\n int x;\n"
},
{
"answer_id": 26807911,
"author": "Pradu",
"author_id": 3753277,
"author_profile": "https://Stackoverflow.com/users/3753277",
"pm_score": 3,
"selected": false,
"text": "template <class... T> Derived(T... t) : Base(t...) {}\n"
},
{
"answer_id": 68139563,
"author": "Sarath Govind",
"author_id": 12284466,
"author_profile": "https://Stackoverflow.com/users/12284466",
"pm_score": 0,
"selected": false,
"text": "class A\n{\n public: \n explicit A(int x) {}\n};\n\nclass B: public A\n{\n B(int x):A(x);\n};\n\nint main(void)\n{\n B *b = new B(5);\n delete b;\n}\n"
},
{
"answer_id": 68180595,
"author": "Eugen Bondarev",
"author_id": 15918345,
"author_profile": "https://Stackoverflow.com/users/15918345",
"pm_score": 2,
"selected": false,
"text": "class Derived : public Parent {\npublic:\n template <typename... Args>\n Derived(Args&&... args) : Parent(std::forward<Args>(args)...) \n {\n\n }\n};\n #define PARENT_CONSTRUCTOR(DERIVED, PARENT) \\\ntemplate<typename... Args> \\\nDERIVED(Args&&... args) : PARENT(std::forward<Args>(args)...)\n\nclass Derived : public Parent\n{\npublic:\n PARENT_CONSTRUCTOR(Derived, Parent)\n {\n }\n};\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43496/"
] |
347,365 | <p>I am using Delphi TApplication.OnException Event to catch unhandled exceptions</p>
<p>This works well but does not give sufficient information about where the exception happened
i.e. ‘Catastrophic failure’ </p>
<p>How can I find out which procedure made the error happened?</p>
<pre><code>procedure TFrmMain.FormCreate(Sender: TObject);
begin
Application.OnException := MyExceptionHandler;
end;
procedure TFrmMain.MyExceptionHandler(Sender : TObject; E : Exception );
begin
LogException (E.Message);
Application.ShowException( E );
end;
</code></pre>
| [
{
"answer_id": 347381,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 3,
"selected": false,
"text": "jcl-install-dir\\experts\\debug\\dialog %DELHPIDIR%\\bin\\delphi32.dro"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] |
347,372 | <p>I don't know how to save object with where clause. I need it to prevent saving object with range of dates overlapping on others.</p>
<pre><code>public class TaskEvent
{
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
}
</code></pre>
<p>I want to check overlaping in criteria within saving operation but I don't know how.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 2087341,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 2,
"selected": true,
"text": "session.CreateQuery(\"UPDATE TaskEvent SET ... WHERE ID = :ID and ...\")\n.SetInt32(\"ID\", ID)\n//.SetDateTime(\"\", )\n//.SetDateTime(\"\", )\n.ExecuteUpdate();\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3644960/"
] |
347,377 | <p>Both Session.Clear() and Session.Abandon() get rid of session variables. As I understand it, Abandon() ends the current session, and causes a new session to be created thus causing the End and Start events to fire.</p>
<p>It seems preferable to call Abandon() in most cases, such as logging a user out. Are there scenarios where I'd use Clear() instead? Is there much of a performance difference?</p>
| [
{
"answer_id": 347382,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 8,
"selected": true,
"text": "Session.Abandon() Session.Clear() Session.Abandon() Session.Clear()"
},
{
"answer_id": 347640,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 0,
"selected": false,
"text": "public static void RemoveEverythingButUserInfo()\n{\n foreach (String o in HttpContext.Current.Session.Keys)\n {\n if (o != \"UserInfoIDontWantToAskForAgain\")\n keys.Add(o);\n }\n}\n"
},
{
"answer_id": 10598559,
"author": "Kasim Shafiq",
"author_id": 1395870,
"author_profile": "https://Stackoverflow.com/users/1395870",
"pm_score": 2,
"selected": false,
"text": "Session.Abandon Session.Clear"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] |
347,396 | <p>I'm using the Accessibility API to detect when a certain application opens windows, closes windows, when the windows are moved or resized, or made main and/or focused. However the client app seems to move a window to front without an Accessibility API notification being
fired.</p>
<p>How can my application detect when another application brings a window to front, without making it key?</p>
<p>I'm hoping to find a solution that works on OS X 10.4 and 10.5</p>
<p>More info:
I'm using these statements at the moment. They work fine when the user manually selects a window to bring it to front. But it doens't work when the app itself is bringing the window to the front.</p>
<pre><code>AXObserverAddNotification(observer, element, kAXMainWindowChangedNotification, 0);
AXObserverAddNotification(observer, element, kAXFocusedWindowChangedNotification, 0);
</code></pre>
| [
{
"answer_id": 624866,
"author": "Nick Haddad",
"author_id": 2813,
"author_profile": "https://Stackoverflow.com/users/2813",
"pm_score": 3,
"selected": false,
"text": "@interface CurrentAppData : NSObject {\n NSString* _title;\n AXUIElementRef _systemWide;\n AXUIElementRef _app;\n AXUIElementRef _window;\n}\n -(void) updateCurrentApplication {\n // get the currently active application \n _app = (AXUIElementRef)[CurrentAppData\n valueOfExistingAttribute:kAXFocusedApplicationAttribute \n ofUIElement:_systemWide];\n\n // Get the window that has focus for this application\n _window = (AXUIElementRef)[CurrentAppData \n valueOfExistingAttribute:kAXFocusedWindowAttribute \n ofUIElement:_app];\n\n NSString* appName = [CurrentAppData descriptionOfValue:_window\n beingVerbose:TRUE]; \n\n [self setTitle:appName];\n}\n // -------------------------------------------------------------------------------\n// valueOfExistingAttribute:attribute:element\n//\n// Given a uiElement and its attribute, return the value of an accessibility\n// object's attribute.\n// -------------------------------------------------------------------------------\n+ (id)valueOfExistingAttribute:(CFStringRef)attribute ofUIElement:(AXUIElementRef)element\n{\n id result = nil;\n NSArray *attrNames;\n\n if (AXUIElementCopyAttributeNames(element, (CFArrayRef *)&attrNames) == kAXErrorSuccess) \n {\n if ( [attrNames indexOfObject:(NSString *)attribute] != NSNotFound\n &&\n AXUIElementCopyAttributeValue(element, attribute, (CFTypeRef *)&result) == kAXErrorSuccess\n ) \n {\n [result autorelease];\n }\n [attrNames release];\n }\n return result;\n}\n"
},
{
"answer_id": 624958,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 3,
"selected": false,
"text": "kAXApplicationActivatedNotification kAXApplicationDeactivatedNotification"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
] |
347,404 | <p>I am currently doing IE-hacks on a website I'm working on:
<a href="http://www.timkjaerlange.com/wip/co2penhagen/" rel="nofollow noreferrer">http://www.timkjaerlange.com/wip/co2penhagen/</a></p>
<p>I got a problem with this unordered list. IE seems to add extra top-margin for every li-element, making my navigation look like a flight of stairs:
<a href="http://dl.getdropbox.com/u/228089/ie-prob.jpg" rel="nofollow noreferrer">http://dl.getdropbox.com/u/228089/ie-prob.jpg</a></p>
<p>I'm using conditional comments to target IE. I tried:</p>
<pre><code>ul#mainnav li { top-margin: 0;}
</code></pre>
<p>But that doesn't do anything. I wish there was a Firebug-style plugin for IE, that would make it easier to sort out problems like these.</p>
<p>Any ideas regarding what could be causing this problem?</p>
| [
{
"answer_id": 347424,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 2,
"selected": false,
"text": "ul#mainnav li { top-margin: 0;}\n ul#mainnav li { margin-top: 0;}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24218/"
] |
347,439 | <p>I have a mouseenter and mouseleave event for a Panel control that changes the backcolor when the mouse enters and goes back to white when it leaves.</p>
<p>I have Label control within this panel as well but when the mouse enters the Label control, the mouseleave event for the panel fires.</p>
<p>This makes sense but how do I keep the backcolor of the Panel the same when the mouse is in its area without the other controls inside affecting it?</p>
| [
{
"answer_id": 347461,
"author": "ng5000",
"author_id": 36860,
"author_profile": "https://Stackoverflow.com/users/36860",
"pm_score": 0,
"selected": false,
"text": " private void panel1_ParentChanged(object sender, EventArgs e)\n {\n Panel thisPanel = sender as Panel;\n\n if(thisPanel != null && thisPanel.Parent != null)\n {\n thisPanel.Parent.MouseEnter += delegate(object senderObj, EventArgs eArgs) { thisPanel.BackColor = SystemColors.Control; };\n }\n }\n"
},
{
"answer_id": 354448,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 4,
"selected": true,
"text": "private void panel1_MouseLeave(object sender, EventArgs e)\n{\n if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null)\n {\n panel1.BackColor = Color.Gray;\n }\n}\n private void panel1_MouseLeave(object sender, EventArgs e)\n{\n Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size);\n if (!screenBounds.Contains(MousePosition))\n {\n panel1.BackColor = Color.Gray;\n }\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
347,441 | <p>I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:</p>
<pre><code>void erase(std::vector<int>& myNumbers_in, int number_in)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
std::vector<int>::iterator endIter = myNumbers_in.end();
for(; iter != endIter; ++iter)
{
if(*iter == number_in)
{
myNumbers_in.erase(iter);
}
}
}
int main(int argc, char* argv[])
{
std::vector<int> myNmbers;
for(int i = 0; i < 2; ++i)
{
myNmbers.push_back(i);
myNmbers.push_back(i);
}
erase(myNmbers, 1);
return 0;
}
</code></pre>
<p>This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector?</p>
| [
{
"answer_id": 347445,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 6,
"selected": false,
"text": "void erase(std::vector<int>& myNumbers_in, int number_in)\n{\n std::vector<int>::iterator iter = myNumbers_in.begin();\n while (iter != myNumbers_in.end())\n {\n if (*iter == number_in)\n {\n iter = myNumbers_in.erase(iter);\n }\n else\n {\n ++iter;\n }\n }\n\n}\n struct Eraser\n{\n Eraser(int number_in) : number_in(number_in) {}\n int number_in;\n bool operator()(int i) const\n {\n return i == number_in;\n }\n};\n\nstd::vector<int> myNumbers;\nmyNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());\n std::vector<int> myNumbers;\nmyNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());\n std::vector<int> myNumbers;\nmyNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());\n std::vector<int> myNumbers;\nstd::erase_if(myNumbers, Eraser(number_in)); // or use lambda\n std::vector<int> myNumbers;\nstd::erase(myNumbers, number_in);\n"
},
{
"answer_id": 347478,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 9,
"selected": true,
"text": "std::vector<int>& vec = myNumbers; // use shorter name\nvec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());\n remove number_in vector erase"
},
{
"answer_id": 347500,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 4,
"selected": false,
"text": "void erase(std::vector<int>& v, int num)\n{\n size_t j = 0;\n for (size_t i = 0; i < v.size(); ++i) {\n if (v[i] != num) v[j++] = v[i];\n }\n // trim vector to new size\n v.resize(j);\n}\n erase #include <algorithm>\n\nvoid erase(std::vector<int>& v, int num) {\n vector<int>::iterator it = remove(v.begin(), v.end(), num);\n v.erase(it, v.end());\n}\n"
},
{
"answer_id": 70660787,
"author": "Eduard Rostomyan",
"author_id": 1856429,
"author_profile": "https://Stackoverflow.com/users/1856429",
"pm_score": 2,
"selected": false,
"text": "std::vector<int> nums;\n...\nstd::erase(nums, targetNumber);\n std::vector<int> nums;\n...\nstd::erase_if(nums, [](int x) { return x % 2 == 0; }); \n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39742/"
] |
347,449 | <p>I'll be using the <a href="http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=4004" rel="nofollow noreferrer">AdventureWorks Database</a> to illustrate my problem.</p>
<p>I need to show for a particular customer a list of OrderDate with the most Orders.</p>
<p>My intial attempt was as follows:</p>
<pre><code>SELECT CustomerID, OrderDate, COUNT(1) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate
ORDER BY Cnt DESC
</code></pre>
<p>This will get us the following result:</p>
<pre><code>CustomerID OrderDate Cnt
----------- ---------- ----
11300 2003-11-22 00:00:00.000 2
11300 2004-01-28 00:00:00.000 2
11300 2004-02-18 00:00:00.000 2
11300 2004-02-08 00:00:00.000 2
11300 2004-02-15 00:00:00.000 1
11300 2004-03-11 00:00:00.000 1
11300 2004-03-24 00:00:00.000 1
11300 2004-03-30 00:00:00.000 1
11300 2004-04-28 00:00:00.000 1
11300 2004-05-03 00:00:00.000 1
11300 2004-05-17 00:00:00.000 1
11300 2004-06-18 00:00:00.000 1
...
</code></pre>
<p>Not exactly what I wanted, as the result should only show all records where Cnt = 2, like so:</p>
<pre><code>CustomerID OrderDate Cnt
----------- ---------- ----
11300 2003-11-22 00:00:00.000 2
11300 2004-01-28 00:00:00.000 2
11300 2004-02-18 00:00:00.000 2
11300 2004-02-08 00:00:00.000 2
</code></pre>
<p>I'm stuck because I can't wrap my mind around two problems:</p>
<p>1) A customer might have more than one OrderDate with the same Cnt value. This means I can't do something like TOP 1 to get the desired result.<br>
2) Because the number of Orders for each customer may be different, I cannot use the following SQL statement:</p>
<pre><code>SELECT CustomerID, OrderDate, COUNT(1) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate HAVING COUNT(1) > 1
ORDER BY Cnt DESC
</code></pre>
<p>This will work for getting the right result for this customer, but will definitely be wrong if the next customer has only one Order for a particular day.</p>
<p>So, either the query is impossible in this situation, or I am approaching the query in the wrong way. Any ideas on this problem is appreciated. </p>
<p>Also, since this will be a query in a stored procedure, any ideas on solving this in T-SQL will be acceptable.</p>
<p>UPDATE: Thanks to <a href="https://stackoverflow.com/questions/347449/sql-statement-help-select-list-of-customerid-orderdate-with-the-most-records-in#347460">Mehrdad</a>, I've been introduced to <a href="http://msdn.microsoft.com/en-us/library/ms190766(SQL.90).aspx" rel="nofollow noreferrer">Common Table Expressions</a>, and Life is Good®. :) </p>
| [
{
"answer_id": 347456,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 1 WITH TIES CustomerID, OrderDate, COUNT(*) Cnt\n...\nORDER BY COUNT(*) DESC\n"
},
{
"answer_id": 347460,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 3,
"selected": true,
"text": "TOP n WITH TIES SELECT TOP 1 WITH TIES CustomerID, OrderDate, COUNT(*) Cnt\nFROM Sales.SalesOrderHeader\nWHERE CustomerID = 11300\nGROUP BY CustomerID, OrderDate\nORDER BY Cnt DESC\n WITH MyTable AS (SELECT CustomerID, OrderDate, COUNT(*) Cnt\n FROM Sales.SalesOrderHeader\n WHERE CustomerID = 11300\n GROUP BY CustomerID, OrderDate)\nSELECT CustomerID, OrderDate, Cnt\nFROM MyTable\nWHERE Cnt = (SELECT MAX(Cnt) FROM MyTable);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582/"
] |
347,463 | <p>I made a code that translate strings to match each word from the array 0ne to the array two and its showing the right results. But how to let the compiler take the number in the string and print it out as it is, ummmm see the code i wrote</p>
<hr>
<pre><code>class Program
{
public static string[] E = { "i", "go", "school", "to", "at" };
public static string[] A = { "Je", "vais", "ecole", "a", "a" };
public static string Translate(string s)
{
string str = "";
Regex Expression = new Regex(@"[a-zA-Z]+");
MatchCollection M = Expression.Matches(s);
foreach (Match x in M)
str = str + " " + TranslateWord(x.ToString());
return str;
}
public static string TranslateWord(string s)
{
for (int i = 0; i < E.Length; i++)
if (s.ToLower() == E[i].ToLower())
return A[i];
return "Undefined";
}
</code></pre>
<hr>
<p>here I want to enter the the whole string and the code should translate it with the number, now i know how to do the word (by spliting them and translate) but what about the numbers)</p>
<pre><code> static void Main(string[] args)
{
string str = "I go to school at 8";
Console.WriteLine(Translate(str));
}
</code></pre>
<p>how to continue ?!</p>
| [
{
"answer_id": 347466,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 3,
"selected": true,
"text": "[a-zA-Z0-9]+ String.Split"
},
{
"answer_id": 347582,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 0,
"selected": false,
"text": "public static void process (String s) {\n String [] tokens = s.split(\"\\\\s+\");\n for (String token : tokens) {\n if (token.matches(\"[A-Za-z]+\")) {\n System.out.println(\" word: '\" + token + \"'\");\n } else if (token.matches(\"[0-9]+\")) {\n System.out.println(\"number: '\" + token + \"'\");\n } else {\n System.out.println(\" mixed: '\" + token + \"'\");\n }\n }\n}\n process(\"My 23 dogs have 496 fleas.\");\n word: 'My'\nnumber: '23'\n word: 'dogs'\n word: 'have'\nnumber: '496'\n mixed: 'fleas.'\n"
},
{
"answer_id": 349763,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 1,
"selected": false,
"text": "\\w+\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,472 | <p>I'm building a website in ASP.Net, using MVC, and need to list a set of results. Both of the following work as I want them to but I'm wondering which is faster, cleaner and/or better - or if another option entirely would be more appropriate?</p>
<p>Note: <code>ViewData.Model</code> is of type <code>IEnumerable<Thing></code> and I need to display more attributes than <code>Name</code> - I've cropped the code for this example.</p>
<hr>
<pre><code><% foreach (var thing in ViewData.Model)
{ %>
<p><%= thing.Name %></p>
<% }; %>
</code></pre>
<hr>
<pre><code><% rptThings.DataSource = ViewData.Model;
rptThings.DataBind(); %>
<asp:Repeater ID="rptThings" runat="server">
<ItemTemplate>
<p><%# DataBinder.Eval(Container.DataItem, "Name") %></p>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<hr>
| [
{
"answer_id": 347474,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 4,
"selected": true,
"text": "foreach Repeater foreach Repeater foreach"
},
{
"answer_id": 347495,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 4,
"selected": false,
"text": "foreach asp:xxx event delegates asp:xxx mastpage / content control foreach <% .. %> foreach"
},
{
"answer_id": 347691,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p each=\"var item in ViewData.Model\">${item.Name}</p>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40079/"
] |
347,497 | <p>I am writing a web-framework for Python, of which the goal is to be as "small" as possible (currently under 100 lines of code).. You can see the current code <a href="http://github.com/dbr/pyerweb/tree/master" rel="nofollow noreferrer">on github</a></p>
<p>Basically it's written to be as simple to use as possible. An example "Hello World" like site:</p>
<pre><code>from pyerweb import GET, runner
@GET("/")
def index():
return "<strong>This</strong> would be the output HTML for the URL / "
@GET("/view/([0-9]+?)$")
def view_something(id):
return "Viewing id %s" % (id) # URL /view/123 would output "Viewing id 123"
runner(url = "/", # url would be from a web server, in actual use
output_helper = "html_tidy" # run returned HTML though "HTML tidy"
</code></pre>
<p>Basically you have a function that returns HTML, and the GET decorator maps this to a URL.</p>
<p>When <code>runner()</code> is called, each decorated function is checked, if the URL regex matches the request URL, the function is run, and the output is sent to the browser.</p>
<p>Now, the problem - outputting headers. Currently for development I've just put a line before the <code>runner()</code> call which does <code>print Content-type:text/html\n</code> - this is obviously a bit limiting..</p>
<p>My first ideas was to have the functions return a dict, something like..</p>
<pre><code>@GET("/")
def index():
return {
"html": "<html><body>...</body></html>",
"headers": {"Location":"http://google.com"}
}
</code></pre>
<p>I really don't like this - having to return a dict with a specifically named key isn't nearly as nice as just returning a string..</p>
<p>I could check if the returned data is a dict, if so use <code>returned_data['html']</code> as the output, if it's a string, there is no custom headers to be sent... but this means to go from no headers (which would be the case a huge majority of the time) to headers, you'd have to change the return function from <code>return my_html</code> to <code>return {'html':my_html}</code> which isn't very elegant either..</p>
<p>After writing this, I discovered "Sinatra" - a similar-in-use Ruby library, and looked at how it dealt with headers:</p>
<pre><code>get "/" do
content_type 'text/css', :charset => 'utf-8'
end
</code></pre>
<p>This seems like it could be nice enough in Python:</p>
<pre><code>@GET("/")
def index():
header("location", "http://google.com")
</code></pre>
<p>To implement this, I was considering changing how the functions are executed - instead of simply using the return value, I would change <code>sys.stdout</code> to a StringIO, so you could do..</p>
<pre><code>def index():
print "<html>"
print "<head><title>Something</title></head>"
print "<body>...</body>"
print "</html>
</code></pre>
<p>..without having to worry about concatenating a bunch of strings together. The upshot of this is I could have a separate stream for headers, so the above <code>header()</code> function would write to this.. Something like:</p>
<pre><code>def header(name, value):
pyerweb.header_stream.write("%s: %s" % (name, value))
</code></pre>
<p>Basically, the question is, how would you output headers from this web-framework (mostly in terms of <em>use</em>, but to a lesser extent implementation)?</p>
| [
{
"answer_id": 347509,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "HTTP/1.1 200 OK\nDate: Mon, 23 May 2005 22:38:34 GMT\nServer: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\nLast-Modified: Wed, 08 Jan 2003 23:11:55 GMT\nEtag: \"3f80f-1b6-3e1cb03b\"\nAccept-Ranges: bytes\nContent-Length: 438\nConnection: close\nContent-Type: text/html; charset=UTF-8\n BaseHTTPRequestHandler.send_header(keyword, value"
},
{
"answer_id": 347545,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 2,
"selected": false,
"text": "@GET(\"/\")\ndef index():\nreturn \"<html><body>...</body></html>\"\n @GET(\"/\")\n@HEADER(\"Location\",\"http://google.com\")\ndef index():\nreturn \"<html><body>...</body></html>\"\n @GET(\"/\")\ndef index():\nreturn {\n \"html\": \"<html><body>...</body></html>\",\n \"headers\": {\"Location\":\"http://google.com\"}\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
347,502 | <p>I'm seeing some wierd behaviour when throwing exceptions and catching them in the <code>Application.ThreadException</code> event handler.</p>
<p>Basically whats happening in the sample below is that an exception is thrown in the <code>DoWork</code> event handler of a <code>BackgroundWorker</code>. The <code>RunWorkerCompleted</code> event handler rethrows a new exception with the original as the inner exception.</p>
<p>Why does the inner exception show up in the <code>ThreadException</code> event handler and not the acutal exception being thrown? If I do not provide an inner exception in the <code>RunWorkerCompleted</code> event handler, the correct exception will show up.</p>
<pre><code>using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace WierdExceptionApp
{
class WierdExceptionForm : Form
{
BackgroundWorker worker = new BackgroundWorker();
public WierdExceptionForm()
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
throw new Exception("worker_RunWorkerCompleted", e.Error);
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
throw new Exception("worker_DoWork");
}
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new WierdExceptionForm());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
}
}
</code></pre>
| [
{
"answer_id": 347928,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 1,
"selected": false,
"text": " if (e.Error != null)\n {\n throw new Exception(\"worker_RunWorkerCompleted\", new Exception(\"Inner\", new Exception(\"Inner inner\")));\n }\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
] |
347,512 | <p>I have an element with an <strong>onclick</strong> method.</p>
<p>I would like to activate that method (or: fake a click on this element) within another function.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 347517,
"author": "Ben",
"author_id": 36522,
"author_profile": "https://Stackoverflow.com/users/36522",
"pm_score": 6,
"selected": false,
"text": "document.getElementById('link').click();\n"
},
{
"answer_id": 347520,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 7,
"selected": true,
"text": "$('#elementid').click();\n"
},
{
"answer_id": 347525,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 1,
"selected": false,
"text": "onclick onclick"
},
{
"answer_id": 347526,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 2,
"selected": false,
"text": "<div id=\"c\" onclick=\"alert('hello')\">Click me!</div>\n<div onclick=\"document.getElementById('c').onclick()\">Fake click the previous link!</div>\n"
},
{
"answer_id": 347532,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 3,
"selected": false,
"text": "var clickEvent = new MouseEvent('click', {\n view: window,\n bubbles: true,\n cancelable: true\n});\nvar element = document.getElementById('element-id'); \nvar cancelled = !element.dispatchEvent(clickEvent);\nif (cancelled) {\n // A handler called preventDefault.\n alert(\"cancelled\");\n} else {\n // None of the handlers called preventDefault.\n alert(\"not cancelled\");\n}\n element.dispatchEvent simulateClick()"
},
{
"answer_id": 347554,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 3,
"selected": false,
"text": "var oElement = document.getElementById('elementId'); // get a reference to your element\noElement.onclick = clickHandler; // assign its click function a function reference\n\nfunction clickHandler() {\n // this function will be called whenever the element is clicked\n // and can also be called from the context of other functions\n}\n clickHandler clickHandler"
},
{
"answer_id": 3497621,
"author": "cnaut",
"author_id": 355989,
"author_profile": "https://Stackoverflow.com/users/355989",
"pm_score": -1,
"selected": false,
"text": "eval(document.getElementById('elementId').getAttribute('onclick'));\n"
},
{
"answer_id": 13527036,
"author": "rink.attendant.6",
"author_id": 404623,
"author_profile": "https://Stackoverflow.com/users/404623",
"pm_score": 3,
"selected": false,
"text": ".trigger element.trigger('click');\n"
},
{
"answer_id": 46389710,
"author": "Niklesh Raut",
"author_id": 2815635,
"author_profile": "https://Stackoverflow.com/users/2815635",
"pm_score": 2,
"selected": false,
"text": "javascript click() focus() document.addEventListener(\"click\", function(e) {\n console.log(\"Clicked On : \",e.toElement);\n},true);\ndocument.addEventListener('focus',function(e){\n console.log(\"Focused On : \",e.srcElement);\n},true);\n\ndocument.querySelector(\"#button_1\").click();\ndocument.querySelector(\"#input_1\").focus(); <input type=\"button\" value=\"test-button\" id=\"button_1\">\n<input type=\"text\" value=\"value 1\" id=\"input_1\">\n<input type=\"text\" value=\"value 2\" id=\"input_2\">"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011/"
] |
347,524 | <p>I'm having trouble with <code>TryUpdateModel()</code>. My form fields are named with a prefix but I am using - as my separator and not the default dot.</p>
<pre><code><input type="text" id="Record-Title" name="Record-Title" />
</code></pre>
<p>When I try to update the model it does not get updated. If i change the name attribute to <code>Record.Title</code> it works perfectly but that is not what I want to do.</p>
<pre><code>bool success = TryUpdateModel(record, "Record");
</code></pre>
<p>Is it possible to use a custom separator?</p>
| [
{
"answer_id": 348665,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 3,
"selected": false,
"text": "public class Customer\n{\n public string FirstName {get; set;}\n public string LastName {get; set;}\n}\n\npublic class MyCustomViewData\n{\n public Customer Customer {get; set;}\n public Address Address {get; set;}\n public string Comment {get; set;}\n}\n <%= Html.TextBox(\"FirstName\", ViewData.Model.Customer.FirstName) %>\n <%= Html.TextBox(\"Customer.FirstName\", ViewData.Model.Customer.FirstName) %>\n public ActionResult Save (Formcollection form)\n{\n MyCustomViewData model = GetModel(); // get our model data\n\n TryUpdateModel(model, form); // works for name=\"Customer.FirstName\" only\n TryUpdateModel(model.Customer, form) // works for name=\"FirstName\" only\n TryUpdateModel(model.Customer, \"Customer\", form); // works for name=\"Customer.FirstName\" only\n TryUpdateModel(model, \"Customer\", form) // do not work\n\n ..snip..\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44085/"
] |
347,528 | <p>I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my <code>~/Views/Shared/Site.Master</code>):</p>
<pre><code><script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
</code></pre>
<p>Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with <code>~/Scripts/...</code> doesn't work. Starting with <code>/Scripts/...</code> would only work if the project was at the site root (which I don't want to assume).</p>
<p>I have one working approach (I'll post below) - but: am I missing something?</p>
<p>I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?</p>
<p>Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:</p>
<pre><code><script src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
</code></pre>
| [
{
"answer_id": 347565,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 7,
"selected": true,
"text": "public static string ReferenceScript(string scriptFile)\n{\n var filePath = VirtualPathUtility.ToAbsolute(\"~/Scripts/\" + scriptFile);\n return \"<script type=\\\"text/javascript\\\" src=\\\"\" + filePath + \"\\\"></script>\";\n}\n <%= AppHelper.ReferenceScript(\"jquery-1.2.6.js\") %>\n"
},
{
"answer_id": 347581,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": false,
"text": "public static string ReferenceGoogleAPI()\n{\n var appSettings = new AppSettingsReader();\n string apiKey = appSettings.GetValue(\"GoogleApiKey\", typeof(string)).ToString();\n return ReferenceGoogleAPI(apiKey);\n}\n\npublic static string ReferenceGoogleAPI(string key)\n{\n return \"<script type=\\\"text/javascript\\\" src=\\\"http://www.google.com/jsapi?key=\" + key + \"\\\"></script>\";\n}\n\npublic static string ReferenceGoogleLibrary(string name, string version)\n{\n return \"<script type=\\\"text/javascript\\\">google.load(\\\"\" + name + \"\\\", \\\"\" + version + \"\\\");</script>\";\n}\n"
},
{
"answer_id": 347621,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": " <%=Html.Script(\"~/Scripts/jquery-1.2.6.js\")%>\n public static string Script(this HtmlHelper html, string path)\n{\n var filePath = VirtualPathUtility.ToAbsolute(path);\n return \"<script type=\\\"text/javascript\\\" src=\\\"\" + filePath + \"\\\"></script>\";\n}\n"
},
{
"answer_id": 449995,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 1,
"selected": false,
"text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Const jQuery As String = \"jQuery\"\n\n With Me.Page.ClientScript\n If Not .IsClientScriptIncludeRegistered(jQuery) Then\n .RegisterClientScriptInclude(jQuery, VirtualPathUtility.ToAbsolute(\"~/Includes/jQuery-1.2.6.js\"))\n End If\n End With\nEnd Sub\n"
},
{
"answer_id": 1072513,
"author": "superlogical",
"author_id": 52360,
"author_profile": "https://Stackoverflow.com/users/52360",
"pm_score": 5,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"<%=ResolveUrl(\"~/Scripts/myscript.js\") %>\">\n\n</script>\n"
},
{
"answer_id": 3472880,
"author": "Russell",
"author_id": 154186,
"author_profile": "https://Stackoverflow.com/users/154186",
"pm_score": 0,
"selected": false,
"text": "<script src=\"<%=Request.ApplicationPath%>/Web/AppName/JavaScript/jquery-1.4.1.js\"></script>\n"
},
{
"answer_id": 12222676,
"author": "Alex Pryiomka",
"author_id": 8435658,
"author_profile": "https://Stackoverflow.com/users/8435658",
"pm_score": 0,
"selected": false,
"text": "<script src=\"@Url.Content(\"~/Scripts/jquery.min.js\")\" type=\"text/javascript\"></script>\n"
},
{
"answer_id": 13948770,
"author": "Raisul Asad",
"author_id": 1097403,
"author_profile": "https://Stackoverflow.com/users/1097403",
"pm_score": 1,
"selected": false,
"text": "<script src=\"/Script/jquery-1.4.1.js\"></script>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23354/"
] |
347,529 | <p>I need to add Workflows to an existing solution, which already contains a class library and a web site. If I add the workflows to the class library, where they fit logically, I have no designer support. If I create them in a separate project, I tend to have circular dependencies because my domain objects run the workflows and the workflows need my domain objects.</p>
<p>What is the preferred architecture to avoid this problem?</p>
| [
{
"answer_id": 374977,
"author": "kay.herzam",
"author_id": 47093,
"author_profile": "https://Stackoverflow.com/users/47093",
"pm_score": 3,
"selected": true,
"text": "<ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <Import Project=\"$(MSBuildExtensionsPath)\\Microsoft\\Windows Workflow Foundation\\v3.5\\Workflow.Targets\" /> <Import Project=\"$(MSBuildExtensionsPath)\\Microsoft\\Windows Workflow Foundation\\v3.0\\Workflow.Targets\" />"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40396/"
] |
347,535 | <p>I know that MSTest doesn't support <code>RowTest</code> and similar tests.</p>
<p>What do <code>MSTests</code> users do? How is it possible to live without <code>RowTest</code> support? </p>
<p>I've seen <code>DataDriven</code> test features but sounds like too much overhead, is there any 3rd party patch or tool which allow me to do <code>RowTest</code> similar tests in <code>MSTest</code>?</p>
| [
{
"answer_id": 1205297,
"author": "Tormod",
"author_id": 80577,
"author_profile": "https://Stackoverflow.com/users/80577",
"pm_score": 5,
"selected": false,
"text": "[TestMethod]\nTest1Row1\n{\n Test1(1,4,5);\n}\n\n[TestMethod]\nTest1Row2\n{\n Test1(1,7,8);\n}\n\nprivate Test1(int i, int j, int k)\n{\n //all code and assertions in here\n}\n"
},
{
"answer_id": 13875394,
"author": "allen",
"author_id": 1691227,
"author_profile": "https://Stackoverflow.com/users/1691227",
"pm_score": 3,
"selected": false,
"text": "[DataRow]"
},
{
"answer_id": 18625620,
"author": "Dmytro Zharii",
"author_id": 1126595,
"author_profile": "https://Stackoverflow.com/users/1126595",
"pm_score": 0,
"selected": false,
"text": "[TestClass]\npublic class Ha_ha_ha_Test: MsTestRows.Rows.TestRows_42<string>\n{\n public override void TestMethod(string dataRow, int rowNumber)\n {\n Console.WriteLine(dataRow);\n Assert.IsFalse(dataRow.Contains(\"3\"));\n }\n\n public override string GetNextDataRow(int rowNumber)\n {\n return \"data\" + rowNumber;\n }\n}\n"
},
{
"answer_id": 19536942,
"author": "Thwaitesy",
"author_id": 1295088,
"author_profile": "https://Stackoverflow.com/users/1295088",
"pm_score": 3,
"selected": false,
"text": "public class UnitTest1 : TestBase\n{ }\n public class UnitTest1 : TestBase\n{\n private IEnumerable<int> Stuff\n {\n get\n {\n //This could do anything, get a dynamic list from anywhere....\n return new List<int> { 1, 2, 3 };\n }\n }\n}\n [DataSource(\"Namespace.UnitTest1.Stuff\")]\npublic void TestMethod1()\n{\n var number = this.TestContext.GetRuntimeDataSourceObject<int>();\n\n Assert.IsNotNull(number);\n}\n using Microsoft.VisualStudio.TestTools.UnitTesting;\nusing MSTestHacks;\n\nnamespace Namespace\n{\n public class UnitTest1 : TestBase\n {\n private IEnumerable<int> Stuff\n {\n get\n {\n //This could do anything, get a dynamic list from anywhere....\n return new List<int> { 1, 2, 3 };\n }\n }\n\n [DataSource(\"Namespace.UnitTest1.Stuff\")]\n public void TestMethod1()\n {\n var number = this.TestContext.GetRuntimeDataSourceObject<int>();\n\n Assert.IsNotNull(number);\n }\n }\n}\n"
},
{
"answer_id": 27881529,
"author": "Gary.Ray",
"author_id": 76874,
"author_profile": "https://Stackoverflow.com/users/76874",
"pm_score": 2,
"selected": false,
"text": "public static class Extensions\n{\n /// <summary>\n /// Get the Qtr with optional offset to add or subtract quarters\n /// </summary>\n public static int GetQuarterNumber(this DateTime parmDate, int offset = 0)\n {\n return (int)Math.Ceiling(parmDate.AddMonths(offset * 3).Month / 3m);\n }\n}\n [TestMethod]\npublic void MonthReturnsProperQuarterWithOffset()\n{\n // Arrange\n var values = new[] {\n new { inputDate = new DateTime(2013, 1, 1), offset = 1, expectedQuarter = 2},\n new { inputDate = new DateTime(2013, 1, 1), offset = -1, expectedQuarter = 4},\n new { inputDate = new DateTime(2013, 4, 1), offset = 1, expectedQuarter = 3},\n new { inputDate = new DateTime(2013, 4, 1), offset = -1, expectedQuarter = 1},\n new { inputDate = new DateTime(2013, 7, 1), offset = 1, expectedQuarter = 4},\n new { inputDate = new DateTime(2013, 7, 1), offset = -1, expectedQuarter = 2},\n new { inputDate = new DateTime(2013, 10, 1), offset = 1, expectedQuarter = 1},\n new { inputDate = new DateTime(2013, 10, 1), offset = -1, expectedQuarter = 3}\n // Could add as many rows as you want, or extract to a private method that\n // builds the array of data\n }; \n values.ToList().ForEach(val => \n { \n // Act \n int actualQuarter = val.inputDate.GetQuarterNumber(val.offset); \n // Assert \n Assert.AreEqual(val.expectedQuarter, actualQuarter, \n \"Failed for inputDate={0}, offset={1} and expectedQuarter={2}.\", val.inputDate, val.offset, val.expectedQuarter); \n }); \n }\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40322/"
] |
347,551 | <p>Given a file tree - a directory with directories in it etc, how would you write a script to create a diagram of the file-tree as a graphic file that I can embed in a word processor document.
I prefer vector (SVG, EPS, EMF...) files.
The tool must run on Windows, but preferably cross-platform.
The tool may be commercial but preferably free.</p>
<p>Update 2012-02-20.
The question was related to a documentation sub project. I had to explan where files (in particular resources and configuration files) reside.
I ended up with using dos tree command. I both screen grabbed the result (for short folders) AND for longer folders I redirected to a text file, which I then edited. For example if a subfolder contained 20 similarly typed files that individually were not important to the point I was making, I left just two and replaced the rest with one ... line. I then printed out the file to console again and screen grabbed it.
Before screen grabbing I had to modify foreground color to black and background color to white, to look better and save ink in a document should that be printed.</p>
<p>It is very surprising that there is no better tool for it. If I had time, I'd write a Visio Extension or may be some command line that produces SVG. SVG being HTML5 substandard, would even allow painless inclusion into online documentation.</p>
<p>Update 2017-10-17.
I am sorry that this question was removed as not belonging to SO. So I have re-worded it. I need a script - not a WYSIWYG tool. So any scripting language or library is ok. So it is a code - writing question, and I believe belongs to SO. </p>
| [
{
"answer_id": 347577,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 8,
"selected": true,
"text": "tree C:\\Foobar>tree\nC:.\n├───FooScripts\n├───barconfig\n├───Baz\n│ ├───BadBaz\n│ └───Drop\n...\n C:\\Foobar>tree\nC:.\n├───FooScripts\n│ foo.sh\n├───barconfig\n│ bar.xml\n├───Baz\n│ ├───BadBaz\n│ │ badbaz.xml\n│ └───Drop\n...\n C:\\Foobar>tree /A\nC:.\n+---FooScripts\n+---barconfig\n+---Baz\n¦ +---BadBaz\n¦ \\---Drop\n...\n C:\\Foobar>tree /A\nC:.\n+---FooScripts\n¦ foo.sh\n+---barconfig\n¦ bar.xml\n+---Baz\n¦ +---BadBaz\n¦ ¦ badbaz.xml\n¦ \\---Drop\n...\n tree drive: path /F /A drive:\\path /F /A /a"
},
{
"answer_id": 348254,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "digraph tree\n{\n rankdir=LR;\n\n DirTree [label=\"Directory Tree\" shape=box]\n\n a_Foo_txt [shape=point]\n f_Foo_txt [label=\"Foo.txt\", shape=none]\n a_Foo_txt -> f_Foo_txt\n\n a_Foo_Bar_html [shape=point]\n f_Foo_Bar_html [label=\"Foo Bar.html\", shape=none]\n a_Foo_Bar_html -> f_Foo_Bar_html\n\n a_Bar_png [shape=point]\n f_Bar_png [label=\"Bar.png\", shape=none]\n a_Bar_png -> f_Bar_png\n\n a_Some_Dir [shape=point]\n d_Some_Dir [label=\"Some Dir\", shape=ellipse]\n a_Some_Dir -> d_Some_Dir\n\n a_VBE_C_reg [shape=point]\n f_VBE_C_reg [label=\"VBE_C.reg\", shape=none]\n a_VBE_C_reg -> f_VBE_C_reg\n\n a_P_Folder [shape=point]\n d_P_Folder [label=\"P Folder\", shape=ellipse]\n a_P_Folder -> d_P_Folder\n\n a_Processing_20081117_7z [shape=point]\n f_Processing_20081117_7z [label=\"Processing-20081117.7z\", shape=none]\n a_Processing_20081117_7z -> f_Processing_20081117_7z\n\n a_UsefulBits_lua [shape=point]\n f_UsefulBits_lua [label=\"UsefulBits.lua\", shape=none]\n a_UsefulBits_lua -> f_UsefulBits_lua\n\n a_Graphviz [shape=point]\n d_Graphviz [label=\"Graphviz\", shape=ellipse]\n a_Graphviz -> d_Graphviz\n\n a_Tree_dot [shape=point]\n f_Tree_dot [label=\"Tree.dot\", shape=none]\n a_Tree_dot -> f_Tree_dot\n\n {\n rank=same;\n DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]\n }\n {\n rank=same;\n d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]\n }\n {\n rank=same;\n d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]\n }\n {\n rank=same;\n d_Graphviz -> a_Tree_dot [arrowhead=none]\n }\n}\n\n> dot -Tpng Tree.dot -o Tree.png\nError: lost DirTree a_Foo_txt edge\nError: lost a_Foo_txt a_Foo_Bar_html edge\nError: lost a_Foo_Bar_html a_Bar_png edge\nError: lost a_Bar_png a_Some_Dir edge\nError: lost a_Some_Dir a_Graphviz edge\nError: lost d_Some_Dir a_VBE_C_reg edge\nError: lost a_VBE_C_reg a_P_Folder edge\nError: lost a_P_Folder a_UsefulBits_lua edge\nError: lost d_P_Folder a_Processing_20081117_7z edge\nError: lost d_Graphviz a_Tree_dot edge\n"
},
{
"answer_id": 351449,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "-- LuaFileSystem <http://www.keplerproject.org/luafilesystem/>\nrequire\"lfs\"\n-- LuaCairo <http://www.dynaset.org/dogusanh/>\nrequire\"lcairo\"\nlocal CAIRO = cairo\n\n\nlocal PI = math.pi\nlocal TWO_PI = 2 * PI\n\n--~ local dirToList = arg[1] or \"C:/PrgCmdLine/Graphviz\"\n--~ local dirToList = arg[1] or \"C:/PrgCmdLine/Tecgraf\"\nlocal dirToList = arg[1] or \"C:/PrgCmdLine/tcc\"\n-- Ensure path ends with /\ndirToList = string.gsub(dirToList, \"([^/])$\", \"%1/\")\nprint(\"Listing: \" .. dirToList)\nlocal fileNb = 0\n\n--~ outputType = 'svg'\noutputType = 'png'\n\n-- dirToList must have a trailing slash\nfunction ListDirectory(dirToList)\n local dirListing = {}\n for file in lfs.dir(dirToList) do\n if file ~= \"..\" and file ~= \".\" then\n local fileAttr = lfs.attributes(dirToList .. file)\n if fileAttr.mode == \"directory\" then\n dirListing[file] = ListDirectory(dirToList .. file .. '/')\n else\n dirListing[file] = \"\"\n end\n fileNb = fileNb + 1\n end\n end\n return dirListing\nend\n\n--dofile[[../Lua/DumpObject.lua]] -- My own dump routine\nlocal dirListing = ListDirectory(dirToList)\n--~ print(\"\\n\" .. DumpObject(dirListing))\nprint(\"Found \" .. fileNb .. \" files\")\n\n--~ os.exit()\n\n-- Constants to change to adjust aspect\nlocal initialOffsetX = 20\nlocal offsetY = 50\nlocal offsetIncrementX = 20\nlocal offsetIncrementY = 12\nlocal iconOffset = 10\n\nlocal width = 800 -- Still arbitrary\nlocal titleHeight = width/50\nlocal height = offsetIncrementY * (fileNb + 1) + titleHeight\nlocal outfile = \"CairoDirTree.\" .. outputType\n\nlocal ctxSurface\nif outputType == 'svg' then\n ctxSurface = cairo.SvgSurface(outfile, width, height)\nelse\n ctxSurface = cairo.ImageSurface(CAIRO.FORMAT_RGB24, width, height)\nend\nlocal ctx = cairo.Context(ctxSurface)\n\n-- Display a file name\n-- file is the file name to display\n-- offsetX is the indentation\nfunction DisplayFile(file, bIsDir, offsetX)\n if bIsDir then\n ctx:save()\n ctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)\n ctx:set_source_rgb(0.5, 0.0, 0.7)\n end\n\n -- Display file name\n ctx:move_to(offsetX, offsetY)\n ctx:show_text(file)\n\n if bIsDir then\n ctx:new_sub_path() -- Position independent of latest move_to\n -- Draw arc with absolute coordinates\n ctx:arc(offsetX - iconOffset, offsetY - offsetIncrementY/3, offsetIncrementY/3, 0, TWO_PI)\n -- Violet disk\n ctx:set_source_rgb(0.7, 0.0, 0.7)\n ctx:fill()\n ctx:restore() -- Restore original settings\n end\n\n -- Increment line offset\n offsetY = offsetY + offsetIncrementY\nend\n\n-- Erase background (white)\nctx:set_source_rgb(1.0, 1.0, 1.0)\nctx:paint()\n\n--~ ctx:set_line_width(0.01)\n\n-- Draw in dark blue\nctx:set_source_rgb(0.0, 0.0, 0.3)\nctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)\nctx:set_font_size(titleHeight)\nctx:move_to(5, titleHeight)\n-- Display title\nctx:show_text(\"Directory tree of \" .. dirToList)\n\n-- Select font for file names\nctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_NORMAL)\nctx:set_font_size(10)\noffsetY = titleHeight * 2\n\n-- Do the job\nfunction DisplayDirectory(dirToList, offsetX)\n for k, v in pairs(dirToList) do\n--~ print(k, v)\n if type(v) == \"table\" then\n -- Sub-directory\n DisplayFile(k, true, offsetX)\n DisplayDirectory(v, offsetX + offsetIncrementX)\n else\n DisplayFile(k, false, offsetX)\n end\n end\nend\n\nDisplayDirectory(dirListing, initialOffsetX)\n\nif outputType == 'svg' then\n cairo.show_page(ctx)\nelse\n --cairo.surface_write_to_png(ctxSurface, outfile)\n ctxSurface:write_to_png(outfile)\nend\n\nctx:destroy()\nctxSurface:destroy()\n\nprint(\"Found \" .. fileNb .. \" files\")\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33427/"
] |
347,553 | <p>With the JavaFX 1.0 release I am trying to layout some SwingButton instances in a HBox such that they are aligned to the right. A lot of the tutorials on the net (admittedly pre 1.0 release) talk about layout classes (FlowPanel et. al) which dont seem to be in this release. Whats the simplest way to achieve this seemingly simple task?</p>
| [
{
"answer_id": 347577,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 8,
"selected": true,
"text": "tree C:\\Foobar>tree\nC:.\n├───FooScripts\n├───barconfig\n├───Baz\n│ ├───BadBaz\n│ └───Drop\n...\n C:\\Foobar>tree\nC:.\n├───FooScripts\n│ foo.sh\n├───barconfig\n│ bar.xml\n├───Baz\n│ ├───BadBaz\n│ │ badbaz.xml\n│ └───Drop\n...\n C:\\Foobar>tree /A\nC:.\n+---FooScripts\n+---barconfig\n+---Baz\n¦ +---BadBaz\n¦ \\---Drop\n...\n C:\\Foobar>tree /A\nC:.\n+---FooScripts\n¦ foo.sh\n+---barconfig\n¦ bar.xml\n+---Baz\n¦ +---BadBaz\n¦ ¦ badbaz.xml\n¦ \\---Drop\n...\n tree drive: path /F /A drive:\\path /F /A /a"
},
{
"answer_id": 348254,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "digraph tree\n{\n rankdir=LR;\n\n DirTree [label=\"Directory Tree\" shape=box]\n\n a_Foo_txt [shape=point]\n f_Foo_txt [label=\"Foo.txt\", shape=none]\n a_Foo_txt -> f_Foo_txt\n\n a_Foo_Bar_html [shape=point]\n f_Foo_Bar_html [label=\"Foo Bar.html\", shape=none]\n a_Foo_Bar_html -> f_Foo_Bar_html\n\n a_Bar_png [shape=point]\n f_Bar_png [label=\"Bar.png\", shape=none]\n a_Bar_png -> f_Bar_png\n\n a_Some_Dir [shape=point]\n d_Some_Dir [label=\"Some Dir\", shape=ellipse]\n a_Some_Dir -> d_Some_Dir\n\n a_VBE_C_reg [shape=point]\n f_VBE_C_reg [label=\"VBE_C.reg\", shape=none]\n a_VBE_C_reg -> f_VBE_C_reg\n\n a_P_Folder [shape=point]\n d_P_Folder [label=\"P Folder\", shape=ellipse]\n a_P_Folder -> d_P_Folder\n\n a_Processing_20081117_7z [shape=point]\n f_Processing_20081117_7z [label=\"Processing-20081117.7z\", shape=none]\n a_Processing_20081117_7z -> f_Processing_20081117_7z\n\n a_UsefulBits_lua [shape=point]\n f_UsefulBits_lua [label=\"UsefulBits.lua\", shape=none]\n a_UsefulBits_lua -> f_UsefulBits_lua\n\n a_Graphviz [shape=point]\n d_Graphviz [label=\"Graphviz\", shape=ellipse]\n a_Graphviz -> d_Graphviz\n\n a_Tree_dot [shape=point]\n f_Tree_dot [label=\"Tree.dot\", shape=none]\n a_Tree_dot -> f_Tree_dot\n\n {\n rank=same;\n DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]\n }\n {\n rank=same;\n d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]\n }\n {\n rank=same;\n d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]\n }\n {\n rank=same;\n d_Graphviz -> a_Tree_dot [arrowhead=none]\n }\n}\n\n> dot -Tpng Tree.dot -o Tree.png\nError: lost DirTree a_Foo_txt edge\nError: lost a_Foo_txt a_Foo_Bar_html edge\nError: lost a_Foo_Bar_html a_Bar_png edge\nError: lost a_Bar_png a_Some_Dir edge\nError: lost a_Some_Dir a_Graphviz edge\nError: lost d_Some_Dir a_VBE_C_reg edge\nError: lost a_VBE_C_reg a_P_Folder edge\nError: lost a_P_Folder a_UsefulBits_lua edge\nError: lost d_P_Folder a_Processing_20081117_7z edge\nError: lost d_Graphviz a_Tree_dot edge\n"
},
{
"answer_id": 351449,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "-- LuaFileSystem <http://www.keplerproject.org/luafilesystem/>\nrequire\"lfs\"\n-- LuaCairo <http://www.dynaset.org/dogusanh/>\nrequire\"lcairo\"\nlocal CAIRO = cairo\n\n\nlocal PI = math.pi\nlocal TWO_PI = 2 * PI\n\n--~ local dirToList = arg[1] or \"C:/PrgCmdLine/Graphviz\"\n--~ local dirToList = arg[1] or \"C:/PrgCmdLine/Tecgraf\"\nlocal dirToList = arg[1] or \"C:/PrgCmdLine/tcc\"\n-- Ensure path ends with /\ndirToList = string.gsub(dirToList, \"([^/])$\", \"%1/\")\nprint(\"Listing: \" .. dirToList)\nlocal fileNb = 0\n\n--~ outputType = 'svg'\noutputType = 'png'\n\n-- dirToList must have a trailing slash\nfunction ListDirectory(dirToList)\n local dirListing = {}\n for file in lfs.dir(dirToList) do\n if file ~= \"..\" and file ~= \".\" then\n local fileAttr = lfs.attributes(dirToList .. file)\n if fileAttr.mode == \"directory\" then\n dirListing[file] = ListDirectory(dirToList .. file .. '/')\n else\n dirListing[file] = \"\"\n end\n fileNb = fileNb + 1\n end\n end\n return dirListing\nend\n\n--dofile[[../Lua/DumpObject.lua]] -- My own dump routine\nlocal dirListing = ListDirectory(dirToList)\n--~ print(\"\\n\" .. DumpObject(dirListing))\nprint(\"Found \" .. fileNb .. \" files\")\n\n--~ os.exit()\n\n-- Constants to change to adjust aspect\nlocal initialOffsetX = 20\nlocal offsetY = 50\nlocal offsetIncrementX = 20\nlocal offsetIncrementY = 12\nlocal iconOffset = 10\n\nlocal width = 800 -- Still arbitrary\nlocal titleHeight = width/50\nlocal height = offsetIncrementY * (fileNb + 1) + titleHeight\nlocal outfile = \"CairoDirTree.\" .. outputType\n\nlocal ctxSurface\nif outputType == 'svg' then\n ctxSurface = cairo.SvgSurface(outfile, width, height)\nelse\n ctxSurface = cairo.ImageSurface(CAIRO.FORMAT_RGB24, width, height)\nend\nlocal ctx = cairo.Context(ctxSurface)\n\n-- Display a file name\n-- file is the file name to display\n-- offsetX is the indentation\nfunction DisplayFile(file, bIsDir, offsetX)\n if bIsDir then\n ctx:save()\n ctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)\n ctx:set_source_rgb(0.5, 0.0, 0.7)\n end\n\n -- Display file name\n ctx:move_to(offsetX, offsetY)\n ctx:show_text(file)\n\n if bIsDir then\n ctx:new_sub_path() -- Position independent of latest move_to\n -- Draw arc with absolute coordinates\n ctx:arc(offsetX - iconOffset, offsetY - offsetIncrementY/3, offsetIncrementY/3, 0, TWO_PI)\n -- Violet disk\n ctx:set_source_rgb(0.7, 0.0, 0.7)\n ctx:fill()\n ctx:restore() -- Restore original settings\n end\n\n -- Increment line offset\n offsetY = offsetY + offsetIncrementY\nend\n\n-- Erase background (white)\nctx:set_source_rgb(1.0, 1.0, 1.0)\nctx:paint()\n\n--~ ctx:set_line_width(0.01)\n\n-- Draw in dark blue\nctx:set_source_rgb(0.0, 0.0, 0.3)\nctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)\nctx:set_font_size(titleHeight)\nctx:move_to(5, titleHeight)\n-- Display title\nctx:show_text(\"Directory tree of \" .. dirToList)\n\n-- Select font for file names\nctx:select_font_face(\"Sans\", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_NORMAL)\nctx:set_font_size(10)\noffsetY = titleHeight * 2\n\n-- Do the job\nfunction DisplayDirectory(dirToList, offsetX)\n for k, v in pairs(dirToList) do\n--~ print(k, v)\n if type(v) == \"table\" then\n -- Sub-directory\n DisplayFile(k, true, offsetX)\n DisplayDirectory(v, offsetX + offsetIncrementX)\n else\n DisplayFile(k, false, offsetX)\n end\n end\nend\n\nDisplayDirectory(dirListing, initialOffsetX)\n\nif outputType == 'svg' then\n cairo.show_page(ctx)\nelse\n --cairo.surface_write_to_png(ctxSurface, outfile)\n ctxSurface:write_to_png(outfile)\nend\n\nctx:destroy()\nctxSurface:destroy()\n\nprint(\"Found \" .. fileNb .. \" files\")\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5193/"
] |
347,564 | <p>I have a problem with simple c++ programs... </p>
<p>I would like to install a program, but always have the error like "c++ compiler is unable to create executables"...</p>
<p>Now I tried to compile a simple "hello world" program, but I get errors as I would if I compile a c++ program with a c compiler ("`cout' undeclared"... although I included iostream)...</p>
<p>Now I am not sure, if g++ does not work on my machine?</p>
<p>Does anyone know about how to fix this problem?</p>
<p>Thank you very much in advance...<br>
Chris</p>
<hr>
<p><em>Added</em> In response to Pax's answer:</p>
<p>Well, I think, my code is okay, I can compile it on another machine, and I use the namespace std...</p>
<p>So, it's not possible, that the configuration of g++ is mismatched or something like that...?</p>
| [
{
"answer_id": 347595,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "g++\n g++: no input files\n g++ -o output-file input-file\n"
},
{
"answer_id": 348535,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\nint main() { std::cout << \"Hello\" << std::endl; }\n \"g++ t.cc\" \"g++ -v\""
},
{
"answer_id": 357510,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 0,
"selected": false,
"text": "which gcc\nwhich c++\n gcc --version\ng++ --version\n"
},
{
"answer_id": 7296582,
"author": "Templar",
"author_id": 799,
"author_profile": "https://Stackoverflow.com/users/799",
"pm_score": -1,
"selected": false,
"text": "sudo apt-get install build-essential\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,572 | <p>I'm new to iPhone and Apple development and working on my first application. It simple with only a TableView and a "detail view" when an item in a table is selected.</p>
<p>What I want to do is change the background color of the cell in the TableView based on some action taken in my "detail view".</p>
<p>When the application initially loads I customize the colors in <code>-cellForRowAtIndexPath:</code> method, but when user navigates back from my detail view that function is not called, so my table view doesn't have the colors updated. The only way to get that refreshed now is to exit the application and start it up again. (I persist their selection with NSUserDefaults.)</p>
<p>Obviously, I want the table view to be refreshed when they come back form the detail view, but I don't know how to get a reference to a cell and in which method to do that. I'm assuming it should go in <code>-viewDidAppear</code>, since that is called everything the view is shown.</p>
| [
{
"answer_id": 347598,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 3,
"selected": false,
"text": "viewWillAppear: visibleCells dequeue..."
},
{
"answer_id": 347751,
"author": "Adam Byram",
"author_id": 25886,
"author_profile": "https://Stackoverflow.com/users/25886",
"pm_score": 6,
"selected": true,
"text": "[tableView reloadData]"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44091/"
] |
347,574 | <p>This is a follow-up to a <a href="https://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest">previous question</a> of mine.</p>
<p>In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring testing did not stop at the first function that failed.</p>
<p>My preferred solution used a metaclass to dynamically insert the tests into a unittest.TestCase. Unfortunately, nose does not pick this up because nose statically scans for test cases.</p>
<p>How do I get nose to discover and run such a TestCase? Please refer <a href="https://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest#347175">here</a> for an example of the TestCase in question.</p>
| [
{
"answer_id": 366620,
"author": "ionelmc",
"author_id": 23658,
"author_profile": "https://Stackoverflow.com/users/23658",
"pm_score": 1,
"selected": false,
"text": "class UnderTest_MixIn(object):\n\n def f1(self, i):\n return i + 1\n\n def f2(self, i):\n return i + 2\n\nSomeDynamicTestcase = type(\n \"SomeDynamicTestcase\", \n (UnderTest_MixIn, unittest.TestCase), \n {\"even_more_dynamic\":\"attributes ..\"}\n)\n\n# or even:\n\nname = 'SomeDynamicTestcase'\nglobals()[name] = type(\n name, \n (UnderTest_MixIn, unittest.TestCase), \n {\"even_more_dynamic\":\"attributes ..\"}\n)\n"
},
{
"answer_id": 676420,
"author": "Matt Good",
"author_id": 81845,
"author_profile": "https://Stackoverflow.com/users/81845",
"pm_score": 4,
"selected": true,
"text": "import unittest\nimport numpy\n\nfrom somewhere import the_functions\n\ndef test_matrix_functions():\n for function in the_functions:\n yield check_matrix_function, function\n\ndef check_matrix_function(function)\n matrix1 = numpy.ones((5,10))\n matrix2 = numpy.identity(5)\n output = function(matrix1, matrix2)\n assert matrix1.shape == output.shape, \\\n \"%s produces output of the wrong shape\" % str(function)\n"
},
{
"answer_id": 13579703,
"author": "Robert T. McGibbon",
"author_id": 1079728,
"author_profile": "https://Stackoverflow.com/users/1079728",
"pm_score": 2,
"selected": false,
"text": "\"test_%d\" %i import new\nfrom inspect import isfunction, getdoc\n\nclass Meta(type):\n def __new__(cls, name, bases, dct):\n\n newdct = dct.copy()\n for i, (k, v) in enumerate(filter(lambda e: isfunction(e[1]), dct.items())):\n def m(self, func):\n assert getdoc(func) is not None\n\n fname = 'test_%d' % i\n newdct[fname] = new.function(m.func_code, globals(), fname,\n (v,), m.func_closure)\n\n return super(Meta, cls).__new__(cls, 'Test_'+name, bases, newdct)\n class Foo(object):\n __metaclass__ = Meta\n\n def greeter(self):\n \"sdf\"\n print 'Hello World'\n\n def greeter_no_docstring(self):\n pass\n Foo Test_Foo greeter greeter_no_docstring test_1 test_2 nosetests $ nosetests -v test.py\ntest.Test_Foo.test_0 ... FAIL\ntest.Test_Foo.test_1 ... ok\n\n======================================================================\nFAIL: test.Test_Foo.test_0\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/nose/case.py\", line 197, in runTest\n self.test(*self.arg)\n File \"/Users/rmcgibbo/Desktop/test.py\", line 10, in m\n assert getdoc(func) is not None\nAssertionError\n\n----------------------------------------------------------------------\nRan 2 tests in 0.002s\n\nFAILED (failures=1)\n Meta m(self, func) func value"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
347,575 | <p>What is the easiest way to check if a computer is alive and responding (say in ping/NetBios)?
I'd like a deterministic method that I can time-limit.</p>
<p>One solution is simple access the share (File.GetDirectories(@"\compname")) in a separate thread, and kill the thread if it takes too long.</p>
| [
{
"answer_id": 347587,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 4,
"selected": true,
"text": "System.Net.NetworkInformation"
},
{
"answer_id": 347616,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "myPort System.Net.Sockets.SocketException using System.Net;\nusing System.Net.Sockets;\n...\n\nIPHostEntry myHostEntry = Dns.GetHostByName(\"myserver\");\nIPEndPoint host = new IPEndPoint(myHostEntry.AddressList[0], myPort);\n\nSocket s = new Socket(AddressFamily.InterNetwork,\n SocketType.Stream, ProtocolType.Tcp);\ns.Connect(host);\n"
},
{
"answer_id": 10449906,
"author": "SanBen",
"author_id": 1087372,
"author_profile": "https://Stackoverflow.com/users/1087372",
"pm_score": 1,
"selected": false,
"text": " //for sending an arp request (see pinvoke.net)\n [DllImport(\"iphlpapi.dll\", ExactSpelling = true)]\n public static extern int SendARP(\n int DestIP, \n int SrcIP, \n byte[] pMacAddr, \n ref uint PhyAddrLen);\n\n\n public bool IsComputerAlive(IPAddress host)\n {\n //can't check the own machine (assume it's alive)\n if (host.Equals(IPAddress.Loopback))\n return true;\n\n //Prepare the magic\n\n //this is only needed to pass a valid parameter\n byte[] macAddr = new byte[6];\n uint macAddrLen = (uint)macAddr.Length;\n\n //Let's check if it is alive by sending an arp request\n if (SendARP((int)host.Address, 0, macAddr, ref macAddrLen) == 0)\n return true; //Igor it's alive!\n\n return false;//Not alive\n }\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
347,592 | <p>The title pretty much says it all. I'm using a TClientDataset to store an array of objects, and one of the objects has a member defined as a <strong>set of</strong> an enumerated type. As I understand it, Delphi sets are bitfields whose size can vary from 1 to 32 bytes depending on how much data they contain, and Delphi doesn't define a TSetField. What sort of field should I use to load this value into?</p>
| [
{
"answer_id": 347604,
"author": "Andreas Hausladen",
"author_id": 44005,
"author_profile": "https://Stackoverflow.com/users/44005",
"pm_score": 5,
"selected": true,
"text": "var\n MySet: set of Byte;\n Bytes: array of Byte;\nbegin\n MySet := [1, 2, 4, 8, 16];\n\n // Write\n Assert(ClientDataSet1MySet.DataSize >= SizeOf(MySet), 'Data field is too small');\n\n SetLength(Bytes, ClientDataSet1MySet.DataSize);\n Move(MySet, Bytes[0], SizeOf(MySet));\n ClientDataSet1.Edit;\n ClientDataSet1MySet.SetData(@Bytes[0]);\n ClientDataSet1.Post;\n\n // Read\n SetLength(Bytes, ClientDataSet1MySet.DataSize);\n if ClientDataSet1MySet.GetData(@Bytes[0]) then\n Move(Bytes[0], MySet, SizeOf(MySet))\n else\n MySet := []; // NULL\nend;\n"
},
{
"answer_id": 350934,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 2,
"selected": false,
"text": "var\n States : TUpdateStatusSet; // Can be any set, I took this one from DB.pas unit\n SetAsAInteger: Integer;\n dbs: Pointer; // Here's the trick\nbegin\n States := [usModified, usInserted]; // Putting some content in that set\n dbs := @States;\n SetAsAInteger := PByte(dbs)^;\n //Once you got it, SetAsAInteger is just another ordinary integer variable.\n //Use it the way you like.\nend;\n var\n MSG: string;\n Inserted, Modified: string;\n States: TUpdateStatusSet;\n MySet: Byte;\n\nbegin\n while not ClientDataSet.Eof do\n begin\n //That's the part that interest us\n //Convert that integer you stored in the database or whatever \n //place to a Byte and, in the sequence, to your set type.\n iSet := Byte(ClientDatasetMyIntegerField);// Sets are one byte, so they\n // fit on a byte variable \n States := TUpdateStatusSet(iSet);\n //Conversion finished, below is just interface stuff\n\n\n if usInserted in States then\n Inserted := 'Yes';\n if usModified in States then\n Modified := 'Yes';\n MSG := Format('Register Num: %d. Inserted: %s. Modified:%s',\n [ClientDataSet.RecNo, Inserted, Alterted]);\n ShowMessage( MSG );\n ClientDataset.Next;\n end;\n\nend;\n"
},
{
"answer_id": 20395170,
"author": "Roeland Van Heddegem",
"author_id": 1140659,
"author_profile": "https://Stackoverflow.com/users/1140659",
"pm_score": 0,
"selected": false,
"text": "var\n MySet: set of Byte;\n Bytes: TBytes;\nbegin\n MySet := [0];\n\n // Write\n Assert(ClientDataSet1Test.DataSize >= SizeOf(MySet), 'Data field is too small');\n\n SetLength(Bytes, ClientDataSet1Test.DataSize);\n Move(MySet, Bytes[0], SizeOf(MySet));\n ClientDataSet1.Edit;\n ClientDataSet1Test.AsBytes := Bytes;\n ClientDataSet1.Post;\nend;\n var\n MyResultSet: set of Byte;\nbegin\n Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize);\nend;\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32914/"
] |
347,606 | <p>I was curious as to what other shops are doing regarding base application frameworks? I look at an application framework as being able to provide additional or extended functionality to improve the quality of applications built from it.</p>
<p>There are a variety of out of the box frameworks, such as Spring (or Spring.NET), etc. I find that the largest problem with these being that they are not a la carte. Basically, they have too much functionality and unless every piece of that functionality is the best implementation available, chances are that you will end up using a patchwork of multiple frameworks to accomplish these tasks - causing bloat and confusion. This applies to free and commercial systems, in my opinion.</p>
<p>Of course, writing is largely re-inventing the wheel. I don't think it is without merit, though, as it provides the most customizable option. Some things are just too large to develop, though, and seem to be poorly implemented or not implemented at all in this case because of the hesitation to commit to the upfront costs of development.</p>
<p>There are a large variety of open source projects that address individual portions of a could-be application framework as well. These can be adopted or assimilated (obviously depending upon license agreements) to help frame in a comprehensive framework from diverse sources.</p>
<p>We approached the situation by looking at some of the larger concerns in our applications across the entire enterprise and came up with a list of valid cross-cutting concerns and recurring implementation issues. In the end, we came up with hybrid solution that is partially open source, partially based on existing open source options, and partially custom developed.</p>
<p>A few examples of things that are in our framework:</p>
<ul>
<li>Exception and event logging providers. A simple, uniform means by which every application can log exceptions and events in an identical fashion with a minimal coding effort. Out of the box, it can log to a SQL Server, text file, event viewer, etc. It contains extensibility points to log to other sources, as well.</li>
<li>Variable assignment enforcement. A generic class that exposes extension methods based upon the object type, using a syntax that is inspired by JUnit. For example, to determine if myObject is not null, we can do a simple Enforce.That(myObject).IsNotNull(); or determine if it is a specific type by doing a simple Enforce.That(myObject).IsOfType(typeof(Hashtable)); Enforcement failures raise the appropriate exception, both reducing the amount of code and providing consistency in implementation.</li>
<li>Unit testing helpers. A series of classes, based upon reflection that can automatically test classes and their properties. (Inspired by <a href="http://www.codeplex.com/classtester" rel="nofollow noreferrer">Automatic Class Tester</a> from CodePlex) but written from the ground up. Helps to simplify the creation of unit tests for things that are traditionally hard or time-consuming to test.</li>
</ul>
<p>We have also outright adopted some other functionality, as is. For example, we are using <a href="http://postsharp.org" rel="nofollow noreferrer">PostSharp</a> for AOP, <a href="http://code.google.com/p/moq" rel="nofollow noreferrer">moq</a> for mocking, and <a href="http://code.google.com/p/autofac/" rel="nofollow noreferrer">autofaq</a> for DI.</p>
<p>Just wondering what other people might have done and what concerns your framework addresses that you did not find tooling that you were satisfied with? As for our experience, we are definitely reaping the benefits of the new framework and are content with the approach that we have taken.</p>
| [
{
"answer_id": 347604,
"author": "Andreas Hausladen",
"author_id": 44005,
"author_profile": "https://Stackoverflow.com/users/44005",
"pm_score": 5,
"selected": true,
"text": "var\n MySet: set of Byte;\n Bytes: array of Byte;\nbegin\n MySet := [1, 2, 4, 8, 16];\n\n // Write\n Assert(ClientDataSet1MySet.DataSize >= SizeOf(MySet), 'Data field is too small');\n\n SetLength(Bytes, ClientDataSet1MySet.DataSize);\n Move(MySet, Bytes[0], SizeOf(MySet));\n ClientDataSet1.Edit;\n ClientDataSet1MySet.SetData(@Bytes[0]);\n ClientDataSet1.Post;\n\n // Read\n SetLength(Bytes, ClientDataSet1MySet.DataSize);\n if ClientDataSet1MySet.GetData(@Bytes[0]) then\n Move(Bytes[0], MySet, SizeOf(MySet))\n else\n MySet := []; // NULL\nend;\n"
},
{
"answer_id": 350934,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 2,
"selected": false,
"text": "var\n States : TUpdateStatusSet; // Can be any set, I took this one from DB.pas unit\n SetAsAInteger: Integer;\n dbs: Pointer; // Here's the trick\nbegin\n States := [usModified, usInserted]; // Putting some content in that set\n dbs := @States;\n SetAsAInteger := PByte(dbs)^;\n //Once you got it, SetAsAInteger is just another ordinary integer variable.\n //Use it the way you like.\nend;\n var\n MSG: string;\n Inserted, Modified: string;\n States: TUpdateStatusSet;\n MySet: Byte;\n\nbegin\n while not ClientDataSet.Eof do\n begin\n //That's the part that interest us\n //Convert that integer you stored in the database or whatever \n //place to a Byte and, in the sequence, to your set type.\n iSet := Byte(ClientDatasetMyIntegerField);// Sets are one byte, so they\n // fit on a byte variable \n States := TUpdateStatusSet(iSet);\n //Conversion finished, below is just interface stuff\n\n\n if usInserted in States then\n Inserted := 'Yes';\n if usModified in States then\n Modified := 'Yes';\n MSG := Format('Register Num: %d. Inserted: %s. Modified:%s',\n [ClientDataSet.RecNo, Inserted, Alterted]);\n ShowMessage( MSG );\n ClientDataset.Next;\n end;\n\nend;\n"
},
{
"answer_id": 20395170,
"author": "Roeland Van Heddegem",
"author_id": 1140659,
"author_profile": "https://Stackoverflow.com/users/1140659",
"pm_score": 0,
"selected": false,
"text": "var\n MySet: set of Byte;\n Bytes: TBytes;\nbegin\n MySet := [0];\n\n // Write\n Assert(ClientDataSet1Test.DataSize >= SizeOf(MySet), 'Data field is too small');\n\n SetLength(Bytes, ClientDataSet1Test.DataSize);\n Move(MySet, Bytes[0], SizeOf(MySet));\n ClientDataSet1.Edit;\n ClientDataSet1Test.AsBytes := Bytes;\n ClientDataSet1.Post;\nend;\n var\n MyResultSet: set of Byte;\nbegin\n Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize);\nend;\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15906/"
] |
347,614 | <p>For a WPF application which will need 10 - 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go?</p>
<p>If so, how do I specify in XAML that an Image control should load the image from an embedded resource?</p>
| [
{
"answer_id": 347805,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 6,
"selected": false,
"text": "<Image Source=\"..\\Media\\Image.png\" />\n"
},
{
"answer_id": 606986,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 10,
"selected": true,
"text": "Image BitmapSource <BitmapImage x:Key=\"MyImageSource\" UriSource=\"../Media/Image.png\" />\n <Image Source=\"{StaticResource MyImageSource}\" />\n Image.png Resource Content"
},
{
"answer_id": 2416464,
"author": "Nuno Rodrigues",
"author_id": 109912,
"author_profile": "https://Stackoverflow.com/users/109912",
"pm_score": 8,
"selected": false,
"text": "<Image Source=\"/WPFApplication;component/Images/Start.png\" />\n"
},
{
"answer_id": 4985459,
"author": "Craig",
"author_id": 615222,
"author_profile": "https://Stackoverflow.com/users/615222",
"pm_score": 6,
"selected": false,
"text": "doGetImageSourceFromResource (\"[YourAssemblyNameHere]\", \"[YourResourceNameHere]\");\n static internal ImageSource doGetImageSourceFromResource(string psAssemblyName, string psResourceName)\n{\n Uri oUri = new Uri(\"pack://application:,,,/\" +psAssemblyName +\";component/\" +psResourceName, UriKind.RelativeOrAbsolute);\n return BitmapFrame.Create(oUri);\n}\n"
},
{
"answer_id": 7158723,
"author": "JoanComasFdz",
"author_id": 383129,
"author_profile": "https://Stackoverflow.com/users/383129",
"pm_score": 3,
"selected": false,
"text": "<BitmapImage x:Key=\"MyImageSource\" UriSource=\"Resources/Image.png\" />\n"
},
{
"answer_id": 9737958,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 6,
"selected": false,
"text": "Freq.png Icons Resource this.Icon = new BitmapImage(new Uri(@\"pack://application:,,,/\" \n + Assembly.GetExecutingAssembly().GetName().Name \n + \";component/\" \n + \"Icons/Freq.png\", UriKind.Absolute)); \n /// <summary>\n/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.\n/// </summary>\n/// <param name=\"pathInApplication\">Path without starting slash</param>\n/// <param name=\"assembly\">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>\n/// <returns></returns>\npublic static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)\n{\n if (assembly == null)\n {\n assembly = Assembly.GetCallingAssembly();\n }\n\n if (pathInApplication[0] == '/')\n {\n pathInApplication = pathInApplication.Substring(1);\n }\n return new BitmapImage(new Uri(@\"pack://application:,,,/\" + assembly.GetName().Name + \";component/\" + pathInApplication, UriKind.Absolute)); \n}\n this.Icon = ResourceHelper.LoadBitmapFromResource(\"Icons/Freq.png\");\n pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml"
},
{
"answer_id": 27851170,
"author": "Raghulan Gowthaman",
"author_id": 1751602,
"author_profile": "https://Stackoverflow.com/users/1751602",
"pm_score": -1,
"selected": false,
"text": " var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),\n IntPtr.Zero,\n Int32Rect.Empty,\n BitmapSizeOptions.FromEmptyOptions());\n MyButton.Background = new ImageBrush(bitmapSource);\nimg_username.Source = bitmapSource;\n"
},
{
"answer_id": 49999778,
"author": "Sanjay Ranavaya",
"author_id": 9097210,
"author_profile": "https://Stackoverflow.com/users/9097210",
"pm_score": 2,
"selected": false,
"text": "<StackPanel Orientation=\"Horizontal\">\n <CheckBox Content=\"{Binding Nname}\" IsChecked=\"{Binding IsChecked}\"/>\n <Image Source=\"E:\\SWorking\\SharePointSecurityApps\\SharePointSecurityApps\\SharePointSecurityApps.WPF\\Images\\sitepermission.png\"/>\n <TextBlock Text=\"{Binding Path=Title}\"></TextBlock>\n</StackPanel>\n"
},
{
"answer_id": 72454323,
"author": "datchung",
"author_id": 4856020,
"author_profile": "https://Stackoverflow.com/users/4856020",
"pm_score": 0,
"selected": false,
"text": "Images MyImage.png Images MyImage.png Build Action Resource MainResourceDictionary.xaml <ResourceDictionary\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <BitmapImage x:Key=\"MyImageSource\" UriSource=\"Images/MyImage.png\" />\n</ResourceDictionary>\n <UserControl ...>\n <UserControl.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"MainResourceDictionary.xaml\" />\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n </UserControl.Resources>\n ...\n <UserControl ...>\n <UserControl.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"MainResourceDictionary.xaml\" />\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n </UserControl.Resources>\n ...\n <Image Source=\"{DynamicResource ResourceKey=ServiceLevel1Source}\" />\n ...\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13627/"
] |
347,617 | <p>I have a string that has angle brackets in it like this:</p>
<pre><code><element1>my text here</element1>
</code></pre>
<p>The string literally looks like this when I write it to console or my dataGridView or anywhere else. However, I'm trying to write this as part of an XML document. </p>
<p>Everything is fine except that in the xml file that is written, the above shows up as:</p>
<pre><code>&lt;element1&gt;my text here&lt;/element1&gt;
</code></pre>
<p>How do I get this to write out as my literal text instead of with the codes?</p>
<p>Thanks!</p>
<p>-Adeena</p>
| [
{
"answer_id": 347651,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<xml><![CDATA[<element1>my text here</element1>]]></xml>\n"
},
{
"answer_id": 347752,
"author": "kdgregory",
"author_id": 42126,
"author_profile": "https://Stackoverflow.com/users/42126",
"pm_score": 2,
"selected": false,
"text": "<container><element1>my text here</element1></container>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44004/"
] |
347,620 | <p>How do I find out which directories are responsible for chewing up all my inodes?</p>
<p>Ultimately the root directory will be responsible for the largest number of inodes, so I'm not sure exactly what sort of answer I want..</p>
<p>Basically, I'm running out of available inodes and need to find a unneeded directory to cull.</p>
<p>Thanks, and sorry for the vague question.</p>
| [
{
"answer_id": 347633,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 5,
"selected": true,
"text": "find . -type d -print0 | xargs -0 -n1 count_files | sort -n\n echo $(ls -a \"$1\" | wc -l) $1\n"
},
{
"answer_id": 347700,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/perl -w\n\nuse strict;\n\nsub count_inodes($);\nsub count_inodes($)\n{\n my $dir = shift;\n if (opendir(my $dh, $dir)) {\n my $count = 0;\n while (defined(my $file = readdir($dh))) {\n next if ($file eq '.' || $file eq '..');\n $count++;\n my $path = $dir . '/' . $file;\n count_inodes($path) if (-d $path);\n }\n closedir($dh);\n printf \"%7d\\t%s\\n\", $count, $dir;\n } else {\n warn \"couldn't open $dir - $!\\n\";\n }\n}\n\npush(@ARGV, '.') unless (@ARGV);\nwhile (@ARGV) {\n count_inodes(shift);\n}\n du return $count $count += count_inodes($path) if (-d $path);\n"
},
{
"answer_id": 8954671,
"author": "Hannes",
"author_id": 1162525,
"author_profile": "https://Stackoverflow.com/users/1162525",
"pm_score": 7,
"selected": false,
"text": "for i in `find . -type d `; do echo `ls -a $i | wc -l` $i; done | sort -n\n"
},
{
"answer_id": 14391775,
"author": "insider",
"author_id": 1166912,
"author_profile": "https://Stackoverflow.com/users/1166912",
"pm_score": 6,
"selected": false,
"text": "cd /partition_that_is_out_of_inodes\nfor i in *; do echo -e \"$(find $i | wc -l)\\t$i\"; done | sort -n\n"
},
{
"answer_id": 20952025,
"author": "Romuald Brunet",
"author_id": 286182,
"author_profile": "https://Stackoverflow.com/users/286182",
"pm_score": 2,
"selected": false,
"text": "find /path -type d -size +500k\n"
},
{
"answer_id": 20984776,
"author": "Noah Spurrier",
"author_id": 319432,
"author_profile": "https://Stackoverflow.com/users/319432",
"pm_score": 4,
"selected": false,
"text": "for ii in $(find . -maxdepth 1 -type d); do \n echo -e \"${ii}\\t$(find \"${ii}\" -type l -o -type d -o -type f | wc -l)\"\ndone | sort -n -k 2 | column -t\n # cd /\n# for ii in $(find -maxdepth 1 -type d); do echo -e \"${ii}\\t$(find \"${ii}\" -type l -o -type d -o -type f | wc -l)\"; done | sort -n -k 2 | column -t\n./boot 1\n./lost+found 1\n./media 1\n./mnt 1\n./opt 1\n./srv 1\n./lib64 2\n./tmp 5\n./bin 107\n./sbin 109\n./home 146\n./root 169\n./dev 188\n./run 226\n./etc 1545\n./var 3611\n./sys 12421\n./lib 17219\n./proc 20824\n./usr 56628\n. 113207\n"
},
{
"answer_id": 26309724,
"author": "sanxiago",
"author_id": 4131171,
"author_profile": "https://Stackoverflow.com/users/4131171",
"pm_score": -1,
"selected": false,
"text": "find / -type f | grep -oP '^/([^/]+/){3}' | sort | uniq -c | sort -n"
},
{
"answer_id": 28310430,
"author": "CO4 Computing",
"author_id": 3097726,
"author_profile": "https://Stackoverflow.com/users/3097726",
"pm_score": 0,
"selected": false,
"text": "find . -type f -delete\n"
},
{
"answer_id": 30531027,
"author": "Sam Critchley",
"author_id": 645042,
"author_profile": "https://Stackoverflow.com/users/645042",
"pm_score": 4,
"selected": false,
"text": " root@polo:/# df -i\n Filesystem Inodes IUsed IFree IUse% Mounted on\n /dev/xvda1 524288 427294 96994 81% /\n none 256054 2 256052 1% /sys/fs/cgroup\n udev 254757 404 254353 1% /dev\n tmpfs 256054 332 255722 1% /run\n none 256054 3 256051 1% /run/lock\n none 256054 1 256053 1% /run/shm\n none 256054 3 256051 1% /run/user\n root@polo:/# find / -xdev -printf '%h\\n' | sort | uniq -c | sort -k 1 -n\n [...]\n 1088 /usr/src/linux-headers-3.13.0-39/include/linux\n 1375 /usr/src/linux-headers-3.13.0-29-generic/include/config\n 1377 /usr/src/linux-headers-3.13.0-39-generic/include/config\n 2727 /var/lib/dpkg/info\n 2834 /usr/share/man/man3\n 416811 /var/lib/php5/session\n root@polo:/#\n root@polo:/var/lib/php5/session# find ./ -cmin +1440 | xargs rm\nroot@polo:/var/lib/php5/session#\n root@polo:~# find / -xdev -printf '%h\\n' | sort | uniq -c | sort -k 1 -n\n [...]\n 1088 /usr/src/linux-headers-3.13.0-39/include/linux\n 1375 /usr/src/linux-headers-3.13.0-29-generic/include/config\n 1377 /usr/src/linux-headers-3.13.0-39-generic/include/config\n 2727 /var/lib/dpkg/info\n 2834 /usr/share/man/man3\n 2886 /var/lib/php5/session\n root@polo:~# df -i\n Filesystem Inodes IUsed IFree IUse% Mounted on\n /dev/xvda1 524288 166420 357868 32% /\n none 256054 2 256052 1% /sys/fs/cgroup\n udev 254757 404 254353 1% /dev\n tmpfs 256054 332 255722 1% /run\n none 256054 3 256051 1% /run/lock\n none 256054 1 256053 1% /run/shm\n none 256054 3 256051 1% /run/user\n root@polo:~#\n"
},
{
"answer_id": 36046072,
"author": "AnrDaemon",
"author_id": 1449366,
"author_profile": "https://Stackoverflow.com/users/1449366",
"pm_score": 2,
"selected": false,
"text": "-xdev find / -xdev -type d | while read -r i; do printf \"%d %s\\n\" $(ls -a \"$i\" | wc -l) \"$i\"; done | sort -nr | head -10 find / -xdev -type d -size +100k"
},
{
"answer_id": 39379847,
"author": "jarno",
"author_id": 4414935,
"author_profile": "https://Stackoverflow.com/users/4414935",
"pm_score": 0,
"selected": false,
"text": "d=2; find . -mount -not -path . -print0 | gawk '\nBEGIN{RS=\"\\0\";FS=\"/\";SUBSEP=\"/\";ORS=\"\\0\"}\n{\n s=\"./\"\n for(i=2;i!=d+1 && i<NF;i++){s=s $i \"/\"}\n ++n[s]\n}\nEND{for(val in n){print n[val] \"\\t\" val \"\\n\"}}' d=\"$d\" \\\n | sort -gz -k 1,1\n #!/bin/bash\nd=$1\ndeclare -A n\n\nwhile IFS=/ read -d $'\\0' -r -a a; do\n s=\"./\"\n for ((i=2; i!=$((d+1)) && i<${#a[*]}; i++)); do\n s+=\"${a[$((i-1))]}/\"\n done\n ((++n[\\$s]))\ndone < <(find . -mount -not -path . -print0)\n\nfor j in \"${!n[@]}\"; do\n printf '%i\\t%s\\n\\0' \"${n[$j]}\" \"$j\"\ndone | sort -gz -k 1,1 \n"
},
{
"answer_id": 46448852,
"author": "LPby",
"author_id": 2725563,
"author_profile": "https://Stackoverflow.com/users/2725563",
"pm_score": 1,
"selected": false,
"text": "ncdu -x <path>\n"
},
{
"answer_id": 62229027,
"author": "Thomas Urban",
"author_id": 3182819,
"author_profile": "https://Stackoverflow.com/users/3182819",
"pm_score": 1,
"selected": false,
"text": "du du -hs /*\n du -hs /var/*\n du -s --inodes /*\n"
},
{
"answer_id": 70968885,
"author": "SergeiMinaev",
"author_id": 5992036,
"author_profile": "https://Stackoverflow.com/users/5992036",
"pm_score": 2,
"selected": false,
"text": "du --inodes --separate-dirs --one-file-system | sort -rh | head du --inodes -Sx | sort -rh | head --one-file-system"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31092/"
] |
347,624 | <p>I have a simple problem when querying the SQL Server 2005 database. I have tables called Customer and Products (1->M). One customer has most 2 products. Instead of output as</p>
<p>CustomerName, ProductName ...</p>
<p>I like to output as </p>
<p>CustomerName, Product1Name, Product2Name ...</p>
<p>Could anybody help me?</p>
<p>Thanks!</p>
| [
{
"answer_id": 347673,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 4,
"selected": true,
"text": "USE AdventureWorks;\nGO\n\nDECLARE @columns NVARCHAR(MAX);\n\nSELECT x.ProductName\nINTO #products\nFROM (SELECT p.[Name] AS ProductName\n FROM Purchasing.Vendor AS v\n INNER JOIN Purchasing.PurchaseOrderHeader AS poh ON v.VendorID = poh.VendorID\n INNER JOIN Purchasing.PurchaseOrderDetail AS pod ON poh.PurchaseOrderID = pod.PurchaseOrderID\n INNER JOIN Production.Product AS p ON pod.ProductID = p.ProductID\n GROUP BY p.[Name]) AS x;\n\nSELECT @columns = STUFF(\n (SELECT ', ' + QUOTENAME(ProductName, '[') AS [text()]\n FROM #products FOR XML PATH ('')\n ), 1, 1, '');\n\nSELECT @columns;\n DECLARE @sql NVARCHAR(MAX);\n\nSET @sql = 'SELECT CustomerName, ' + @columns + '\nFROM (\n // your query goes here\n) AS source\nPIVOT (SUM(order_count) FOR product_name IN (' + @columns + ') AS p';\n\nEXEC sp_executesql @sql\n"
},
{
"answer_id": 348463,
"author": "Jamal Hansen",
"author_id": 2035722,
"author_profile": "https://Stackoverflow.com/users/2035722",
"pm_score": 1,
"selected": false,
"text": "Select \n Customer,\n Sum(Case When Product = 'Foo' Then 1 Else 0 End) Foo_Count,\n Sum(Case When Product = 'Bar' Then 1 Else 0 End) Bar_Count\nFrom Customers_Products\nGroup By Customer\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31689/"
] |
347,625 | <p>What do you recommend as minimum specs for a Windows laptop running Vista, an IDE, and Apache, MySQL, and PHP?</p>
| [
{
"answer_id": 347673,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 4,
"selected": true,
"text": "USE AdventureWorks;\nGO\n\nDECLARE @columns NVARCHAR(MAX);\n\nSELECT x.ProductName\nINTO #products\nFROM (SELECT p.[Name] AS ProductName\n FROM Purchasing.Vendor AS v\n INNER JOIN Purchasing.PurchaseOrderHeader AS poh ON v.VendorID = poh.VendorID\n INNER JOIN Purchasing.PurchaseOrderDetail AS pod ON poh.PurchaseOrderID = pod.PurchaseOrderID\n INNER JOIN Production.Product AS p ON pod.ProductID = p.ProductID\n GROUP BY p.[Name]) AS x;\n\nSELECT @columns = STUFF(\n (SELECT ', ' + QUOTENAME(ProductName, '[') AS [text()]\n FROM #products FOR XML PATH ('')\n ), 1, 1, '');\n\nSELECT @columns;\n DECLARE @sql NVARCHAR(MAX);\n\nSET @sql = 'SELECT CustomerName, ' + @columns + '\nFROM (\n // your query goes here\n) AS source\nPIVOT (SUM(order_count) FOR product_name IN (' + @columns + ') AS p';\n\nEXEC sp_executesql @sql\n"
},
{
"answer_id": 348463,
"author": "Jamal Hansen",
"author_id": 2035722,
"author_profile": "https://Stackoverflow.com/users/2035722",
"pm_score": 1,
"selected": false,
"text": "Select \n Customer,\n Sum(Case When Product = 'Foo' Then 1 Else 0 End) Foo_Count,\n Sum(Case When Product = 'Bar' Then 1 Else 0 End) Bar_Count\nFrom Customers_Products\nGroup By Customer\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,636 | <p>I create a TCP socket without bothering about the port number to bind to [socket.sin_port = 0]. However later on if I want to print the port number of client how do I do that? The client C application (on Linux) creates many clients which get connected to server. To debug issues I capture the traffic on ethereal. I thought of printing the port number in logs while issue arises so that filtering on ethereal becomes easy. </p>
<p>Any help would be appreciated.</p>
<p>-Prabhu</p>
| [
{
"answer_id": 347709,
"author": "D.Shawley",
"author_id": 41747,
"author_profile": "https://Stackoverflow.com/users/41747",
"pm_score": 2,
"selected": false,
"text": "getsockname() connect() bind() getpeername() man sockstat grep"
},
{
"answer_id": 347882,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 0,
"selected": false,
"text": "lsof -p <process id> | grep TCP\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,642 | <p>I have a problem. One of the datatable colums value is a string value '001200' for example. When the Excel document creats the value became '1200'. How can I keep a data format as is? I'm working with ASP.NET 1.1.</p>
<p>The part of the code is:</p>
<pre><code>private void lnkExport_Click( object sender, System.EventArgs e )
{
Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader( "Content-Disposition", "attachment; filename=" + "CartsList.xls" );
Response.Charset = "iso-8859-8";
Response.Cache.SetCacheability( HttpCacheability.Public );
Response.ContentEncoding = System.Text.Encoding.UTF7;
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter( oStringWriter );
this.ClearControls( dtgCarts );
dtgCarts.RenderControl( oHtmlTextWriter );
Response.Write( oStringWriter.ToString() );
Response.End();
}
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 347650,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 0,
"selected": false,
"text": "'001200\n"
},
{
"answer_id": 1973337,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 1,
"selected": false,
"text": "<style> .text { mso-number-format:\\@; } </style> \n"
},
{
"answer_id": 6039972,
"author": "Robert Tyson ",
"author_id": 705357,
"author_profile": "https://Stackoverflow.com/users/705357",
"pm_score": 0,
"selected": false,
"text": "// Open template\nstring xlfile = @\"d:\\prj\\HrePro.xlsx\";\nExcelWorkbook Wbook = ExcelWorkbook.ReadXLSX(xlfile);\nExcelCellCollection Cells = Wbook.Worksheets.Add(\"Sheet1\").Cells;\n\n// Save values and excel file\nCells[\"b2\"].Value = \"001\";\nCells[\"b2\"].Style.StringFormat = DefinedFormats.Textual;\n\nWbook.WriteXLSX(@\"d:\\prj\\HReport.xlsx\");\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,656 | <p>I have a table of data sorted by date, from which a user can select a set of data by supplying a start and end date. The data itself is non-continuous, in that I don't have data for weekends and public holidays. </p>
<p>I would like to be able to list all the days that I don't have data for in the extracted dataset. Is there an easy way, in Java, to go:</p>
<ol>
<li>Here is an ordered array of dates. </li>
<li>This is the selected start date. (The first date in the array is not always the start date)</li>
<li>This is the selected end date. (The last date in the array is not always the end date)</li>
<li>Return a list of dates which have no data.</li>
</ol>
| [
{
"answer_id": 347688,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 3,
"selected": true,
"text": "dates = [...]; // list you have now;\n\n// build list\nunused = [];\nfor (Date i = startdate; i < enddate; i += day) {\n unused.push(i);\n}\n\n// remove used dates\nfor (int j = 0; j < dates.length; j += 1) {\n if (unused.indexOf((Date) dates[j]) > -1) { // time = 00:00:00\n unused.remove(unused.indexOf((Date) dates[j]));\n }\n}\n"
},
{
"answer_id": 347744,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "# given - array of given dates\n# N - number of dates in given array\n# missing - array of dates missing\n\ni = 0; # Index into given date array\nj = 0; # Index into missing data array\nfor (current_date = start_date; current_date <= end_date; current_date++)\n{\n while (given[i] < current_date && i < N)\n i++\n if (i >= N)\n break\n if (given[i] != current_date)\n missing[j++] = current_date\n}\nwhile (current_date < end_date)\n{\n missing[j++] = current_date\n current_date++\n}\n date + 1 date++ date"
},
{
"answer_id": 347768,
"author": "P Arrayah",
"author_id": 33459,
"author_profile": "https://Stackoverflow.com/users/33459",
"pm_score": 0,
"selected": false,
"text": "protected List<Calendar> getDatesWithNoData(Calendar start, Calendar end,\n Calendar[] existingDates) throws ParseException {\n\n List<Calendar> missingData = new ArrayList<Calendar>();\n\n for(Calendar c=start ; c.compareTo(end)<=0 ; c.roll(Calendar.DAY_OF_MONTH, true) ) {\n\n if(!isInDataSet(c, existingDates)) {\n Calendar c2 = Calendar.getInstance();\n c2.setTimeInMillis(c.getTimeInMillis());\n\n missingData.add(c2);\n }\n }\n return missingData;\n}\n\nprotected boolean isInDataSet(Calendar toSearch, Calendar[] dataSet) {\n for(Calendar l : dataSet) {\n if(toSearch.equals(l)) return true;\n }\n return false;\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3410/"
] |
347,659 | <p>I looked at SQL Server dateformat codes but I couldn't find dd.mm.yyyy hh:mm format in the list. German Date Format(Code is 4) works for me but it doesn't contain hh:mm. Does someone know this format's code?</p>
| [
{
"answer_id": 347670,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "CONVERT(varchar,[datefield],104)\n + ' '\n + SUBSTRING(CONVERT(varchar,[datefield],108),1,5)\n"
},
{
"answer_id": 2628171,
"author": "Herz Garlan",
"author_id": 315279,
"author_profile": "https://Stackoverflow.com/users/315279",
"pm_score": 0,
"selected": false,
"text": "select CONVERT(varchar,getdate(),101)\n + ' ' + SUBSTRING(CONVERT(varchar,getdate(),108),1,5) + ' '\n + SUBSTRING(CONVERT(varchar,getdate(),109),25,2)\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,661 | <p>How would I handle something like the below uri using ASP.NET MVC's routing capability:</p>
<pre><code>http://localhost/users/{username}/bookmarks/ - GET
http://localhost/users/{username}/bookmark/{bookmarkid} - PUT
</code></pre>
<p>Which lists the bookmarks for the user in {username}.</p>
<p>Thanks</p>
| [
{
"answer_id": 347726,
"author": "Pablo Retyk",
"author_id": 30729,
"author_profile": "https://Stackoverflow.com/users/30729",
"pm_score": 3,
"selected": true,
"text": "routes.MapRoute(\"Bookmarks\", \"{controller}/{user}/{action}/{id}\");\n public class UsersController : Controller\n{\n [AcceptVerbs(\"Post\")]\n public void Bookmarks(string user, int? id)\n {\n\n //add your bookmark\n }\n}\n"
},
{
"answer_id": 348671,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 3,
"selected": false,
"text": "public class BookmarksController : Controller\n{\n [AcceptVerbs(HttpVerbs.Get)]\n public void Bookmarks(string user)\n {\n\n //add your bookmark\n }\n\n [AcceptVerbs(HttpVerbs.Post)]\n public void Bookmarks(string user, int? id)\n {\n\n //add your bookmark\n }\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33764/"
] |
347,664 | <p>Is it possible to use something like:</p>
<pre><code>require 'serialport.o'
</code></pre>
<p>with Shoes? serialport.o is compiled c code as a ruby extension.</p>
<p>When I attempt to run the following code in shoes, I see no visible output to the screen and shoes crashes on OS X.</p>
<p>Thank you</p>
<p>CODE:</p>
<pre><code>require "serialport.o"
port = "/dev/tty.usbserial-A1001O0o"
sp = SerialPort.new( port, 9600, 8, 1, SerialPort::NONE)
Shoes.app :width => 300, :height => 150, :margin => 10 do
button "On" do
sp.write( "1" )
end
end
sp.close
</code></pre>
| [
{
"answer_id": 347701,
"author": "Moss Collum",
"author_id": 13210,
"author_profile": "https://Stackoverflow.com/users/13210",
"pm_score": 1,
"selected": false,
"text": "require \"serialport.o\"\n\nport = \"/dev/tty.usbserial-A1001O0o\"\nsp = SerialPort.new( port, 9600, 8, 1, SerialPort::NONE)\nsp.write( \"1\" )\nsp.close\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,675 | <p>I have a class like this:</p>
<pre><code>public class myClass
{
public List<myOtherClass> anewlist = new List<myOtherClass>;
public void addToList(myOtherClass tmp)
{
anewList.Add(tmp);
}
}
</code></pre>
<p>So I call "addToList" a hundred times, each adding a unique item to the list. I've tested my items to show that before I run the "addToList" method, they are unique. I even put a line in to test "tmp" to make sure it was what I was expecting.</p>
<p>However, when I do this (lets say myClass object is called tmpClass):</p>
<pre><code>int i = tmpClass.anewList.Count();
for (int j = 0; j<i; j++)
{
//write out each member of the list based on index j...
}
</code></pre>
<p>I get the same exact item, and it's the last one that was written into my list. It's as if when I add, I'm overwriting the entire list with the last item I've added. </p>
<p>Help? This makes no sense.
I've also tried List.Insert, where I'm always inserting at the end or at index 0. Still no dice. Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.</p>
<p>:)</p>
<p>UPDATE:
Okay, I tried this and still had the same problem:</p>
<pre><code>foreach(myOtherClass tmpC in tmpClass.anewList)
{
Console.WriteLine(tmpC.theStringInMyClass.ToString());
}
</code></pre>
<p>and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.</p>
<p>-Adeena</p>
<hr>
<p>Okay, I tried this and still had the same problem:</p>
<pre><code>foreach(myOtherClass tmpC in tmpClass.anewList)
{
Console.WriteLine(tmpC.theStringInMyClass.ToString());
}
</code></pre>
<p>and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.</p>
<p>-Adeena</p>
| [
{
"answer_id": 347679,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "foreach (MyOtherClass item in tmpClass.anewList)\n{\n Console.WriteLine( item ); // or whatever you use to write it\n}\n .Count .Count()"
},
{
"answer_id": 347685,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": " for (int j = 0; j < tmpClass.anewList.Count(); j++)\n"
},
{
"answer_id": 347689,
"author": "James",
"author_id": 41039,
"author_profile": "https://Stackoverflow.com/users/41039",
"pm_score": 2,
"selected": false,
"text": "foreach anewList public"
},
{
"answer_id": 347702,
"author": "vt100",
"author_id": 27616,
"author_profile": "https://Stackoverflow.com/users/27616",
"pm_score": 5,
"selected": true,
"text": "public void addToList(myOtherClass tmp)\n {\n anewList.Add(tmp);\n }\n myOtherClass item = new myOtherClass();\n\nfor(int i=0; i < 100; i++)\n{\n item.Property = i;\n addToList(item);\n}\n myOtherClass item = null;\nfor(int i=0; i < 100; i++)\n{\n item = new myOtherClass();\n item.Property = i;\n addToList(item);\n}\n"
},
{
"answer_id": 347712,
"author": "adeena",
"author_id": 44004,
"author_profile": "https://Stackoverflow.com/users/44004",
"pm_score": 0,
"selected": false,
"text": "myClass tmpClass = new myClass();\nmyOtherClass anewitem = new myOtherClass();\nstring tst = \"\";\n\nfor (int i = 0; i < 100; i++) \n{\n tst += \"blah\";\n anewitem.theStirngInMyClass = tst;\n tmpClass.AddToList(anewitem);\n}\n myClass tmpClass = new myClass();\nstring tst = \"\";\n\nfor (int i = 0; i < 100; i++) \n{\n myOtherClass anewitem = new myOtherClass()\n tst += \"blah\";\n anewitem.theStringInMyClass = tst;\n tmpClass.AddToList(tst);\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44004/"
] |
347,690 | <p>Does any of you have a clue how to alter the contents of <code>Security.framework/TrustStore.sqlite3</code>. It seems as if the iPhone uses it to store trusted CA certificates. I really want my iPod touch to trust my custom certificate. Beside that, does anyone of you know an app (win32) to edit sqlite3 database files (except sqliteman, this one always crashes for me).</p>
| [
{
"answer_id": 45053184,
"author": "Patrik",
"author_id": 242026,
"author_profile": "https://Stackoverflow.com/users/242026",
"pm_score": 1,
"selected": false,
"text": "/System/Library/Security/Certificates.bundle /System/Library/Frameworks/Security.framework"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44107/"
] |
347,703 | <p>I made an array in PHP which holds a bucnh of unix timestamps.</p>
<p>I'm trying to make a function that will return an array containing the indexes of the 3 largest numbers in that array.</p>
<p>For instance, if the largest numbers are located at indexes 3,5 and 8</p>
<p>And if the largest is 5, second largest is 8 and smallest of the three is number 3, I want an array that holds the values (5,8,3) in that order.</p>
<p>And frankly, I don't have a clue how to pull this off. Does anybody know how to do this?</p>
| [
{
"answer_id": 347722,
"author": "mepcotterell",
"author_id": 43312,
"author_profile": "https://Stackoverflow.com/users/43312",
"pm_score": 0,
"selected": false,
"text": "function select(list[1..n], k)\n for i from 1 to k\n maxIndex = i\n maxValue = list[i]\n for j from i+1 to n\n if list[j] > maxValue\n maxIndex = j\n maxValue = list[j]\n swap list[i] and list[maxIndex]\n return list[k]\n\nnewarray[] = select(array, 1);\nnewarray[] = select(array, 2);\nnewarray[] = select(array, 3);\n"
},
{
"answer_id": 347790,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": -1,
"selected": false,
"text": "function threeLargest($array){\n krsort($array, \"SORT_NUMERIC\");\n $return[0] = $array[0];\n $return[1] = $array[1];\n $return[2] = $array[2];\n return $return;\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
347,721 | <p>I'm looking to perform a perspective transform on a UIView (such as seen in coverflow)</p>
<p>Does anyonew know if this is possible? </p>
<p>I've investigated using <code>CALayer</code> and have run through all the pragmatic programmer Core Animation podcasts, but I'm still no clearer on how to create this kind of transform on an iPhone.</p>
<p>Any help, pointers or example code snippets would be really appreciated!</p>
| [
{
"answer_id": 353611,
"author": "Brad Larson",
"author_id": 19679,
"author_profile": "https://Stackoverflow.com/users/19679",
"pm_score": 9,
"selected": true,
"text": "UIView's CATransform3D layer's rotation cells CATransform3D UIView *myView = [[self subviews] objectAtIndex:0];\nCALayer *layer = myView.layer;\nCATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;\nrotationAndPerspectiveTransform.m34 = 1.0 / -500;\nrotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);\nlayer.transform = rotationAndPerspectiveTransform;\n if let myView = self.subviews.first {\n let layer = myView.layer\n var rotationAndPerspectiveTransform = CATransform3DIdentity\n rotationAndPerspectiveTransform.m34 = 1.0 / -500\n rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)\n layer.transform = rotationAndPerspectiveTransform\n}\n CALayers sublayerTransform UIView's CALayer CALayers"
},
{
"answer_id": 47924259,
"author": "Sunil M.",
"author_id": 7348569,
"author_profile": "https://Stackoverflow.com/users/7348569",
"pm_score": -1,
"selected": false,
"text": " override func viewDidLoad() {\n super.viewDidLoad()\n let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))\n carousel.dataSource = self\n carousel.type = .coverFlow\n view.addSubview(carousel) \n }\n\n func numberOfItems(in carousel: iCarousel) -> Int {\n return 10\n }\n\n func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {\n let imageView: UIImageView\n\n if view != nil {\n imageView = view as! UIImageView\n } else {\n imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))\n }\n\n imageView.image = UIImage(named: \"example\")\n\n return imageView\n }\n"
},
{
"answer_id": 65978405,
"author": "Amir Ardalan",
"author_id": 4316042,
"author_profile": "https://Stackoverflow.com/users/4316042",
"pm_score": 0,
"selected": false,
"text": "func makeTransform(horizontalDegree: CGFloat, verticalDegree: CGFloat, maxVertical: CGFloat,rotateDegree: CGFloat, maxHorizontal: CGFloat) -> CATransform3D {\n var transform = CATransform3DIdentity\n \n transform.m34 = 1 / -500\n \n let xAnchor = (horizontalDegree / (2 * maxHorizontal)) + 0.5\n let yAnchor = (verticalDegree / (-2 * maxVertical)) + 0.5\n let anchor = CGPoint(x: xAnchor, y: yAnchor)\n \n setAnchorPoint(anchorPoint: anchor, forView: self.imgView)\n let hDegree = (CGFloat(horizontalDegree) * .pi) / 180\n let vDegree = (CGFloat(verticalDegree) * .pi) / 180\n let rDegree = (CGFloat(rotateDegree) * .pi) / 180\n transform = CATransform3DRotate(transform, vDegree , 1, 0, 0)\n transform = CATransform3DRotate(transform, hDegree , 0, 1, 0)\n transform = CATransform3DRotate(transform, rDegree , 0, 0, 1)\n \n return transform\n}\n\nfunc setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {\n var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)\n var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)\n \n newPoint = newPoint.applying(view.transform)\n oldPoint = oldPoint.applying(view.transform)\n \n var position = view.layer.position\n position.x -= oldPoint.x\n position.x += newPoint.x\n \n position.y -= oldPoint.y\n position.y += newPoint.y\n \n print(\"Anchor: \\(anchorPoint)\")\n \n view.layer.position = position\n view.layer.anchorPoint = anchorPoint\n}\n var transform = makeTransform(horizontalDegree: 20.0 , verticalDegree: 25.0, maxVertical: 25, rotateDegree: 20, maxHorizontal: 25)\nimgView.layer.transform = transform\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221378/"
] |
347,724 | <p>I have a Page with a UserControl on it. If the user presses Esc while anywhere on Page I want to handle.</p>
<p>I thought this would be as easy as hooking up the PreviewKeyDown event, testing for the Esc key, and then handling it. However, when I placed I breakpoint in the event handler I found it was never getting called. I thought perhaps the UserControl might be getting hit, so I tried PreviewKeyDown there... same result.</p>
<p>Does anyone know the proper place to test for a KeyDown or PreviewKeyDown on a Page object?</p>
| [
{
"answer_id": 14887563,
"author": "Daniel",
"author_id": 84873,
"author_profile": "https://Stackoverflow.com/users/84873",
"pm_score": 6,
"selected": false,
"text": "KeyDown Window.GetWindow(this) <UserControl Loaded=\"UserControl_Loaded\">\n</UserControl>\n private void UserControl_Loaded(object sender, RoutedEventArgs e) {\n var window = Window.GetWindow(this);\n window.KeyDown += HandleKeyPress;\n}\n\nprivate void HandleKeyPress(object sender, KeyEventArgs e) {\n //Do work\n}\n"
},
{
"answer_id": 22282641,
"author": "alansiqueira27",
"author_id": 375422,
"author_profile": "https://Stackoverflow.com/users/375422",
"pm_score": 3,
"selected": false,
"text": "void GameScreen_Loaded(object sender, RoutedEventArgs e)\n{\n this.PreviewKeyDown += GameScreen_PreviewKeyDown;\n this.Focusable = true;\n this.Focus();\n}\n\nvoid GameScreen_PreviewKeyDown(object sender, KeyEventArgs e)\n{\n MessageBox.Show(\"it works!\"); \n}\n"
},
{
"answer_id": 25860481,
"author": "Jeff T.",
"author_id": 1613961,
"author_profile": "https://Stackoverflow.com/users/1613961",
"pm_score": 3,
"selected": false,
"text": "Window Window Window HandleKeyPress private void UserControl_Loaded(object sender, RoutedEventArgs e) {\n var window = Window.GetWindow(this);\n window.KeyDown += HandleKeyPress;\n}\n\nprivate void HandleKeyPress(object sender, KeyEventArgs e) {\n //Do work\n}\n += protected override void OnKeyDown(KeyEventArgs e)\n{\n base.OnKeyDown(e);\n\n // You need to have a reference to YourUserControlViewModel in the class.\n YourUserControlViewModel.CallKeyDown(e);\n\n // Or, if you don't like ViewModel, hold your user-control in the class then\n YourUserControl.CallKeyDown(e);\n}\n public void CallKeyDown(KeyEventArgs e) {\n //Do your work\n}\n"
},
{
"answer_id": 34572101,
"author": "user5739335",
"author_id": 5739335,
"author_profile": "https://Stackoverflow.com/users/5739335",
"pm_score": -1,
"selected": false,
"text": " Private Sub textbox1_PreviewKeyDown(sender As Object, e As KeyEventArgs) Handles textbox1_input.PreviewKeyDown\n If (e.Key = Key.Down) Then\n MessageBox.Show(\"It works.\")\n End If\n End Sub\n\n'detect key state directly with something like this below\n Dim x As KeyStates = System.Windows.Input.Keyboard.GetKeyStates(Key.Down)\n"
},
{
"answer_id": 39966947,
"author": "Janez Krnc",
"author_id": 4317660,
"author_profile": "https://Stackoverflow.com/users/4317660",
"pm_score": 2,
"selected": false,
"text": "var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();\n ElementHost.EnableModelessKeyboardInterop(wpfwindow);\n wpfwindow.Show();\n var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();\n ElementHost.EnableModelessKeyboardInterop(wpfwindow);\n wpfwindow.ShowDialog();\n void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)\n {\n switch (e.Key)\n {\n case Key.Escape:\n this.Close();\n break;\n case Key.Right:\n page_forward();\n break;\n case Key.Left:\n page_backward();\n break;\n }\n }\n"
},
{
"answer_id": 57181469,
"author": "Sracanis",
"author_id": 2851537,
"author_profile": "https://Stackoverflow.com/users/2851537",
"pm_score": 1,
"selected": false,
"text": "Weindow_KeyDown private void Window_KeyDown(object sender, KeyEventArgs e)\n {\n // ... Test for F1 key.\n if (e.Key == Key.F1)\n {\n this.Title = \"You pressed F1 key\";\n }\n }\n Weindow_KeyDown <Window x:Class=\"WpfApplication25.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\"\n KeyDown=\"Window_KeyDown\">\n</Window>\n"
},
{
"answer_id": 57648533,
"author": "Kevin",
"author_id": 8262633,
"author_profile": "https://Stackoverflow.com/users/8262633",
"pm_score": 2,
"selected": false,
"text": "IsVisibleChanged=\"Page_IsVisibleChanged\"\n private void Page_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if(this.Visibility == Visibility.Visible)\n {\n this.Focusable = true;\n this.Focus();\n }\n }\n"
},
{
"answer_id": 57656838,
"author": "Leo Kolezhuk",
"author_id": 4156298,
"author_profile": "https://Stackoverflow.com/users/4156298",
"pm_score": 1,
"selected": false,
"text": "public partial class MyControl : UserControl{\n\npublic MyControl()\n{\n MouseEnter+= MouseEnterHandler;\n MouseLeave+= MouseLeaveHandler;\n}\n\nprotected void MouseEnterHandler(object sender, MouseEventArgs e)\n{\n var view = sender as MyControl;\n view.KeyDown += HandleKeyPress;\n view.KeyUp += HandleKeyReleased;\n view.Focus();\n}\n\nprotected void MouseLeaveHandler(object sender, MouseEventArgs e)\n{\n var view = sender as MyControl;\n view.KeyDown -= HandleKeyPress;\n view.KeyUp -= HandleKeyReleased;\n}\n\nprotected void HandleKeyPress(object sender, KeyEventArgs e)\n{\n // What happens on key pressed\n}\n\nprotected void HandleKeyReleased(object sender, KeyEventArgs e)\n{\n // What happens on key released\n}\n\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42620/"
] |
347,734 | <p>I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use.
I have read about the <a href="http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm" rel="noreferrer">Gauss-Legendre Algorithm</a>, and I have tried porting it to Python with no success.</p>
<p>I am reading from <a href="http://www.geocities.com/hjsmithh/Pi/Gauss_L.html" rel="noreferrer">Here</a>, and I would appreciate any input as to where I am going wrong!</p>
<p>It outputs: 0.163991276262</p>
<pre><code>from __future__ import division
import math
def square(x):return x*x
a = 1
b = 1/math.sqrt(2)
t = 1/4
x = 1
for i in range(1000):
y = a
a = (a+b)/2
b = math.sqrt(b*y)
t = t - x * square((y-a))
x = 2* x
pi = (square((a+b)))/4*t
print pi
raw_input()
</code></pre>
| [
{
"answer_id": 347749,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 6,
"selected": true,
"text": "4*t pi = (a+b)**2 / (4*t)\n decimal #!/usr/bin/env python\nfrom __future__ import with_statement\nimport decimal\n\ndef pi_gauss_legendre():\n D = decimal.Decimal\n with decimal.localcontext() as ctx:\n ctx.prec += 2 \n a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1 \n pi = None\n while 1:\n an = (a + b) / 2\n b = (a * b).sqrt()\n t -= p * (a - an) * (a - an)\n a, p = an, 2*p\n piold = pi\n pi = (a + b) * (a + b) / (4 * t)\n if pi == piold: # equal within given precision\n break\n return +pi\n\ndecimal.getcontext().prec = 100\nprint pi_gauss_legendre()\n 3.141592653589793238462643383279502884197169399375105820974944592307816406286208\\\n 998628034825342117068\n"
},
{
"answer_id": 347758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "pi = (square((a+b)))/4*t\n pi = (square((a+b)))/(4*t)\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42584/"
] |
347,741 | <p>Why don't we get compile errors on inline code errors in asp.net mvc views f.eks</p>
<pre><code><h1><%= ViewData.Model.Title.Tostrig() %></h1>
</code></pre>
<p>The code above will build just fine. Wrong spelling in webform controls will give you an error so I can't see why this isn't supported in asp.net mvc</p>
<p>EDIT:
Luckily there seem to be a fix included in the first RC for asp.net mvc
<a href="http://weblogs.asp.net/scottgu/archive/2008/12/19/asp-net-mvc-design-gallery-and-upcoming-view-improvements-with-the-asp-net-mvc-release-candidate.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2008/12/19/asp-net-mvc-design-gallery-and-upcoming-view-improvements-with-the-asp-net-mvc-release-candidate.aspx</a></p>
| [
{
"answer_id": 347836,
"author": "Dan Atkinson",
"author_id": 31532,
"author_profile": "https://Stackoverflow.com/users/31532",
"pm_score": 4,
"selected": false,
"text": " C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_compiler -v / -p \"$(ProjectDir)\\\"\n C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_compiler -v / -p \"$(ProjectDir)\\\"\n"
},
{
"answer_id": 1484128,
"author": "user17060",
"author_id": 17060,
"author_profile": "https://Stackoverflow.com/users/17060",
"pm_score": 3,
"selected": false,
"text": " <PropertyGroup>\n <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n <MvcBuildViews>true</MvcBuildViews>\n </PropertyGroup>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29519/"
] |
347,798 | <p>I need to change an element's ID using jQuery. </p>
<p>Apparently these don't work:</p>
<pre><code>jQuery(this).prev("li").attr("id")="newid"
jQuery(this).prev("li")="newid"
</code></pre>
<p>I found out that I can make it happen with the following code:</p>
<pre><code>jQuery(this).prev("li")show(function() {
this.id="newid";
});
</code></pre>
<p>But that doesn't seem right to me. There must be a better way, no? Also, in case there isn't, what other method can I use instead of show/hide or other effects? Obviously I don't want to show/hide or affect the element every time, just to change its ID.</p>
<p>(Yep, I'm a jQuery newbie.)</p>
<p><strong>Edit</strong><br>
I can't use classes in this case, I must use IDs.</p>
| [
{
"answer_id": 347808,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 10,
"selected": true,
"text": "jQuery(this).prev(\"li\").attr(\"id\",\"newId\");\n"
},
{
"answer_id": 347810,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 6,
"selected": false,
"text": "jQuery(this).prev(\"li\").attr(\"id\", \"newID\");\n"
},
{
"answer_id": 478139,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "$('li').each(function(){\n if(this.id){\n this.id = this.id+\"something\";\n }\n});\n"
},
{
"answer_id": 23551875,
"author": "rfornal",
"author_id": 3390364,
"author_profile": "https://Stackoverflow.com/users/3390364",
"pm_score": 0,
"selected": false,
"text": "$(\"#myId\").on(\"click\", function() {});\n"
},
{
"answer_id": 25493852,
"author": "Jeremy Moritz",
"author_id": 2069295,
"author_profile": "https://Stackoverflow.com/users/2069295",
"pm_score": 6,
"selected": false,
"text": ".attr .prop $(this).prev('li').prop('id', 'newId');\n .attr .prop"
},
{
"answer_id": 32745339,
"author": "Prassanna D Manikandan",
"author_id": 5358342,
"author_profile": "https://Stackoverflow.com/users/5358342",
"pm_score": 2,
"selected": false,
"text": "<script>\n $(document).ready(function () {\n $('select').attr(\"id\", \"newId\"); //direct descendant of a\n });\n</script>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011/"
] |
347,804 | <p>I'm building a web application that guides my users through the configuration and installation of an application. It builds a set of configuration files dynamically, then sends them in an archive (.ZIP file) along with an installer for the application. The web page is generated from a linux shell script (sorry), and for security reasons, I'd prefer the file be sent directly from the script, rather than as a link, so the user can't access it directly.</p>
<p>Here's the process: Once the user has entered some information, and the files have been generated, I want to display a page with instructions, then start the download automatically, without asking the user to click a "download this file" link:</p>
<pre><code>#!/bin/bash
echo_header_and_instructions # Standard HTML
<Magic HTML tag to start transfer> # ??? What goes here???
command_to_stream_the_files # Probably 'cat'
echo_end_tags # End the page.
</code></pre>
<p>Thanks for your help!</p>
| [
{
"answer_id": 347913,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": false,
"text": "<meta http-equiv=\"refresh\" content=\"5;url=http://example.com/pathtodownload.zip\" />\n"
},
{
"answer_id": 347915,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": true,
"text": "<iframe> <iframe id=\"file_download\" width=\"0\" height=\"0\" scrolling=\"no\" \n frameborder=\"0\" src=/cgi-bin/my/scripts/sendfiles?file=$filename.zip>\n You need a browser that supports frames.\n</iframe>`\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29157/"
] |
347,811 | <p>A few years ago, it was proven that <a href="http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf" rel="noreferrer">PRIMES is in P</a>. Are there any algorithms implementing <a href="http://en.wikipedia.org/wiki/AKS_primality_test" rel="noreferrer">their primality test</a> in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast it is. I'd implement it myself, but I don't understand the paper enough yet to do that.</p>
| [
{
"answer_id": 29834291,
"author": "Jacques",
"author_id": 2504116,
"author_profile": "https://Stackoverflow.com/users/2504116",
"pm_score": -1,
"selected": false,
"text": "def expand_x_1(p):\n ex = [1]\n for i in range(p):\n ex.append(ex[-1] * -(p-i) / (i+1))\n return ex[::-1]\n\ndef aks_test(p):\n if p < 2: return False\n ex = expand_x_1(p)\n ex[0] += 1\n return not any(mult % p for mult in ex[0:-1])\n print('# p: (x-1)^p for small p')\n for p in range(12):\n print('%3i: %s' % (p, ' '.join('%+i%s' % (e, ('x^%i' % n) if n else '')\n for n,e in enumerate(expand_x_1(p)))))\n\nprint('\\n# small primes using the aks test')\nprint([p for p in range(101) if aks_test(p)])\n # p: (x-1)^p for small p\n 0: +1\n 1: -1 +1x^1\n 2: +1 -2x^1 +1x^2\n 3: -1 +3x^1 -3x^2 +1x^3\n 4: +1 -4x^1 +6x^2 -4x^3 +1x^4\n 5: -1 +5x^1 -10x^2 +10x^3 -5x^4 +1x^5\n 6: +1 -6x^1 +15x^2 -20x^3 +15x^4 -6x^5 +1x^6\n 7: -1 +7x^1 -21x^2 +35x^3 -35x^4 +21x^5 -7x^6 +1x^7\n 8: +1 -8x^1 +28x^2 -56x^3 +70x^4 -56x^5 +28x^6 -8x^7 +1x^8\n 9: -1 +9x^1 -36x^2 +84x^3 -126x^4 +126x^5 -84x^6 +36x^7 -9x^8 +1x^9\n 10: +1 -10x^1 +45x^2 -120x^3 +210x^4 -252x^5 +210x^6 -120x^7 +45x^8 -10x^9 +1x^10\n 11: -1 +11x^1 -55x^2 +165x^3 -330x^4 +462x^5 -462x^6 +330x^7 -165x^8 +55x^9 -11x^10 +1x^11\n\n# small primes using the aks test\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n"
},
{
"answer_id": 68583331,
"author": "bruno xavier",
"author_id": 15496709,
"author_profile": "https://Stackoverflow.com/users/15496709",
"pm_score": -1,
"selected": false,
"text": "from math import comb\n \ndef AKS(n):\n if (n ^ 1 == n + 1): # check if it's even\n if n == 2:\n return True \n return False\n for i in range(3,n//2):\n if comb(n,i)%n != 0: # check if any coefficient isn't divisible by n\n return False\n return True\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
347,812 | <p>Is there a way to be <strong>sure</strong> that a page is coming from cache on a production server and on the development server as well?</p>
<p>The solution <strong>shouldn't</strong> involve caching middleware because not every project uses them. Though the solution itself might <strong>be</strong> a middleware.</p>
<p>Just checking if the data is stale is not a very safe testing method IMO.</p>
| [
{
"answer_id": 348546,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 5,
"selected": true,
"text": "<!-- component_name {{host}} {{timestamp}} -->\n <!-- {{page_object.class_id}} @ {{timestamp}} -->\n def class_id(self):\n \"%s.%s.%s\" % (self.__class__._meta.app_label,\n self.__class__.__name__, self.id)\n"
},
{
"answer_id": 5563503,
"author": "Johannes",
"author_id": 641189,
"author_profile": "https://Stackoverflow.com/users/641189",
"pm_score": 4,
"selected": false,
"text": " <!-- {% now \"jS F Y H:i\" %} --> \n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42188/"
] |
347,818 | <p>It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:</p>
<pre><code>public abstract class SomeClass()
{
public void SomeMehod()
{
SomeOtherMethod();
}
internal abstract void SomeOtherMethod();
}
</code></pre>
<p>I want to test that if I call <code>SomeMethod()</code> then I expect that <code>SomeOtherMethod()</code> will be called. </p>
<p>Am I right in thinking this sort of test is available in a mocking framework?</p>
| [
{
"answer_id": 347907,
"author": "Paul",
"author_id": 41301,
"author_profile": "https://Stackoverflow.com/users/41301",
"pm_score": 9,
"selected": true,
"text": "static void Main(string[] args)\n{\n Mock<ITest> mock = new Mock<ITest>();\n\n ClassBeingTested testedClass = new ClassBeingTested();\n testedClass.WorkMethod(mock.Object);\n\n mock.Verify(m => m.MethodToCheckIfCalled());\n}\n\nclass ClassBeingTested\n{\n public void WorkMethod(ITest test)\n {\n //test.MethodToCheckIfCalled();\n }\n}\n\npublic interface ITest\n{\n void MethodToCheckIfCalled();\n}\n"
},
{
"answer_id": 5098105,
"author": "Val",
"author_id": 631219,
"author_profile": "https://Stackoverflow.com/users/631219",
"pm_score": 3,
"selected": false,
"text": "SomeClass.SomeMethod SomeOtherMethod Someclass New(ISomeOtherClass) ISomeOtherClass SomeOtherMethod"
},
{
"answer_id": 55722104,
"author": "Johnny",
"author_id": 3311799,
"author_profile": "https://Stackoverflow.com/users/3311799",
"pm_score": 0,
"selected": false,
"text": "moq SomeClass abstract public void SomeMehod() CallBase SomeOtherMethod() // This class is used only for test and purpose is make SomeMethod mockable\npublic abstract class DummyClass : SomeClass\n{\n public virtual void DummyMethod() => base.SomeMethod();\n}\n DummyMethod() CallBase //Arrange\nvar mock = new Mock<DummyClass>();\nmock.Setup(m => m.DummyMethod()).CallBase();\n\n//Act\nmock.Object.SomeMethod();\n\n//Assert\nmock.Verify(m => m.SomeOtherMethod(), Times.Once);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425/"
] |
347,851 | <p>The project I'm working on has two type of accounts, "<code>people</code>" and "<code>companies</code>". </p>
<p>I hold a single "<code>users</code>" table with all the accounts and just the basic info needed for login (email, pass, etc), and two other tables "<code>user_profiles</code>" (regular people) and "<code>company_profiles</code>" (companies) that hold more specific columns for each type, both of the tables linked to the general "<code>users</code>" table via a "<code>profile_user_id</code>" column.</p>
<p>But, whenever I want to list users that can be both people and companies, I use :</p>
<p>"<code>select user_id, user_type, concat_ws('', concat_ws(' ', user_profiles.profile_first_name, user_profiles.profile_last_name), company_profiles.profile_company_name) as user_fullname</code>".</p>
<p>When I list these users I know whether they're people or companies by the "<code>user_type</code>". </p>
<p>Is my approach using <code>concat_ws</code> the right (optimal) one? I did this instead of <code>select</code>-ing every <code>*_name</code> to avoid returning more columns than necessary.</p>
<p>Thanks</p>
<p>EDIT: the query above continues like: <code>from users left join user_profiles on ... left join company_profiles on ...</code></p>
| [
{
"answer_id": 347858,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 4,
"selected": true,
"text": "select\n u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name\nfrom \n users u, user_profiles up\nwhere u.key = up.key\n and u.user_type = 'user'\n\nunion\n\nselect\n u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name\nfrom \n users u, company_profiles cp\nwhere u.key = cp.key\n and u.user_type = 'company'\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44126/"
] |
347,856 | <p>I have created a form to add a user to a database and make user available for login.</p>
<p>Now I have two password fields (the second is for validation of the first). How can I add a validator for this kind of validation to zend_form?</p>
<p>This is my code for the two password fields:</p>
<pre><code> $password = new Zend_Form_Element_Password('password', array(
'validators'=> array(
'Alnum',
array('StringLength', array(6,20))
),
'filters' => array('StringTrim'),
'label' => 'Wachtwoord:'
));
$password->addFilter(new Ivo_Filters_Sha1Filter());
$password2 = new Zend_Form_Element_Password('password', array(
'validators'=> array(
'Alnum',
array('StringLength', array(6,20))
),
'filters' => array('StringTrim'),
'required' => true,
'label' => 'Wachtwoord:'
));
$password2->addFilter(new Ivo_Filters_Sha1Filter());
</code></pre>
| [
{
"answer_id": 348782,
"author": "Irmantas",
"author_id": 43182,
"author_profile": "https://Stackoverflow.com/users/43182",
"pm_score": 1,
"selected": false,
"text": "$password_2->addValidator('identical', false, $this->_request->getPost('password'));\n"
},
{
"answer_id": 348805,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 3,
"selected": true,
"text": "<?php\n\nclass Zend_Validate_IdenticalField extends Zend_Validate_Abstract {\n const NOT_MATCH = 'notMatch';\n const MISSING_FIELD_NAME = 'missingFieldName';\n const INVALID_FIELD_NAME = 'invalidFieldName';\n\n /**\n * @var array\n */\n protected $_messageTemplates = array(\n self::MISSING_FIELD_NAME =>\n 'DEVELOPMENT ERROR: Field name to match against was not provided.',\n self::INVALID_FIELD_NAME =>\n 'DEVELOPMENT ERROR: The field \"%fieldName%\" was not provided to match against.',\n self::NOT_MATCH =>\n 'Does not match %fieldTitle%.'\n );\n\n /**\n * @var array\n */\n protected $_messageVariables = array(\n 'fieldName' => '_fieldName',\n 'fieldTitle' => '_fieldTitle'\n );\n\n /**\n * Name of the field as it appear in the $context array.\n *\n * @var string\n */\n protected $_fieldName;\n\n /**\n * Title of the field to display in an error message.\n *\n * If evaluates to false then will be set to $this->_fieldName.\n *\n * @var string\n */\n protected $_fieldTitle;\n\n /**\n * Sets validator options\n *\n * @param string $fieldName\n * @param string $fieldTitle\n * @return void\n */\n public function __construct($fieldName, $fieldTitle = null) {\n $this->setFieldName($fieldName);\n $this->setFieldTitle($fieldTitle);\n }\n\n /**\n * Returns the field name.\n *\n * @return string\n */\n public function getFieldName() {\n return $this->_fieldName;\n }\n\n /**\n * Sets the field name.\n *\n * @param string $fieldName\n * @return Zend_Validate_IdenticalField Provides a fluent interface\n */\n public function setFieldName($fieldName) {\n $this->_fieldName = $fieldName;\n return $this;\n }\n\n /**\n * Returns the field title.\n *\n * @return integer\n */\n public function getFieldTitle() {\n return $this->_fieldTitle;\n }\n\n /**\n * Sets the field title.\n *\n * @param string:null $fieldTitle\n * @return Zend_Validate_IdenticalField Provides a fluent interface\n */\n public function setFieldTitle($fieldTitle = null) {\n $this->_fieldTitle = $fieldTitle ? $fieldTitle : $this->_fieldName;\n return $this;\n }\n\n /**\n * Defined by Zend_Validate_Interface\n *\n * Returns true if and only if a field name has been set, the field name is available in the\n * context, and the value of that field name matches the provided value.\n *\n * @param string $value\n *\n * @return boolean \n */ \n public function isValid($value, $context = null) {\n $this->_setValue($value);\n $field = $this->getFieldName();\n\n if (empty($field)) {\n $this->_error(self::MISSING_FIELD_NAME);\n return false;\n } elseif (!isset($context[$field])) {\n $this->_error(self::INVALID_FIELD_NAME);\n return false;\n } elseif (is_array($context)) {\n if ($value == $context[$field]) {\n return true;\n }\n } elseif (is_string($context) && ($value == $context)) {\n return true;\n }\n $this->_error(self::NOT_MATCH);\n return false;\n }\n}\n?>\n"
},
{
"answer_id": 3782388,
"author": "Tim Lytle",
"author_id": 45531,
"author_profile": "https://Stackoverflow.com/users/45531",
"pm_score": 5,
"selected": false,
"text": "Zend_Validate_Identical Zend_Validate $form->addElement('password', 'elementOne');\n$form->addElement('password', 'elementTwo', array(\n 'validators' => array(\n array('identical', false, array('token' => 'elementOne'))\n )\n));\n"
},
{
"answer_id": 21123830,
"author": "Zrinko Zadravec",
"author_id": 3195591,
"author_profile": "https://Stackoverflow.com/users/3195591",
"pm_score": 0,
"selected": false,
"text": "class Example_Validator extends Zend_Validate_Abstract{\n\nconst NOT_IDENTICALL = 'not same';\n\nprivate $testValue; \n\npublic function __construct( $arg ) {\n $this->testValue = $arg; \n }\n\nprotected $_messageTemplates = array(\n self::NOT_IDENTICALL => \"Passwords aren't same\"\n); \n\npublic function isValid( $value, $context = null )\n{\n echo $context['password']; \n echo '<br>';\n echo $this->testValue;\n\n return true;\n}\n}\n $form = new Zend_Form();\n$form->setAction('success');\n$form->setMethod('post'); \n$form->addElement('text', 'username');\n$usernameElement = $form->getElement('username');\n$form->addElement('password', 'password');\n$passwordElement = $form->getElement('password');\n$myValidator2 = new Example_Validator(\"Hello !\"); \n$passwordElement->addValidator($myValidator2, true); \n$form->addElement('submit', 'submit'); \n$submitButton = $form->getElement('submit');\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42111/"
] |
347,862 | <p>For the umpteenth time my laptop just shut down in the middle of my game because my power cable had disconnected without me noticing it.</p>
<p>Now I want to write a little C# program that detects when my power cable disconnects and then emits a nice long System beep. What API could I use for that?</p>
| [
{
"answer_id": 24464382,
"author": "ARK",
"author_id": 3782508,
"author_profile": "https://Stackoverflow.com/users/3782508",
"pm_score": 1,
"selected": false,
"text": "PowerStatus powerStatus = SystemInformation.PowerStatus;\n\nif (powerStatus.PowerLineStatus == PowerLineStatus.Online)\n{\n MessageBox.Show(\"Running On Power\", Convert.ToString(powerStatus.BatteryLifePercent * 100) + \"%\");\n}\nelse\n{\n MessageBox.Show(\"Running On Battery\", Convert.ToString(powerStatus.BatteryLifePercent * 100) + \"%\");\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
347,889 | <p>i have got an 32bit (hexadecimal)word 0xaabbccdd and have to swap the 2. and the 3. byte. in the end it should look like 0xaaccbbdd</p>
<p>how can i "mask" the 2nd and the 3rd byte to first load them up to register r1 and r2 and the swap them..
i also know that i have to work with lsl and lsr commands but dont know how to start.</p>
<p>sorry for my bad english.hope anyone could help me out!</p>
<p>regards,
sebastian</p>
| [
{
"answer_id": 348009,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 3,
"selected": false,
"text": " .text\n\nswap_v4:\n AND R2, R0, #0x00ff0000 @ R2=0x00BB0000 get byte 2\n AND R3, R0, #0x0000ff00 @ R3=0x0000CC00 get byte 1\n BIC R0, R0, #0x00ff0000 @ R0=0xAA00CCDD clear byte 2\n BIC R0, R0, #0x0000ff00 @ R0=0xAA0000DD clear byte 1\n ORR R0, R2, LSR #8 @ R0=0xAA00BBDD merge and shift byte 2\n ORR R0, R3, LSL #8 @ R0=0xAACCBBDD merge and shift byte 1\n B LR\n int swap (int R0)\n{\n int R2,R3;\n R2 = R0 & 0x00ff0000;\n R3 = R0 & 0x0000ff00;\n R0 = R0 & 0xff00ffff;\n R0 = R0 & 0xffff00ff;\n R0 |= (R2>>8);\n R0 |= (R3<<8);\n return R0;\n}\n swap_v6:\n @ bits in R0: aabbccdd\n ROR R0, R0, #8 @ r0 = ddaabbcc\n REV R1, R0 @ r1 = ccbbaadd\n PKHTB R0, R0, R1 @ r0 = ddaaccbb\n ROR R0, R0, #24 @ r0 = aaccbbdd\n BX LR\n"
},
{
"answer_id": 350110,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 0,
"selected": false,
"text": "static union {\n BYTE BBuf[4];\n WORD WWBuf[2];\n DWORD DWBuf;\n}swap;\n\nunsigned char *a;\nunsigned char *b;\nswap.DWBuf = 0xaabbccdd;\n\na = &swap.BBuf[1];\nb = &swap.BBuf[2];\n\n*a ^= *b;\n*b ^= *a;\n*a ^= *b;\n swap.DWbuf == 0xaaccbbdd;\n"
},
{
"answer_id": 800871,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 2,
"selected": false,
"text": ".globl midswap\nmidswap:\n mov r2,r0,lsl #8 ;@ r2 = BBCCDDAA\n mov r3,r0,lsr #8 ;@ r3 = DDAABBCC (this might drag a sign bit, dont care)\n and r2,r2,#0x00FF0000 ;@ r2 = 00CC0000\n and r3,r3,#0x0000FF00 ;@ r3 = 0000BB00\n bic r0,r0,#0x00FF0000 ;@ r0 = AA00CCDD\n bic r0,r0,#0x0000FF00 ;@ r0 = AA0000DD\n orr r0,r0,r2 ;@ r0 = AACC00DD\n orr r0,r0,r3 ;@ r0 = AACCBBDD\n bx lr ;@ or mov pc,lr for older arm cores\n\n\n.globl tworegs\ntworegs:\n mov r2,r0,ror #8 ;@ r2 = DDAABBCC\n bic r2,r2,#0xFF000000 ;@ r2 = 00AABBCC\n bic r2,r2,#0x00FF0000 ;@ r2 = 0000BBCC\n orr r2,r2,ror #16 ;@ r2 = BBCCBBCC\n bic r2,r2,#0xFF000000 ;@ r2 = 00CCBBCC\n bic r2,r2,#0x000000FF ;@ r2 = 00CCBB00\n bic r0,r0,#0x00FF0000 ;@ r0 = AA00CCDD\n bic r0,r0,#0x0000FF00 ;@ r0 = AA0000DD\n orr r0,r0,r2 ;@ r0 = AACCBBDD\n bx lr\n\ntestfun:\n ldr r0,=0xAABBCCDD\n bl midswap\n"
},
{
"answer_id": 1100352,
"author": "Dave Gamble",
"author_id": 133758,
"author_profile": "https://Stackoverflow.com/users/133758",
"pm_score": 3,
"selected": false,
"text": "eor r1,r0,r0,lsr #8\nand r1,r1,#0xFF00\norr r1,r1,r1,lsl #8\neor r0,r0,r1\n t=x^(x>>8);\nt=t&0xFF00;\nt=t|(t<<8);\nx^=t;\n eor XXXXEEXX\nand 0000EE00\norr 00EEEE00\neor AACCBBDD\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30954/"
] |
347,897 | <p>I need to use <code>FtpWebRequest</code> to put a file in a FTP directory. Before the upload, I would first like to know if this file exists. </p>
<p>What method or property should I use to check if this file exists?</p>
| [
{
"answer_id": 348334,
"author": "user42467",
"author_id": 42467,
"author_profile": "https://Stackoverflow.com/users/42467",
"pm_score": 8,
"selected": true,
"text": "var request = (FtpWebRequest)WebRequest.Create\n (\"ftp://ftp.domain.com/doesntexist.txt\");\nrequest.Credentials = new NetworkCredential(\"user\", \"pass\");\nrequest.Method = WebRequestMethods.Ftp.GetFileSize;\n\ntry\n{\n FtpWebResponse response = (FtpWebResponse)request.GetResponse();\n}\ncatch (WebException ex)\n{\n FtpWebResponse response = (FtpWebResponse)ex.Response;\n if (response.StatusCode ==\n FtpStatusCode.ActionNotTakenFileUnavailable)\n {\n //Does not exist\n }\n}\n request.UseBinary = true;\n WebRequestMethods.Ftp.GetDateTimestamp\n"
},
{
"answer_id": 32613075,
"author": "Nolmë Informatique",
"author_id": 345833,
"author_profile": "https://Stackoverflow.com/users/345833",
"pm_score": 4,
"selected": false,
"text": "request.Method = WebRequestMethods.Ftp.GetFileSize\n reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);\nreqFTP.UseBinary = true;\nreqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;\n"
},
{
"answer_id": 50056879,
"author": "Martin Prikryl",
"author_id": 850848,
"author_profile": "https://Stackoverflow.com/users/850848",
"pm_score": 3,
"selected": false,
"text": "FtpWebRequest GetFileSize GetDateTimestamp string url = \"ftp://ftp.example.com/remote/path/file.txt\";\n\nWebRequest request = WebRequest.Create(url);\nrequest.Credentials = new NetworkCredential(\"username\", \"password\");\nrequest.Method = WebRequestMethods.Ftp.GetFileSize;\ntry\n{\n request.GetResponse();\n Console.WriteLine(\"Exists\");\n}\ncatch (WebException e)\n{\n FtpWebResponse response = (FtpWebResponse)e.Response;\n if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)\n {\n Console.WriteLine(\"Does not exist\");\n }\n else\n {\n Console.WriteLine(\"Error: \" + e.Message);\n }\n}\n Session.FileExists SessionOptions sessionOptions = new SessionOptions {\n Protocol = Protocol.Ftp,\n HostName = \"ftp.example.com\",\n UserName = \"username\",\n Password = \"password\",\n};\n\nSession session = new Session();\nsession.Open(sessionOptions);\n\nif (session.FileExists(\"/remote/path/file.txt\"))\n{\n Console.WriteLine(\"Exists\");\n}\nelse\n{\n Console.WriteLine(\"Does not exist\");\n}\n"
},
{
"answer_id": 68738125,
"author": "Robbert van Leeuwen",
"author_id": 8782458,
"author_profile": "https://Stackoverflow.com/users/8782458",
"pm_score": 0,
"selected": false,
"text": "WebRequestMethods.Ftp.ListDirectory private static bool ExistFile(string remoteAddress)\n {\n int pos = remoteAddress.LastIndexOf('/');\n string dirPath = remoteAddress.Substring(0, pos); // skip the filename only get the directory\n\n NetworkCredential credentials = new NetworkCredential(FtpUser, FtpPass);\n FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(dirPath);\n listRequest.Method = WebRequestMethods.Ftp.ListDirectory;\n listRequest.Credentials = credentials;\n using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())\n using (Stream listStream = listResponse.GetResponseStream())\n using (StreamReader listReader = new StreamReader(listStream))\n {\n string fileToTest = Path.GetFileName(remoteAddress);\n while (!listReader.EndOfStream)\n {\n string fileName = listReader.ReadLine();\n fileName = Path.GetFileName(fileName);\n if (fileToTest == fileName)\n {\n return true;\n }\n\n }\n }\n return false;\n }\n\n static void Main(string[] args)\n {\n bool existFile = ExistFile(\"ftp://123.456.789.12/test/config.json\");\n }\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38940/"
] |
347,910 | <p>The project I'm working on requires access to the users source control. To do this we are wrapping the Perforce API and the Subversion API ( using P4.NET and SubversionSharp respectively ). </p>
<p>We would like to support as many as we can depending on user requirements and I've tried googling for an existing library but no luck. Does a C# library that wraps multiple SCM applications exist?</p>
| [
{
"answer_id": 350738,
"author": "andrewbadera",
"author_id": 25952,
"author_profile": "https://Stackoverflow.com/users/25952",
"pm_score": 1,
"selected": false,
"text": "[DllImport(@\"C:\\Program Files\\Microsoft Visual Studio\\Common\\VSS\\win32\\SSSCC.DLL\")]\n"
},
{
"answer_id": 520027,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 0,
"selected": false,
"text": "using(SvnClient client = new SvnClient())\n{\n client.Update(@\"C:\\My\\WorkingCopy\");\n\n // Do something to your working copy\n File.AppendAllText(@\"C:\\My\\WorkingCopy\", \"\\nFile Change\\n\");\n\n SvnCommitArgs ca = new SvnCommitArgs();\n ca.LogMessage = \"Line added\";\n\n client.Commit(@\"C:\\My\\WorkingCopy\", ca);\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41477/"
] |
347,918 | <p>I would like to generate some JavaScript on the server side in ASP.Net MVC. Is there a view engine that supports this? Ideally I would like to be able to get JavaScript from an url like: </p>
<pre><code>http://myapp/controller/action.js
</code></pre>
<p>I've looked at the MonoRail project, and they seem to have this feature, but it's very lacking in documentation, and I can't find any ports to ASP.Net MVC.</p>
<p><strong>Edit:</strong> The idea is to be able to render a page both as standard HTML by using a url like:</p>
<pre><code>http://myapp/controller/action
</code></pre>
<p>and as js (specifically an ExtJS component) by using the first url in the question. There would be only a single action in the controller, but two views: one for HTML and one for JS.</p>
<p><strong>Edit 2:</strong> I basically wanted to achieve the same result as <a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/" rel="nofollow noreferrer">router extension parsing/request handling</a> in CakePHP.</p>
| [
{
"answer_id": 347946,
"author": "Jennifer",
"author_id": 22360,
"author_profile": "https://Stackoverflow.com/users/22360",
"pm_score": 1,
"selected": false,
"text": "RouteTable.Routes.Add(new Route\n{\n Url = \"[controller]/[action].js\",\n Defaults = new { controller=\"home\", requestType=\"javascript\" }, // Whatever...\n RouteHandler = typeof(MvcRouteHandler)\n});\n\nRouteTable.Routes.Add(new Route\n{\n Url = \"[controller]/[action]\",\n Defaults = new { controller=\"home\"}, // Whatever...\n RouteHandler = typeof(MvcRouteHandler)\n});\n public ActionResult MyAction (RequestType requestType)\n{\n if(requestType == RequestType.JavaScript)\n {\n ... new nvelocity view to render javascript\n }\n else\n {\n ... \n }\n}\n"
},
{
"answer_id": 347981,
"author": "smoothdeveloper",
"author_id": 17049,
"author_profile": "https://Stackoverflow.com/users/17049",
"pm_score": 1,
"selected": false,
"text": "[ControllerDetails(\"js\")]\npublic class JavascriptController : Controller\n{\n private ISessionContext sessionContext;\n\n public JavascriptController(ISessionContext sessionContext)\n {\n this.sessionContext = sessionContext;\n }\n\n public void CultureInfo()\n {\n var scriptformat = @\"var cultureInfo = {0};\";\n var json = Context.Services.JSONSerializer.Serialize(getJSONiZableCultureInfo(sessionContext.CurrentCulture));\n RenderText(String.Format(scriptformat, json));\n }\n\n object getJSONiZableCultureInfo(System.Globalization.CultureInfo culture)\n {\n return new\n { // add more there\n culture.NumberFormat\n };\n }\n}\n"
},
{
"answer_id": 348053,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": false,
"text": "{controller}/{action}.{format}\n\n{controller}/{action}\n public ActionResult List(string format) {\n\n // logic here\n\n if (string.IsNullOrEmpty(format)) {\n return View();\n } else if (format == \"js\") {\n return Json(object_to_serialize);\n }\n\n}\n"
},
{
"answer_id": 348752,
"author": "Jacob",
"author_id": 22107,
"author_profile": "https://Stackoverflow.com/users/22107",
"pm_score": 3,
"selected": true,
"text": "\\Views\n+-\\MyController\n +-\\js\n | +-Index.aspx <- This view will get rendered if you request /MyController/Index.js\n +-Index.aspx\n public class TypeViewEngine<T> : IViewEngine where T : IViewEngine\n{\n private readonly T baseEngine;\n public T BaseEngine\n {\n get { return baseEngine; }\n }\n\n public TypeViewEngine(T baseEngine)\n {\n this.baseEngine = baseEngine;\n }\n\n public void RegisterRoutes(RouteCollection routes)\n {\n routes.MapRoute(\n \"TypeViewEngine\",\n \"{controller}/{action}.{type}\",\n new {controller = \"Home\", action = \"Index\", type = \"html\"}\n );\n }\n\n public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)\n {\n var vars = controllerContext.RouteData.Values;\n if(vars[\"type\"] != null && vars[\"type\"].ToString() != \"html\")\n {\n viewName = string.Format(\"{0}/{1}\", vars[\"type\"], viewName);\n }\n return baseEngine.FindView(controllerContext, viewName, masterName);\n }\n\n public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName)\n {\n return baseEngine.FindPartialView(controllerContext, partialViewName);\n }\n\n public void ReleaseView(ControllerContext controllerContext, IView view)\n {\n baseEngine.ReleaseView(controllerContext, view);\n }\n}\n protected void Application_Start()\n{\n var ve = new TypeViewEngine<WebFormViewEngine>(new WebFormViewEngine());\n ve.RegisterRoutes(RouteTable.Routes);\n RegisterRoutes(RouteTable.Routes);\n\n ViewEngines.Engines.Clear();\n ViewEngines.Engines.Add(ve);\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22107/"
] |
347,920 | <p>I'm messing around with some C code using floats, and I'm getting 1.#INF00, -1.#IND00 and -1.#IND when I try to print floats in the screen. What does those values mean?</p>
<p>I believe that 1.#INF00 means positive infinity, but what about -1.#IND00 and -1.#IND? I also saw sometimes this value: 1.$NaN which is Not a Number, but what causes those strange values and how can those help me with debugging?</p>
<p>I'm using <a href="http://en.wikipedia.org/wiki/MinGW" rel="noreferrer">MinGW</a> which I believe uses <a href="https://en.wikipedia.org/wiki/IEEE_floating_point" rel="noreferrer">IEEE 754</a> representation for float point numbers.</p>
<p>Can someone list all those invalid values and what they mean?</p>
| [
{
"answer_id": 11893772,
"author": "Jeff",
"author_id": 13338,
"author_profile": "https://Stackoverflow.com/users/13338",
"pm_score": 2,
"selected": false,
"text": "If Double.IsNaN(MyVariableName) Then\n MyVariableName = 0 ' Or whatever you want to do here to \"correct\" the situation\nEnd If\n"
},
{
"answer_id": 52491720,
"author": "sam-6174",
"author_id": 2426679,
"author_profile": "https://Stackoverflow.com/users/2426679",
"pm_score": 3,
"selected": false,
"text": "-1.#IND00 -1.#IND -1.#IND00 3.14 / 0 -1.#IND NaN sqrt log 0 / 0 NaN NaN * 5 arcsin(2)"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] |
347,948 | <p>Bonus points for explaining how you improved it.</p>
| [
{
"answer_id": 348000,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "$encrypted_password = md5( sha1( plaintext_password ) );\n"
},
{
"answer_id": 348106,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 1,
"selected": false,
"text": "wget"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
347,949 | <p>How can I convert an <code>std::string</code> to a <code>char*</code> or a <code>const char*</code>?</p>
| [
{
"answer_id": 347952,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": ".c_str() const char * &mystring[0] char * std::string string"
},
{
"answer_id": 347959,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 11,
"selected": true,
"text": "std::string const char * .c_str() std::string str;\nconst char * c = str.c_str();\n char * .data() std::string str;\nchar * c = str.data();\n .data() &str[0] std::string const .data() const char * .c_str() str.size()"
},
{
"answer_id": 4152881,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 8,
"selected": false,
"text": "std::string x = \"hello\";\n x const char* p_c_str = x.c_str();\nconst char* p_data = x.data();\nchar* p_writable_data = x.data(); // for non-const x from C++17 \nconst char* p_x0 = &x[0];\n\n char* p_x0_rw = &x[0]; // compiles iff x is not const...\n std::string(\"this\\0that\", 9) \"this\\0that\\0\" char c = p[n]; // valid for n <= x.size()\n // i.e. you can safely read the NUL at p[x.size()]\n const p_writable_data &x[0] p_writable_data[n] = c;\np_x0_rw[n] = c; // valid for n <= x.size() - 1\n // i.e. don't overwrite the implementation maintained NUL\n string size() string std::string x.data() const char* ['h', 'e', 'l', 'l', 'o'] x.size() x[0] x[x.size() - 1] &x[0] f(const char* p, size_t n) { if (n == 0) return; ...whatever... } f(&x[0], x.size()); x.empty() f(x.data(), ...) x.data() const x const char* x.c_str() const char* x.data() &x[0] x.size() string string string x .c_str() .data() .c_str() .data() .data() &x[0] data() .c_str() fstream::fstream(const char* filename, ...) strchr() printf() .c_str() .data() .c_str() .data() string const char* x.size() .c_str() x string x x string x std::string x // USING ANOTHER STRING - AUTO MEMORY MANAGEMENT, EXCEPTION SAFE\nstd::string old_x = x;\n// - old_x will not be affected by subsequent modifications to x...\n// - you can use `&old_x[0]` to get a writable char* to old_x's textual content\n// - you can use resize() to reduce/expand the string\n// - resizing isn't possible from within a function passed only the char* address\n\nstd::string old_x = x.c_str(); // old_x will terminate early if x embeds NUL\n// Copies ASCIIZ data but could be less efficient as it needs to scan memory to\n// find the NUL terminator indicating string length before allocating that amount\n// of memory to copy into, or more efficient if it ends up allocating/copying a\n// lot less content.\n// Example, x == \"ab\\0cd\" -> old_x == \"ab\".\n\n// USING A VECTOR OF CHAR - AUTO, EXCEPTION SAFE, HINTS AT BINARY CONTENT, GUARANTEED CONTIGUOUS EVEN IN C++03\nstd::vector<char> old_x(x.data(), x.data() + x.size()); // without the NUL\nstd::vector<char> old_x(x.c_str(), x.c_str() + x.size() + 1); // with the NUL\n\n// USING STACK WHERE MAXIMUM SIZE OF x IS KNOWN TO BE COMPILE-TIME CONSTANT \"N\"\n// (a bit dangerous, as \"known\" things are sometimes wrong and often become wrong)\nchar y[N + 1];\nstrcpy(y, x.c_str());\n\n// USING STACK WHERE UNEXPECTEDLY LONG x IS TRUNCATED (e.g. Hello\\0->Hel\\0)\nchar y[N + 1];\nstrncpy(y, x.c_str(), N); // copy at most N, zero-padding if shorter\ny[N] = '\\0'; // ensure NUL terminated\n\n// USING THE STACK TO HANDLE x OF UNKNOWN (BUT SANE) LENGTH\nchar* y = alloca(x.size() + 1);\nstrcpy(y, x.c_str());\n\n// USING THE STACK TO HANDLE x OF UNKNOWN LENGTH (NON-STANDARD GCC EXTENSION)\nchar y[x.size() + 1];\nstrcpy(y, x.c_str());\n\n// USING new/delete HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY\nchar* y = new char[x.size() + 1];\nstrcpy(y, x.c_str());\n// or as a one-liner: char* y = strcpy(new char[x.size() + 1], x.c_str());\n// use y...\ndelete[] y; // make sure no break, return, throw or branching bypasses this\n\n// USING new/delete HEAP MEMORY, SMART POINTER DEALLOCATION, EXCEPTION SAFE\n// see boost shared_array usage in Johannes Schaub's answer\n\n// USING malloc/free HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY\nchar* y = strdup(x.c_str());\n// use y...\nfree(y);\n char* const char* string const char* string string printf(\"x is '%s'\", x.c_str()); x strncpy(callers_buffer, callers_buffer_size, x.c_str()) for (const char* p = x.c_str(); *p; ++p) *p_device = *p; x strcat(other_buffer, x.c_str()) strncat const char* char* std::string string string std::string"
},
{
"answer_id": 5473348,
"author": "Alessandro Teruzzi",
"author_id": 508175,
"author_profile": "https://Stackoverflow.com/users/508175",
"pm_score": 3,
"selected": false,
"text": "char* class DeepString\n{\n DeepString(const DeepString& other);\n DeepString& operator=(const DeepString& other);\n char* internal_; \n \n public:\n explicit DeepString( const string& toCopy): \n internal_(new char[toCopy.size()+1]) \n {\n strcpy(internal_,toCopy.c_str());\n }\n ~DeepString() { delete[] internal_; }\n char* str() const { return internal_; }\n const char* c_str() const { return internal_; }\n};\n void aFunctionAPI(char* input);\n\n// other stuff\n\naFunctionAPI(\"Foo\"); //this call is not safe. if the function modified the \n //literal string the program will crash\nstd::string myFoo(\"Foo\");\naFunctionAPI(myFoo.c_str()); //this is not compiling\naFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string \n //implement reference counting and \n //it may change the value of other\n //strings as well.\nDeepString myDeepFoo(myFoo);\naFunctionAPI(myFoo.str()); //this is fine\n DeepString DeepString"
},
{
"answer_id": 16505452,
"author": "devsaw",
"author_id": 1870685,
"author_profile": "https://Stackoverflow.com/users/1870685",
"pm_score": 3,
"selected": false,
"text": "string str1(\"stackoverflow\");\nconst char * str2 = str1.c_str();\n const char * char * strcpy char"
},
{
"answer_id": 24712763,
"author": "cegprakash",
"author_id": 1137624,
"author_profile": "https://Stackoverflow.com/users/1137624",
"pm_score": 3,
"selected": false,
"text": "char* result = strcpy((char*)malloc(str.length()+1), str.c_str());\n"
},
{
"answer_id": 34748132,
"author": "Pixelchemist",
"author_id": 951423,
"author_profile": "https://Stackoverflow.com/users/951423",
"pm_score": 5,
"selected": false,
"text": "basic_string data() charT* data() noexcept; CharT const * std::basic_string<CharT> std::string const cstr = { \"...\" };\nchar const * p = cstr.data(); // or .c_str()\n CharT * std::basic_string<CharT> std::string str = { \"...\" };\nchar * p = str.data();\n CharT const * std::basic_string<CharT> std::string str = { \"...\" };\nstr.c_str();\n CharT * std::basic_string<CharT> basic_string basic_string s &*(s.begin() + n) == &*s.begin() + n n 0 <= n < s.size() const_reference operator[](size_type pos) const; reference operator[](size_type pos); *(begin() + pos) pos < size() CharT CharT() const charT* c_str() const noexcept; const charT* data() const noexcept; p + i == &operator[](i) i [0,size()] std::string foo{\"text\"};\nauto p = &*foo.begin();\n '\\0' std::vector<CharT> std::string foo{\"text\"};\nstd::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);\nauto p = fcv.data();\n std::array<CharT, N> N std::string foo{\"text\"};\nstd::array<char, 5u> fca;\nstd::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());\n std::string foo{ \"text\" };\nauto p = std::make_unique<char[]>(foo.size()+1u);\nstd::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);\n std::string foo{ \"text\" };\nchar * p = nullptr;\ntry\n{\n p = new char[foo.size() + 1u];\n std::copy(foo.data(), foo.data() + foo.size() + 1u, p);\n // handle stuff with p\n delete[] p;\n}\ncatch (...)\n{\n if (p) { delete[] p; }\n throw;\n}\n"
},
{
"answer_id": 42303195,
"author": "anish",
"author_id": 911576,
"author_profile": "https://Stackoverflow.com/users/911576",
"pm_score": -1,
"selected": false,
"text": "std::string s(reinterpret_cast<const char *>(Data), Size);\n"
},
{
"answer_id": 68014300,
"author": "Vineeth Peddi",
"author_id": 11237257,
"author_profile": "https://Stackoverflow.com/users/11237257",
"pm_score": 0,
"selected": false,
"text": " char* s_rw=&str[0]; \n const char* s_r=&str[0];\n"
},
{
"answer_id": 69745059,
"author": "SHAH MD IMRAN HOSSAIN",
"author_id": 6028039,
"author_profile": "https://Stackoverflow.com/users/6028039",
"pm_score": 2,
"selected": false,
"text": "string::copy string::copy // char string\nchar chText[20];\n\n// c++ string\nstring text = \"I am a Programmer\";\n\n// conversion from c++ string to char string\n// this function does not append a null character at the end of operation\ntext.copy(chText, text.size(), 0);\n\n// we need to put it manually\nchText[text.size()] = '\\0';\n\n// below statement prints \"I am a Programmer\"\ncout << chText << endl;\n char chText[20] = \"I am a Programmer\";\n// using constructor\nstring text(chText);\n string::assign // char string\nchar chText[20] = \"I am a Programmer\";\n\n// c++ string\nstring text;\n\n// convertion from char string to c++ string\n// using assign function\ntext.assign(chText);\n // char string\nchar chText[20] = \"I am a Programmer\";\n\n// c++ string\n// convertion from char string to c++ string using assignment operator overloading\nstring text = chText;\n // char string\nchar chText[20] = \"I am a Programmer\";\n\n// c++ string\nstring text;\n\n\n// convertion from char string to c++ string\ntext = chText;\n"
},
{
"answer_id": 72485404,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": -1,
"selected": false,
"text": "char* std::string char* std::string std::string char* const char* std::string char* const char* .resize() char* data() #include <string>\nconstexpr size_t BUFFER_SIZE = 100;\nstd::string str;\n// IMPORTANT: pre-allocate the underlying buffer to guarantee what size it is\nstr.resize(BUFFER_SIZE); \n\n// -----------------------------------------------------------------------------\n// Get read-writeable access to the underlying `char*` C-string at index i\n// -----------------------------------------------------------------------------\n\nchar* c_str1 = &str[i]; // <=== my favorite!\nchar* c_str2 = str.data() + i;\nchar* c_str3 = &(*str.begin()) + i;\n\n// NB: the C-strings above are NOT guaranteed to be null-terminated, so manually\n// write in a null terminator at the index location where you want it if\n// desired. Ex:\n//\n// 1. write a null terminator at some arbitrary position you choose (index 10\n// here)\nc_str1[10] = '\\0'; \n// 2. write a null terminator at the last guaranteed valid position in the \n// underlying C-string/array of chars\nc_str2[str.size() - i - 1] = '\\0';\n\n// -----------------------------------------------------------------------------\n// Get read-only access to the underlying `const char*` C-string at index i\n// -----------------------------------------------------------------------------\nconst char* const_c_str1 = &str[i];\nconst char* const_c_str2 = str.c_str() + i; // guaranteed to be null-terminated,\n // but not necessarily at the\n // position you desire; the\n // guaranteed null terminator will\n // be at index location \n // `str.size()`\n char* char* c_str1 = &str[i]; str.resize(BUFFER_SIZE) const char* const char* const_c_str1 = &str[i]; const char* const_c_str1 = str.c_str() + i; #include <string>\n\nconstexpr size_t BUFFER_SIZE = 100;\n\nstd::string str;\n// IMPORTANT: pre-allocate the underlying buffer to guarantee what size it is\nstr.resize(BUFFER_SIZE); \n\n// =============================================================================\n// Now you can use the `std::string`'s underlying buffer directly as a C-string\n// =============================================================================\n\n// ---------------------------------------------------------\n// A. As a read-writeable `char*` C-string\n// ---------------------------------------------------------\n\n// Technique 1 [best option if using C++11]: array indexing using `operator[]` \n// to obtain a char, followed by obtaining its address with `&`\n// - Documentation: \n// https://en.cppreference.com/w/cpp/string/basic_string/operator_at\nchar* c_str1 = &str[0];\nchar* c_str2 = &str[10];\nchar* c_str3 = &str[33];\n// etc. \n\n// Technique 2 [best option if using C++17]: use the `.data()` method to obtain\n// a `char*` directly.\n// - Documentation: \n// https://en.cppreference.com/w/cpp/string/basic_string/data\nchar* c_str11 = str.data(); // same as c_str1 above\nchar* c_str12 = str.data() + 10; // same as c_str2 above\nchar* c_str13 = str.data() + 33; // same as c_str3 above\n\n// Technique 3 [fine in C++11 or later, but is awkward, so don't do this. It is\n// for demonstration and learning purposes only]: use the `.begin()` method to\n// obtain an iterator to the first char, and then use the iterator's \n// `operator*()` dereference method to obtain the iterator's `char`\n// `value_type`, and then take the address of that to obtain a `char*`\n// - Documentation:\n// - https://en.cppreference.com/w/cpp/string/basic_string/begin\n// - https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator\nchar* c_str21 = &(*str.begin()); // same as c_str1 and c_str11 above\nchar* c_str22 = &(*str.begin()) + 10; // same as c_str2 and c_str12 above\nchar* c_str23 = &(*str.begin()) + 33; // same as c_str3 and c_str13 above\n\n\n// ---------------------------------------------------------\n// B. As a read-only, null-terminated `const char*` C-string\n// ---------------------------------------------------------\n\n// - Documentation:\n// https://en.cppreference.com/w/cpp/string/basic_string/c_str\n\nconst char* const_c_str1 = str.c_str(); // a const version of c_str1 above\nconst char* const_c_str2 = str.c_str() + 10; // a const version of c_str2 above\nconst char* const_c_str3 = str.c_str() + 33; // a const version of c_str3 above\n .at(i) .front() std::string .at(i) .front() std::string std::string char* std::string char* .size() .resize() .reserve() .capacity() std::string::operator[] pos > size() resize() reserve() capacity() #include <cstring> // `strcpy()`\n#include <iostream>\n#include <string>\n\n\nconstexpr size_t BUFFER_SIZE = 100;\n\nstd::string str;\nstr.resize(BUFFER_SIZE); // pre-allocate the underlying buffer\n// check the size\nstd::cout << \"str.size() = \" << str.size() << \"\\n\";\n constexpr char cstr1[] = \"abcde \";\nconstexpr char cstr2[] = \"fghijk\";\n resize() char* operator[] & char* c_str;\nc_str = &str[0];\nc_str = &str[5]; \n// etc.\n\n// Write these 2 C-strings into a `std::string`'s underlying buffer\nstrcpy(&str[0], cstr1);\nstrcpy(&str[sizeof(cstr1) - 1], cstr2); // `- 1` to overwrite the first \n // null terminator\n\n// print the string\nstd::cout << str << \"\\n\"; // output: `abcde fghijk`\n std::string std::string *pstr operator[] &(*pstr)[0] std::string str2;\nstd::string* pstr = &str2;\npstr->resize(BUFFER_SIZE);\nc_str = &(*pstr)[0]; // <=== dereference the ptr 1st before indexing into it\n// Or, to make the order of precedence \n// (https://en.cppreference.com/w/cpp/language/operator_precedence) really\n// obvious, you can optionally add extra parenthesis like this:\nc_str = &((*pstr)[0]);\n .data() char* char* c_str;\nc_str = str.data();\nc_str = str.data() + 5;\n// etc.\n\n// Write these 2 C-strings into the `std::string`'s underlying buffer\nstrcpy(str.data(), cstr1);\nstrcpy(str.data() + (sizeof(cstr1) - 1), cstr2); // `- 1` to overwrite the\n // first null terminator\n\n// print the string\nstd::cout << str << \"\\n\"; // output: `abcde fghijk`\n .begin() operator*() char value_type char* char* c_str;\nc_str = &(*str.begin());\nc_str = &(*str.begin()) + 5;\n// etc.\n\n// Write these 2 C-strings into the `std::string`'s underlying buffer\nstrcpy(&(*str.begin()), cstr1);\nstrcpy(&(*str.begin()) + (sizeof(cstr1) - 1), cstr2); // `- 1` to overwrite \n // the first null \n // terminator\n\n// print the string\nstd::cout << str << \"\\n\"; // output: `abcde fghijk`\n str.resize(100) size() 100 100 char() char '\\0' str.size() 100 \"hello\" strlen() std::cout << strlen(str.c_str()) << \"\\n\"; // prints `12` in the examples above\n\n// instead of:\nstd::cout << str.size() << \"\\n\"; // prints `100` in the examples above\n std::string const char* const char* std::string .c_str() .data() std::string str = \"hello world\";\nprintf(\"%s\\n\", str.c_str());\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37875/"
] |
347,951 | <p>I have two running processes in Windows, and each process has a pipe to the other.</p>
<p>I want to serialize a complicated class and transmit it from one process to the other. I already have the serialization procedure worked out, and I understand that the pipes are sending binary streams. How should I go about sending my serialized data? I'm using WinAPI and C++.</p>
<p>Should I develop a custom protocol? If so, should it be generic or unique to this particular class? Can I preserve virtual tables when sending the serialized class?</p>
<p>Are there any models or design patterns that are commonly used in this case? A little bit of sample code would be greatly appreciated. Thank you!</p>
| [
{
"answer_id": 347999,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "boost::serialization"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7003/"
] |
347,954 | <p>How can I do a script to catch strings as input and open them on a Firefox document? Each link would go to a different window or tab. Any ideas would be much appreciated.</p>
<p>I just want to be able to take some links and open them. For example I have 50 Links. And copying and parsing those 50 Links take a really long time and also a lot of work. If I can just write a script to read those links and let the computer do the work, it will be very helpful for me. I just don't know how to write that or where because it does not sound too hard (just gotta know how to). Thanks for any suggestions. </p>
| [
{
"answer_id": 349403,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head><title>Your links</title></head>\n<body>\nYour links:<br />\n<a href=\"XXX\">XXX</a><br />\n</body>\n</html>\n innerHTML"
},
{
"answer_id": 485733,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n<title>Documento sin título</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</head>\n\n<body>\n<script>\n<!--\n var dir = new Array();\n dir[0] = \"http://www.creativecorner.cl/\";\n dir[1] = \"http://www.sourcing.cl/\";\n dir[2] = \"http://www.feeds.cl/\";\n dir[3] = \"http://www.neonomade.com/\";\n for(i = 0 ; i < dir.length ; i++){\n window.open(dir[i],'autowindow' + i,'width=1024,height=768');\n }\n-->\n</script>\n</body>\n</html>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
347,969 | <p>My question is whether or not Flex's fcsh can be called from within a PHP script. Here is the background:</p>
<p>I have been created a simple process that creates a simple quiz/tutorial by converting a text file into a .mxml file and compiling to a .swf file using the mxmlc compiler. This works well from the command line, but I wanted to make the process easier by creating a web-interface to do this. My initial attempts with PHP's exec() function have not worked. The Python scripts I use to create the .mxml file work fine (using exec()), but I have not been able to get the mxmlc compiler to work.</p>
<p>After searching on the Web and on this site, I believe that using fcsh (instead of mxmlc) may be the way to go. Using fcsh would certainly compile the .mxml file faster (after the first run), and I think that fcsh can be launched as a service that might be able to be called from PHP.</p>
<p>On the other hand, maybe I am approaching this the wrong way. Would it be better to write a Flex application that calls fcsh and avoid using PHP?</p>
<p><strong>Edit:</strong> Using fcshctl as hasseg suggested in his answer below worked very well. Thanks Ali.</p>
| [
{
"answer_id": 348132,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 2,
"selected": true,
"text": "fcshctl"
},
{
"answer_id": 368665,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "mxmlc fcsh mxmlc -load-config path/to/config.xml FLEX_HOME/frameworks/flex-config.xml"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23089/"
] |
348,021 | <p>By means of a regular expression and Greasemonkey I have an array of results that looks like:<br>
<code>choice1, choice2, choice3, choice3, choice1, etc..</code></p>
<p>My question is how do I tally up the choices so I know how many times choice1 is in the array, choice2 is in the array, etc. if I do not know exactly how many choices there are or what they are.</p>
<p>The ultimate goal is to create a Greasemonkey script that stores the number of votes each choice gets over multiple pages (probably using gm_setvalue although I'm open to other ideas.)</p>
<p>Thanks!</p>
| [
{
"answer_id": 348032,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 1,
"selected": false,
"text": " // Original data\n var choices = [\n \"choice 1\",\n \"choice 1\",\n \"choice 2\",\n \"choice 3\",\n \"choice 3\",\n \"choice 3\",\n \"choice 3\",\n \"choice 3\",\n \"choice 3\",\n \"choice 4\",\n \"choice 4\",\n \"choice 4\"];\n\n\n //Create the results array\n var result = new Object();\n\n for (var choice in choices) {\n if (result[choices[choice]] === undefined)\n result[choices[choice]] = 1;\n else\n result[choices[choice]]++;\n }\n\n //Print result\n var str = \"\";\n\n for (var item in result)\n str += item + \": \" + result[item] + \"<br />\";\n\n\n document.getElementById(\"resultDiv\").innerHTML = str;\n choice 1: 2\nchoice 2: 1\nchoice 3: 6\nchoice 4: 3\n"
},
{
"answer_id": 348038,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 3,
"selected": true,
"text": "var choiceCounts = {};\nfor (var iLoop=0; iLoop < aChoices.length; iLoop++) {\n var keyChoice = aChoices[iLoop];\n if (!choiceCounts[keyChoice]) {\n choiceCounts[keyChoice] = 1;\n } else {\n choiceCounts[keyChoice]++;\n } //if\n} //for\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44133/"
] |
348,022 | <p>I'm trying to implement a Load / Save function for a Windows Forms application.</p>
<p>I've got following components:</p>
<ul>
<li>A tree view</li>
<li>A couple of list views</li>
<li>A couple of text boxes</li>
<li>A couple of objects (which holds a big dictionarylist)</li>
</ul>
<p>I want to implement a way to save all of this into a file, and resume/load it later on.</p>
<p>What's the best way to do this? </p>
<p>I think XML serialization is the way to go, but I'm not quite sure how, or where to start. Or will it require a really complex solution to be able to do this?</p>
| [
{
"answer_id": 348024,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "TreeView DataTable XmlSerializer"
},
{
"answer_id": 348904,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Windows.Forms;\nusing System.Xml.Serialization;\nstatic class Program { // formatted for vertical space\n [STAThread]\n static void Main() {\n Application.EnableVisualStyles();\n\n Button load, save, newCust;\n BindingSource source = new BindingSource { DataSource = typeof(Customer) };\n XmlSerializer serializer = new XmlSerializer(typeof(Customer));\n using (Form form = new Form {\n DataBindings = {{\"Text\", source, \"Name\"}}, // show customer name as form title\n Controls = {\n new DataGridView { Dock = DockStyle.Fill, // grid of orders\n DataSource = source, DataMember = \"Orders\"},\n new TextBox { Dock = DockStyle.Top, ReadOnly = true, // readonly order ref\n DataBindings = {{\"Text\", source, \"Orders.OrderRef\"}}},\n new TextBox { Dock = DockStyle.Top, // editable customer name\n DataBindings = {{\"Text\", source, \"Name\"}}},\n (save = new Button { Dock = DockStyle.Bottom, Text = \"save\" }),\n (load = new Button{ Dock = DockStyle.Bottom, Text = \"load\"}),\n (newCust = new Button{ Dock = DockStyle.Bottom, Text = \"new\"}), \n }\n })\n {\n const string PATH = \"customer.xml\";\n form.Load += delegate {\n newCust.PerformClick(); // create new cust when loading form\n load.Enabled = File.Exists(PATH);\n };\n save.Click += delegate {\n using (var stream = File.Create(PATH)) {\n serializer.Serialize(stream, source.DataSource);\n }\n load.Enabled = true;\n };\n load.Click += delegate {\n using (var stream = File.OpenRead(PATH)) {\n source.DataSource = serializer.Deserialize(stream);\n }\n };\n newCust.Click += delegate {\n source.DataSource = new Customer();\n };\n Application.Run(form);\n } \n }\n}\n\n[Serializable]\npublic sealed class Customer : NotifyBase {\n private int customerId;\n [DisplayName(\"Customer Number\")]\n public int CustomerId {\n get { return customerId; }\n set { SetField(ref customerId, value, \"CustomerId\"); }\n }\n\n private string name;\n public string Name {\n get { return name; }\n set { SetField(ref name, value, \"Name\"); }\n }\n\n public List<Order> Orders { get; set; } // XmlSerializer demands setter\n\n public Customer() {\n Orders = new List<Order>();\n }\n}\n\n[Serializable]\npublic sealed class Order : NotifyBase {\n private int orderId;\n [DisplayName(\"Order Number\")]\n public int OrderId {\n get { return orderId; }\n set { SetField(ref orderId, value, \"OrderId\"); }\n }\n\n private string orderRef;\n [DisplayName(\"Reference\")]\n public string OrderRef {\n get { return orderRef; }\n set { SetField(ref orderRef, value, \"OrderRef\"); }\n }\n\n private decimal orderValue, carriageValue;\n\n [DisplayName(\"Order Value\")]\n public decimal OrderValue {\n get { return orderValue; }\n set {\n if (SetField(ref orderValue, value, \"OrderValue\")) {\n OnPropertyChanged(\"TotalValue\");\n }\n }\n }\n\n [DisplayName(\"Carriage Value\")]\n public decimal CarriageValue {\n get { return carriageValue; }\n set {\n if (SetField(ref carriageValue, value, \"CarriageValue\")) {\n OnPropertyChanged(\"TotalValue\");\n }\n }\n }\n\n [DisplayName(\"Total Value\")]\n public decimal TotalValue { get { return OrderValue + CarriageValue; } }\n}\n\n[Serializable]\npublic class NotifyBase { // purely for convenience\n [field: NonSerialized]\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected bool SetField<T>(ref T field, T value, string propertyName) {\n if (!EqualityComparer<T>.Default.Equals(field, value)) {\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n return false;\n }\n protected virtual void OnPropertyChanged(string propertyName) {\n PropertyChangedEventHandler handler = PropertyChanged;\n if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));\n }\n}\n"
},
{
"answer_id": 4529974,
"author": "Stephan Schinkel",
"author_id": 315331,
"author_profile": "https://Stackoverflow.com/users/315331",
"pm_score": 1,
"selected": false,
"text": "<ObjectState version=\"1\">\n <Field1>value</Field1>\n ... etc ...\n</ObjectState>\n - conversions\n - v1-v2\n - v2-v3\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40322/"
] |
348,037 | <p>I have a problem with the following code:</p>
<pre><code>for(i = 0;(i - 1)< n;i++)
{
char* b;
sprintf(b, "%d", i);
}
</code></pre>
<p>It compiles fine but when I run it it give me the infamous "0XC0000005 Access Violation" error. I have tried setting b to NULL, "", "0", 0 and a bunch of other stuff but then I get the "0XC0000005 Access Violation" error or "Expression: string != NULL. Any help would be appreciated!</p>
| [
{
"answer_id": 348045,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "sprintf sprintf for(i = 0;(i - 1)< n;i++)\n{\n char b[10];\n sprintf(b, \"%d\", i);\n}\n"
},
{
"answer_id": 348059,
"author": "user37875",
"author_id": 37875,
"author_profile": "https://Stackoverflow.com/users/37875",
"pm_score": 0,
"selected": false,
"text": "for(i = 0;(i - 1)< n;i++)\n{\nchar* b;\nchar a[100];\nb = a;\nsprintf(b, \"%d\", i);\n}\n"
},
{
"answer_id": 348060,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "int bufsize = snprintf(NULL, 0, formatstring, ...);\nchar *buffer = malloc(bufsize+1); # count doesn't include trailing nul\nif (buffer == NULL) out_of_memory_error();\nsnprintf(buffer, bufsize+1, formatstring, ...);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37875/"
] |
348,040 | <p>I know that <a href="http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port" rel="noreferrer">OpenCV was ported to Mac OS X</a>, however I did not find any info about a port to the iPhone.</p>
<p>I am not a Mac developer, so that I do not know whether a Mac OS X port is enough for the iPhone.</p>
<p>Does anyone know better than me? </p>
| [
{
"answer_id": 34981960,
"author": "Dair",
"author_id": 667648,
"author_profile": "https://Stackoverflow.com/users/667648",
"pm_score": 1,
"selected": false,
"text": "target 'MyApp' do\n pod 'OpenCV', '~> 3.0' \nend\n pod install"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19816/"
] |
348,090 | <p>My web app has a secure area which users log in to via a JSP. The JSP posts the user name and password to a servlet, which then checks to see if the users credentials are valid. If they are valid then the user is directed to the secure resource. How can I ensure that users can't just navigate to the secure resource without validating first?</p>
| [
{
"answer_id": 348134,
"author": "mtruesdell",
"author_id": 6479,
"author_profile": "https://Stackoverflow.com/users/6479",
"pm_score": 3,
"selected": false,
"text": "session.setAttribute(\"loggedIn\", \"true\"); session.setAttribute(\"loggedInUser\", \"someUserName\");"
},
{
"answer_id": 349287,
"author": "LenW",
"author_id": 41292,
"author_profile": "https://Stackoverflow.com/users/41292",
"pm_score": 2,
"selected": false,
"text": "<security-constraint>\n <web-resource-collection>\n <web-resource-name>Secure</web-resource-name>\n <url-pattern>/secure/*</url-pattern>\n </web-resource-collection>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16684/"
] |
348,093 | <p>Can someone please let me know how do I implement "Did you mean" feature in Lucene.net?</p>
<p>Thanks!</p>
| [
{
"answer_id": 490875,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 6,
"selected": true,
"text": " import org.apache.lucene.search.spell.SpellChecker;\n\n SpellChecker spellchecker = new SpellChecker(spellIndexDirectory);\n // To index a field of a user index:\n spellchecker.indexDictionary(new LuceneDictionary(my_lucene_reader, a_field));\n // To index a file containing words:\n spellchecker.indexDictionary(new PlainTextDictionary(new File(\"myfile.txt\")));\n String[] suggestions = spellchecker.suggestSimilar(\"misspelt\", 5);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40907/"
] |
348,109 | <p>Is hashing a password twice before storage any more or less secure than just hashing it once?</p>
<p>What I'm talking about is doing this:</p>
<pre><code>$hashed_password = hash(hash($plaintext_password));
</code></pre>
<p>instead of just this:</p>
<pre><code>$hashed_password = hash($plaintext_password);
</code></pre>
<p>If it is less secure, can you provide a good explanation (or a link to one)?</p>
<p>Also, does the hash function used make a difference? Does it make any difference if you mix md5 and sha1 (for example) instead of repeating the same hash function?</p>
<p>Note 1: When I say "double hashing" I'm talking about hashing a password twice in an attempt to make it more obscured. I'm not talking about the <a href="http://en.wikipedia.org/wiki/Double_hashing" rel="noreferrer">technique for resolving collisions</a>.</p>
<p><strong>Note 2: I know I need to add a random salt to really make it secure. The question is whether hashing twice with the same algorithm helps or hurts the hash.</strong></p>
| [
{
"answer_id": 348163,
"author": "CodeAndCats",
"author_id": 26335,
"author_profile": "https://Stackoverflow.com/users/26335",
"pm_score": 2,
"selected": false,
"text": "$hashed_password = md5( \"xxx\" + \"|\" + user_name + \"|\" + plaintext_password);\n"
},
{
"answer_id": 12220718,
"author": "hobbs",
"author_id": 152948,
"author_profile": "https://Stackoverflow.com/users/152948",
"pm_score": -1,
"selected": false,
"text": "md5(md5(md5(password)))"
},
{
"answer_id": 17396367,
"author": "ircmaxell",
"author_id": 338665,
"author_profile": "https://Stackoverflow.com/users/338665",
"pm_score": 8,
"selected": false,
"text": "$hashed_password1 = md5( md5( plaintext_password ) );\n$hashed_password2 = md5( plaintext_password );\n $h $m $h === hash($m) $m1 $m2 hash($m1) === hash($m2) ($m1, $m2) hash($m1) === hash($m2) $m1 function ourHash($input) {\n $result = 0;\n for ($i = 0; $i < strlen($input); $i++) {\n $result += ord($input[$i]);\n }\n return (string) ($result % 256);\n}\n var_dump(\n ourHash('abc'), // string(2) \"38\"\n ourHash('def'), // string(2) \"47\"\n ourHash('hij'), // string(2) \"59\"\n ourHash('klm') // string(2) \"68\"\n);\n $tests = array(\n \"abc\",\n \"def\",\n \"hij\",\n \"klm\",\n);\n\nforeach ($tests as $test) {\n $hash = $test;\n for ($i = 0; $i < 100; $i++) {\n $hash = ourHash($hash);\n }\n echo \"Hashing $test => $hash\\n\";\n}\n Hashing abc => 152\nHashing def => 152\nHashing hij => 155\nHashing klm => 155\n Hashing 0 => 48\nHashing 1 => 49\nHashing 2 => 50\nHashing 3 => 51\nHashing 4 => 52\nHashing 5 => 53\nHashing 6 => 54\nHashing 7 => 55\nHashing 8 => 56\nHashing 9 => 57\nHashing 10 => 97\nHashing 11 => 98\nHashing 12 => 99\nHashing 13 => 100\nHashing 14 => 101\nHashing 15 => 102\nHashing 16 => 103\nHashing 17 => 104\nHashing 18 => 105\nHashing 19 => 106\nHashing 20 => 98\nHashing 21 => 99\nHashing 22 => 100\nHashing 23 => 101\nHashing 24 => 102\nHashing 25 => 103\nHashing 26 => 104\nHashing 27 => 105\nHashing 28 => 106\nHashing 29 => 107\nHashing 30 => 99\nHashing 31 => 100\nHashing 32 => 101\nHashing 33 => 102\nHashing 34 => 103\nHashing 35 => 104\nHashing 36 => 105\nHashing 37 => 106\nHashing 38 => 107\nHashing 39 => 108\nHashing 40 => 100\nHashing 41 => 101\nHashing 42 => 102\nHashing 43 => 103\nHashing 44 => 104\nHashing 45 => 105\nHashing 46 => 106\nHashing 47 => 107\nHashing 48 => 108\nHashing 49 => 109\nHashing 50 => 101\nHashing 51 => 102\nHashing 52 => 103\nHashing 53 => 104\nHashing 54 => 105\nHashing 55 => 106\nHashing 56 => 107\nHashing 57 => 108\nHashing 58 => 109\nHashing 59 => 110\nHashing 60 => 102\nHashing 61 => 103\nHashing 62 => 104\nHashing 63 => 105\nHashing 64 => 106\nHashing 65 => 107\nHashing 66 => 108\nHashing 67 => 109\nHashing 68 => 110\nHashing 69 => 111\nHashing 70 => 103\nHashing 71 => 104\nHashing 72 => 105\nHashing 73 => 106\nHashing 74 => 107\nHashing 75 => 108\nHashing 76 => 109\nHashing 77 => 110\nHashing 78 => 111\nHashing 79 => 112\nHashing 80 => 104\nHashing 81 => 105\nHashing 82 => 106\nHashing 83 => 107\nHashing 84 => 108\nHashing 85 => 109\nHashing 86 => 110\nHashing 87 => 111\nHashing 88 => 112\nHashing 89 => 113\nHashing 90 => 105\nHashing 91 => 106\nHashing 92 => 107\nHashing 93 => 108\nHashing 94 => 109\nHashing 95 => 110\nHashing 96 => 111\nHashing 97 => 112\nHashing 98 => 113\nHashing 99 => 114\nHashing 100 => 145\nHashing 101 => 146\nHashing 102 => 147\nHashing 103 => 148\nHashing 104 => 149\nHashing 105 => 150\nHashing 106 => 151\nHashing 107 => 152\nHashing 108 => 153\nHashing 109 => 154\nHashing 110 => 146\nHashing 111 => 147\nHashing 112 => 148\nHashing 113 => 149\nHashing 114 => 150\nHashing 115 => 151\nHashing 116 => 152\nHashing 117 => 153\nHashing 118 => 154\nHashing 119 => 155\nHashing 120 => 147\nHashing 121 => 148\nHashing 122 => 149\nHashing 123 => 150\nHashing 124 => 151\nHashing 125 => 152\nHashing 126 => 153\nHashing 127 => 154\nHashing 128 => 155\nHashing 129 => 156\nHashing 130 => 148\nHashing 131 => 149\nHashing 132 => 150\nHashing 133 => 151\nHashing 134 => 152\nHashing 135 => 153\nHashing 136 => 154\nHashing 137 => 155\nHashing 138 => 156\nHashing 139 => 157\nHashing 140 => 149\nHashing 141 => 150\nHashing 142 => 151\nHashing 143 => 152\nHashing 144 => 153\nHashing 145 => 154\nHashing 146 => 155\nHashing 147 => 156\nHashing 148 => 157\nHashing 149 => 158\nHashing 150 => 150\nHashing 151 => 151\nHashing 152 => 152\nHashing 153 => 153\nHashing 154 => 154\nHashing 155 => 155\nHashing 156 => 156\nHashing 157 => 157\nHashing 158 => 158\nHashing 159 => 159\nHashing 160 => 151\nHashing 161 => 152\nHashing 162 => 153\nHashing 163 => 154\nHashing 164 => 155\nHashing 165 => 156\nHashing 166 => 157\nHashing 167 => 158\nHashing 168 => 159\nHashing 169 => 160\nHashing 170 => 152\nHashing 171 => 153\nHashing 172 => 154\nHashing 173 => 155\nHashing 174 => 156\nHashing 175 => 157\nHashing 176 => 158\nHashing 177 => 159\nHashing 178 => 160\nHashing 179 => 161\nHashing 180 => 153\nHashing 181 => 154\nHashing 182 => 155\nHashing 183 => 156\nHashing 184 => 157\nHashing 185 => 158\nHashing 186 => 159\nHashing 187 => 160\nHashing 188 => 161\nHashing 189 => 162\nHashing 190 => 154\nHashing 191 => 155\nHashing 192 => 156\nHashing 193 => 157\nHashing 194 => 158\nHashing 195 => 159\nHashing 196 => 160\nHashing 197 => 161\nHashing 198 => 162\nHashing 199 => 163\nHashing 200 => 146\nHashing 201 => 147\nHashing 202 => 148\nHashing 203 => 149\nHashing 204 => 150\nHashing 205 => 151\nHashing 206 => 152\nHashing 207 => 153\nHashing 208 => 154\nHashing 209 => 155\nHashing 210 => 147\nHashing 211 => 148\nHashing 212 => 149\nHashing 213 => 150\nHashing 214 => 151\nHashing 215 => 152\nHashing 216 => 153\nHashing 217 => 154\nHashing 218 => 155\nHashing 219 => 156\nHashing 220 => 148\nHashing 221 => 149\nHashing 222 => 150\nHashing 223 => 151\nHashing 224 => 152\nHashing 225 => 153\nHashing 226 => 154\nHashing 227 => 155\nHashing 228 => 156\nHashing 229 => 157\nHashing 230 => 149\nHashing 231 => 150\nHashing 232 => 151\nHashing 233 => 152\nHashing 234 => 153\nHashing 235 => 154\nHashing 236 => 155\nHashing 237 => 156\nHashing 238 => 157\nHashing 239 => 158\nHashing 240 => 150\nHashing 241 => 151\nHashing 242 => 152\nHashing 243 => 153\nHashing 244 => 154\nHashing 245 => 155\nHashing 246 => 156\nHashing 247 => 157\nHashing 248 => 158\nHashing 249 => 159\nHashing 250 => 151\nHashing 251 => 152\nHashing 252 => 153\nHashing 253 => 154\nHashing 254 => 155\nHashing 255 => 156\n Hashing 0 => 153\nHashing 1 => 154\nHashing 2 => 155\nHashing 3 => 156\nHashing 4 => 157\nHashing 5 => 158\nHashing 6 => 150\nHashing 7 => 151\nHashing 8 => 152\nHashing 9 => 153\nHashing 10 => 157\nHashing 11 => 158\nHashing 12 => 150\nHashing 13 => 154\nHashing 14 => 155\nHashing 15 => 156\nHashing 16 => 157\nHashing 17 => 158\nHashing 18 => 150\nHashing 19 => 151\nHashing 20 => 158\nHashing 21 => 150\nHashing 22 => 154\nHashing 23 => 155\nHashing 24 => 156\nHashing 25 => 157\nHashing 26 => 158\nHashing 27 => 150\nHashing 28 => 151\nHashing 29 => 152\nHashing 30 => 150\nHashing 31 => 154\nHashing 32 => 155\nHashing 33 => 156\nHashing 34 => 157\nHashing 35 => 158\nHashing 36 => 150\nHashing 37 => 151\nHashing 38 => 152\nHashing 39 => 153\nHashing 40 => 154\nHashing 41 => 155\nHashing 42 => 156\nHashing 43 => 157\nHashing 44 => 158\nHashing 45 => 150\nHashing 46 => 151\nHashing 47 => 152\nHashing 48 => 153\nHashing 49 => 154\nHashing 50 => 155\nHashing 51 => 156\nHashing 52 => 157\nHashing 53 => 158\nHashing 54 => 150\nHashing 55 => 151\nHashing 56 => 152\nHashing 57 => 153\nHashing 58 => 154\nHashing 59 => 155\nHashing 60 => 156\nHashing 61 => 157\nHashing 62 => 158\nHashing 63 => 150\nHashing 64 => 151\nHashing 65 => 152\nHashing 66 => 153\nHashing 67 => 154\nHashing 68 => 155\nHashing 69 => 156\nHashing 70 => 157\nHashing 71 => 158\nHashing 72 => 150\nHashing 73 => 151\nHashing 74 => 152\nHashing 75 => 153\nHashing 76 => 154\nHashing 77 => 155\nHashing 78 => 156\nHashing 79 => 157\nHashing 80 => 158\nHashing 81 => 150\nHashing 82 => 151\nHashing 83 => 152\nHashing 84 => 153\nHashing 85 => 154\nHashing 86 => 155\nHashing 87 => 156\nHashing 88 => 157\nHashing 89 => 158\nHashing 90 => 150\nHashing 91 => 151\nHashing 92 => 152\nHashing 93 => 153\nHashing 94 => 154\nHashing 95 => 155\nHashing 96 => 156\nHashing 97 => 157\nHashing 98 => 158\nHashing 99 => 150\nHashing 100 => 154\nHashing 101 => 155\nHashing 102 => 156\nHashing 103 => 157\nHashing 104 => 158\nHashing 105 => 150\nHashing 106 => 151\nHashing 107 => 152\nHashing 108 => 153\nHashing 109 => 154\nHashing 110 => 155\nHashing 111 => 156\nHashing 112 => 157\nHashing 113 => 158\nHashing 114 => 150\nHashing 115 => 151\nHashing 116 => 152\nHashing 117 => 153\nHashing 118 => 154\nHashing 119 => 155\nHashing 120 => 156\nHashing 121 => 157\nHashing 122 => 158\nHashing 123 => 150\nHashing 124 => 151\nHashing 125 => 152\nHashing 126 => 153\nHashing 127 => 154\nHashing 128 => 155\nHashing 129 => 156\nHashing 130 => 157\nHashing 131 => 158\nHashing 132 => 150\nHashing 133 => 151\nHashing 134 => 152\nHashing 135 => 153\nHashing 136 => 154\nHashing 137 => 155\nHashing 138 => 156\nHashing 139 => 157\nHashing 140 => 158\nHashing 141 => 150\nHashing 142 => 151\nHashing 143 => 152\nHashing 144 => 153\nHashing 145 => 154\nHashing 146 => 155\nHashing 147 => 156\nHashing 148 => 157\nHashing 149 => 158\nHashing 150 => 150\nHashing 151 => 151\nHashing 152 => 152\nHashing 153 => 153\nHashing 154 => 154\nHashing 155 => 155\nHashing 156 => 156\nHashing 157 => 157\nHashing 158 => 158\nHashing 159 => 159\nHashing 160 => 151\nHashing 161 => 152\nHashing 162 => 153\nHashing 163 => 154\nHashing 164 => 155\nHashing 165 => 156\nHashing 166 => 157\nHashing 167 => 158\nHashing 168 => 159\nHashing 169 => 151\nHashing 170 => 152\nHashing 171 => 153\nHashing 172 => 154\nHashing 173 => 155\nHashing 174 => 156\nHashing 175 => 157\nHashing 176 => 158\nHashing 177 => 159\nHashing 178 => 151\nHashing 179 => 152\nHashing 180 => 153\nHashing 181 => 154\nHashing 182 => 155\nHashing 183 => 156\nHashing 184 => 157\nHashing 185 => 158\nHashing 186 => 159\nHashing 187 => 151\nHashing 188 => 152\nHashing 189 => 153\nHashing 190 => 154\nHashing 191 => 155\nHashing 192 => 156\nHashing 193 => 157\nHashing 194 => 158\nHashing 195 => 159\nHashing 196 => 151\nHashing 197 => 152\nHashing 198 => 153\nHashing 199 => 154\nHashing 200 => 155\nHashing 201 => 156\nHashing 202 => 157\nHashing 203 => 158\nHashing 204 => 150\nHashing 205 => 151\nHashing 206 => 152\nHashing 207 => 153\nHashing 208 => 154\nHashing 209 => 155\nHashing 210 => 156\nHashing 211 => 157\nHashing 212 => 158\nHashing 213 => 150\nHashing 214 => 151\nHashing 215 => 152\nHashing 216 => 153\nHashing 217 => 154\nHashing 218 => 155\nHashing 219 => 156\nHashing 220 => 157\nHashing 221 => 158\nHashing 222 => 150\nHashing 223 => 151\nHashing 224 => 152\nHashing 225 => 153\nHashing 226 => 154\nHashing 227 => 155\nHashing 228 => 156\nHashing 229 => 157\nHashing 230 => 158\nHashing 231 => 150\nHashing 232 => 151\nHashing 233 => 152\nHashing 234 => 153\nHashing 235 => 154\nHashing 236 => 155\nHashing 237 => 156\nHashing 238 => 157\nHashing 239 => 158\nHashing 240 => 150\nHashing 241 => 151\nHashing 242 => 152\nHashing 243 => 153\nHashing 244 => 154\nHashing 245 => 155\nHashing 246 => 156\nHashing 247 => 157\nHashing 248 => 158\nHashing 249 => 159\nHashing 250 => 151\nHashing 251 => 152\nHashing 252 => 153\nHashing 253 => 154\nHashing 254 => 155\nHashing 255 => 156\n S(∞) S(256) $input $output MD5 S(∞) S(2^128) MD5(S(output)) md5 2^128 $output = md5($input); // 2^128 possibilities\n$output = md5($output); // < 2^128 possibilities\n$output = md5($output); // < 2^128 possibilities\n$output = md5($output); // < 2^128 possibilities\n$output = md5($output); // < 2^128 possibilities\n $output = md5($input); // 2^128 possibilities\n$output = md5($input . $output); // 2^128 possibilities\n$output = md5($input . $output); // 2^128 possibilities\n$output = md5($input . $output); // 2^128 possibilities\n$output = md5($input . $output); // 2^128 possibilities \n $input $input 2^128 $input ourHash() $hash = ourHash($input . $hash); Hashing 0 => 201\nHashing 1 => 212\nHashing 2 => 199\nHashing 3 => 201\nHashing 4 => 203\nHashing 5 => 205\nHashing 6 => 207\nHashing 7 => 209\nHashing 8 => 211\nHashing 9 => 204\nHashing 10 => 251\nHashing 11 => 147\nHashing 12 => 251\nHashing 13 => 148\nHashing 14 => 253\nHashing 15 => 0\nHashing 16 => 1\nHashing 17 => 2\nHashing 18 => 161\nHashing 19 => 163\nHashing 20 => 147\nHashing 21 => 251\nHashing 22 => 148\nHashing 23 => 253\nHashing 24 => 0\nHashing 25 => 1\nHashing 26 => 2\nHashing 27 => 161\nHashing 28 => 163\nHashing 29 => 8\nHashing 30 => 251\nHashing 31 => 148\nHashing 32 => 253\nHashing 33 => 0\nHashing 34 => 1\nHashing 35 => 2\nHashing 36 => 161\nHashing 37 => 163\nHashing 38 => 8\nHashing 39 => 4\nHashing 40 => 148\nHashing 41 => 253\nHashing 42 => 0\nHashing 43 => 1\nHashing 44 => 2\nHashing 45 => 161\nHashing 46 => 163\nHashing 47 => 8\nHashing 48 => 4\nHashing 49 => 9\nHashing 50 => 253\nHashing 51 => 0\nHashing 52 => 1\nHashing 53 => 2\nHashing 54 => 161\nHashing 55 => 163\nHashing 56 => 8\nHashing 57 => 4\nHashing 58 => 9\nHashing 59 => 11\nHashing 60 => 0\nHashing 61 => 1\nHashing 62 => 2\nHashing 63 => 161\nHashing 64 => 163\nHashing 65 => 8\nHashing 66 => 4\nHashing 67 => 9\nHashing 68 => 11\nHashing 69 => 4\nHashing 70 => 1\nHashing 71 => 2\nHashing 72 => 161\nHashing 73 => 163\nHashing 74 => 8\nHashing 75 => 4\nHashing 76 => 9\nHashing 77 => 11\nHashing 78 => 4\nHashing 79 => 3\nHashing 80 => 2\nHashing 81 => 161\nHashing 82 => 163\nHashing 83 => 8\nHashing 84 => 4\nHashing 85 => 9\nHashing 86 => 11\nHashing 87 => 4\nHashing 88 => 3\nHashing 89 => 17\nHashing 90 => 161\nHashing 91 => 163\nHashing 92 => 8\nHashing 93 => 4\nHashing 94 => 9\nHashing 95 => 11\nHashing 96 => 4\nHashing 97 => 3\nHashing 98 => 17\nHashing 99 => 13\nHashing 100 => 246\nHashing 101 => 248\nHashing 102 => 49\nHashing 103 => 44\nHashing 104 => 255\nHashing 105 => 198\nHashing 106 => 43\nHashing 107 => 51\nHashing 108 => 202\nHashing 109 => 2\nHashing 110 => 248\nHashing 111 => 49\nHashing 112 => 44\nHashing 113 => 255\nHashing 114 => 198\nHashing 115 => 43\nHashing 116 => 51\nHashing 117 => 202\nHashing 118 => 2\nHashing 119 => 51\nHashing 120 => 49\nHashing 121 => 44\nHashing 122 => 255\nHashing 123 => 198\nHashing 124 => 43\nHashing 125 => 51\nHashing 126 => 202\nHashing 127 => 2\nHashing 128 => 51\nHashing 129 => 53\nHashing 130 => 44\nHashing 131 => 255\nHashing 132 => 198\nHashing 133 => 43\nHashing 134 => 51\nHashing 135 => 202\nHashing 136 => 2\nHashing 137 => 51\nHashing 138 => 53\nHashing 139 => 55\nHashing 140 => 255\nHashing 141 => 198\nHashing 142 => 43\nHashing 143 => 51\nHashing 144 => 202\nHashing 145 => 2\nHashing 146 => 51\nHashing 147 => 53\nHashing 148 => 55\nHashing 149 => 58\nHashing 150 => 198\nHashing 151 => 43\nHashing 152 => 51\nHashing 153 => 202\nHashing 154 => 2\nHashing 155 => 51\nHashing 156 => 53\nHashing 157 => 55\nHashing 158 => 58\nHashing 159 => 0\nHashing 160 => 43\nHashing 161 => 51\nHashing 162 => 202\nHashing 163 => 2\nHashing 164 => 51\nHashing 165 => 53\nHashing 166 => 55\nHashing 167 => 58\nHashing 168 => 0\nHashing 169 => 209\nHashing 170 => 51\nHashing 171 => 202\nHashing 172 => 2\nHashing 173 => 51\nHashing 174 => 53\nHashing 175 => 55\nHashing 176 => 58\nHashing 177 => 0\nHashing 178 => 209\nHashing 179 => 216\nHashing 180 => 202\nHashing 181 => 2\nHashing 182 => 51\nHashing 183 => 53\nHashing 184 => 55\nHashing 185 => 58\nHashing 186 => 0\nHashing 187 => 209\nHashing 188 => 216\nHashing 189 => 219\nHashing 190 => 2\nHashing 191 => 51\nHashing 192 => 53\nHashing 193 => 55\nHashing 194 => 58\nHashing 195 => 0\nHashing 196 => 209\nHashing 197 => 216\nHashing 198 => 219\nHashing 199 => 220\nHashing 200 => 248\nHashing 201 => 49\nHashing 202 => 44\nHashing 203 => 255\nHashing 204 => 198\nHashing 205 => 43\nHashing 206 => 51\nHashing 207 => 202\nHashing 208 => 2\nHashing 209 => 51\nHashing 210 => 49\nHashing 211 => 44\nHashing 212 => 255\nHashing 213 => 198\nHashing 214 => 43\nHashing 215 => 51\nHashing 216 => 202\nHashing 217 => 2\nHashing 218 => 51\nHashing 219 => 53\nHashing 220 => 44\nHashing 221 => 255\nHashing 222 => 198\nHashing 223 => 43\nHashing 224 => 51\nHashing 225 => 202\nHashing 226 => 2\nHashing 227 => 51\nHashing 228 => 53\nHashing 229 => 55\nHashing 230 => 255\nHashing 231 => 198\nHashing 232 => 43\nHashing 233 => 51\nHashing 234 => 202\nHashing 235 => 2\nHashing 236 => 51\nHashing 237 => 53\nHashing 238 => 55\nHashing 239 => 58\nHashing 240 => 198\nHashing 241 => 43\nHashing 242 => 51\nHashing 243 => 202\nHashing 244 => 2\nHashing 245 => 51\nHashing 246 => 53\nHashing 247 => 55\nHashing 248 => 58\nHashing 249 => 0\nHashing 250 => 43\nHashing 251 => 51\nHashing 252 => 202\nHashing 253 => 2\nHashing 254 => 51\nHashing 255 => 53\n 0 3 md5($input . md5($input)); md5($input) T_1 = Hash (P || S) ,\nT_2 = Hash (T_1) ,\n...\nT_c = Hash (T_{c-1}) \n c P S U_1 = PRF (P, S || INT (i)) ,\nU_2 = PRF (P, U_1) ,\n...\nU_c = PRF (P, U_{c-1})\n PRF(P, S) = Hash(P || S) Hash $hash = $input;\n$i = 10000;\ndo {\n $hash = hash($input . $hash);\n} while ($i-- > 0);\n S(∞) S(n) S(∞) S(n) S(∞) -> S(n)\nS(∞) -> S(n)\nS(∞) -> S(n)\nS(∞) -> S(n)\nS(∞) -> S(n)\nS(∞) -> S(n)\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
348,112 | <p><a href="https://stackoverflow.com/questions/116090/how-do-i-kill-a-process-using-vbnet-or-c">This</a> only helps kills processes on the local machine. How do I kill processes on remote machines?</p>
| [
{
"answer_id": 20208856,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 1,
"selected": false,
"text": "ConnectionOptions connectoptions = new ConnectionOptions();\nconnectoptions.Username = string.Format(@\"carpark\\{0}\", \"domainOrWorkspace\\RemoteUsername\");\nconnectoptions.Password = \"remoteComputersPasssword\";\n\nManagementScope scope = new ManagementScope(@\"\\\\\" + ipAddress + @\"\\root\\cimv2\");\nscope.Options = connectoptions;\n\nSelectQuery query = new SelectQuery(\"select * from Win32_Process where name = 'MYPROCESS.EXE'\");\n\nusing (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))\n{\n ManagementObjectCollection collection = searcher.Get();\n\n if (collection.Count > 0)\n {\n foreach (ManagementObject mo in collection)\n {\n uint processId = (uint)mo[\"ProcessId\"];\n string commandLine = (string) mo[\"CommandLine\"];\n\n string expectedCommandLine = string.Format(\"MYPROCESS.EXE {0} {1}\", deviceId, deviceType);\n\n if (commandLine != null && commandLine.ToUpper() == expectedCommandLine.ToUpper())\n {\n mo.InvokeMethod(\"Terminate\", null);\n break;\n }\n }\n }\n}\n"
},
{
"answer_id": 25390702,
"author": "lbmouse",
"author_id": 3957595,
"author_profile": "https://Stackoverflow.com/users/3957595",
"pm_score": 2,
"selected": false,
"text": "ManagementScope managementScope = new ManagementScope(\"\\\\\\\\servername\\\\root\\\\cimv2\");\nmanagementScope.Connect();\nObjectQuery objectQuery = new ObjectQuery(\"SELECT * FROM Win32_Process Where Name = 'processname'\");\nManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);\nManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();\nforeach (ManagementObject managementObject in managementObjectCollection)\n{\n managementObject.InvokeMethod(\"Terminate\", null);\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
348,122 | <p>Is there a possibility to deactivate / activate all try catch blocks in the whole project as easy as clicking a button?</p>
<p>I need this for debugging when I don't want the catch block to handle the exception, but instead prefer that VS breaks into the code as if the try catch block was not there. </p>
<p>At the moment I am commenting out the try/catch blocks but this is inefficient.</p>
<p>Environment: VS 2008 with C# as language.</p>
| [
{
"answer_id": 48085535,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Namespace Global.System\n Public Class NeverOccurException\n Inherits Exception\n End Class\nEnd Namespace\n #If DEBUG\n Imports CatchAtReleaseException = System.NeverOccurException\n#Else\n Imports CatchAtReleaseException = System.Exception\n#End If\n 'Compiled in DEBUG-Mode the TryCatch is \"disabled\", because the\n 'the ALIAS CatchAtReleaseException is set to \"NeverOccurException\"\n\n 'Compiled as RELEASE the TryCatch is \"enabled\", because the ALIAS\n 'is set to the regular \"System.Exception\"\n\n Public Sub SampleSub()\n Try\n '...\n Catch ex As CatchAtReleaseException\n End Try\n End Sub\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,127 | <p>I have the following situation:</p>
<p>I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop.
I want to be able to check whether the loop is still running or not.</p>
<p>For this, i'm doing, for each loop run:</p>
<pre><code>LastTimeIDidTheLoop = new Date();
</code></pre>
<p>And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:</p>
<pre><code>if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
</code></pre>
<p>How do I do this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 348133,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 4,
"selected": true,
"text": "newDate = new Date()\nnewDate.setSeconds(newDate.getSeconds()-30);\nif (newDate > LastTimeIDidTheLoop) {\n alert(\"oops\");\n}\n"
},
{
"answer_id": 348167,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": -1,
"selected": false,
"text": "controlDate = new Date();\ncontrolDate.setSeconds(controlDate.getSeconds() + 30);\n\nif (LastTimeIDidTheLoop > controlDate) {\n...\n"
},
{
"answer_id": 348172,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; \nif (diffSeconds > 30)\n{\n // ...\n}\n"
},
{
"answer_id": 30985591,
"author": "Alexandre N.",
"author_id": 1398758,
"author_profile": "https://Stackoverflow.com/users/1398758",
"pm_score": 0,
"selected": false,
"text": "var dateDiff = function(fromdate, todate) {\n var diff = todate - fromdate;\n return Math.floor(diff/1000);\n}\n if (dateDiff(fromdate, todate) > 30){\n alert(\"oops\");\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
348,128 | <p>This is silly, but I haven't found this information. If you have names of concepts and suitable references, just let me know.</p>
<p>I'd like to understand how should I validate a given named id for a generic entity, like, say, an email login, just like Yahoo, Google and Microsoft do.</p>
<p>I mean... If you do have an user named foo, trying to create foo2 will be denied, as it is likely to be someone trying to mislead users by using a fake id.</p>
| [
{
"answer_id": 348133,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 4,
"selected": true,
"text": "newDate = new Date()\nnewDate.setSeconds(newDate.getSeconds()-30);\nif (newDate > LastTimeIDidTheLoop) {\n alert(\"oops\");\n}\n"
},
{
"answer_id": 348167,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": -1,
"selected": false,
"text": "controlDate = new Date();\ncontrolDate.setSeconds(controlDate.getSeconds() + 30);\n\nif (LastTimeIDidTheLoop > controlDate) {\n...\n"
},
{
"answer_id": 348172,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; \nif (diffSeconds > 30)\n{\n // ...\n}\n"
},
{
"answer_id": 30985591,
"author": "Alexandre N.",
"author_id": 1398758,
"author_profile": "https://Stackoverflow.com/users/1398758",
"pm_score": 0,
"selected": false,
"text": "var dateDiff = function(fromdate, todate) {\n var diff = todate - fromdate;\n return Math.floor(diff/1000);\n}\n if (dateDiff(fromdate, todate) > 30){\n alert(\"oops\");\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39261/"
] |
348,170 | <p>I mistakenly added files to Git using the command:</p>
<pre><code>git add myfile.txt
</code></pre>
<p>I have not yet run <code>git commit</code>. How do I undo this so that these changes will not be included in the commit?</p>
| [
{
"answer_id": 348234,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 15,
"selected": true,
"text": "git add git reset <file>\n git reset\n git reset HEAD <file> git reset HEAD HEAD HEAD"
},
{
"answer_id": 348303,
"author": "Paul Beckingham",
"author_id": 14356,
"author_profile": "https://Stackoverflow.com/users/14356",
"pm_score": 9,
"selected": false,
"text": "git status\n use \"git reset HEAD <file>...\" to unstage\n (use \"git rm --cached <file>...\" to unstage)\n"
},
{
"answer_id": 682343,
"author": "Rhubarb",
"author_id": 20479,
"author_profile": "https://Stackoverflow.com/users/20479",
"pm_score": 11,
"selected": false,
"text": "git rm --cached <added_file_to_undo>\n git reset .\n fatal: Failed to resolve 'HEAD' as a valid ref.\n git init git add . git status git reset . ...\n# Changes to be committed:\n# (use \"git rm --cached <file>...\" to unstage)\n...\n git rm --cached FILE git rm git help rm git rm --cached .\n add . rm -r git rm -r --cached .\n -n git add -n .\n git help rm --cached"
},
{
"answer_id": 1026792,
"author": "Ran",
"author_id": 10272,
"author_profile": "https://Stackoverflow.com/users/10272",
"pm_score": 5,
"selected": false,
"text": "git rm --cached FILE\n"
},
{
"answer_id": 1764679,
"author": "Kokotte23",
"author_id": 214765,
"author_profile": "https://Stackoverflow.com/users/214765",
"pm_score": 5,
"selected": false,
"text": "$> git --version\ngit version 1.6.2.1\n git reset HEAD .\n"
},
{
"answer_id": 1764694,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 6,
"selected": false,
"text": "git reset .git"
},
{
"answer_id": 1876958,
"author": "braitsch",
"author_id": 228315,
"author_profile": "https://Stackoverflow.com/users/228315",
"pm_score": 7,
"selected": false,
"text": "git rm --cached . -r\n"
},
{
"answer_id": 2862736,
"author": "Donovan",
"author_id": 344703,
"author_profile": "https://Stackoverflow.com/users/344703",
"pm_score": 5,
"selected": false,
"text": "git reset git add ."
},
{
"answer_id": 3688108,
"author": "takeshin",
"author_id": 234780,
"author_profile": "https://Stackoverflow.com/users/234780",
"pm_score": 8,
"selected": false,
"text": "git add git stage\n git add git stage git unstage git unadd git reset HEAD --\n git config --global alias.unadd 'reset HEAD --'\ngit config --global alias.unstage 'reset HEAD --'\n git add file1\ngit stage file2\ngit unadd file2\ngit unstage file1\n git a # For staging\ngit u # For unstaging\n"
},
{
"answer_id": 3840321,
"author": "electblake",
"author_id": 253608,
"author_profile": "https://Stackoverflow.com/users/253608",
"pm_score": 7,
"selected": false,
"text": "git reset git unadd git config --global alias.unadd \"reset HEAD\"\n git unadd foo.txt bar.txt\n git reset HEAD foo.txt bar.txt\n"
},
{
"answer_id": 6049090,
"author": "leonbloy",
"author_id": 277304,
"author_profile": "https://Stackoverflow.com/users/277304",
"pm_score": 8,
"selected": false,
"text": "git reset .git git gc --prune=now\n git add git reset HEAD <file> git rm --cached <file> git add git add <file> <file> git add <file> git add git rm --cached <file> git reset HEAD <file> git reset HEAD git rm --cached git reset HEAD git add $ git init\n$ echo \"version 1\" > file.txt\n$ git add file.txt # First add of file.txt\n$ git commit -m 'first commit'\n$ echo \"version 2\" > file.txt\n$ git add file.txt # Stage (don't commit) \"version 2\" of file.txt\n$ git diff --cached file.txt\n-version 1\n+version 2\n$ echo \"version 3\" > file.txt\n$ git diff file.txt\n-version 2\n+version 3\n$ git add file.txt # Oops we didn't mean this\n$ git reset HEAD file.txt # Undo?\n$ git diff --cached file.txt # No dif, of course. stage == HEAD\n$ git diff file.txt # We have irrevocably lost \"version 2\"\n-version 1\n+version 3\n git commit -a"
},
{
"answer_id": 7542639,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 6,
"selected": false,
"text": "git init git reset git add -A git reset"
},
{
"answer_id": 7734259,
"author": "Khaja Minhajuddin",
"author_id": 24105,
"author_profile": "https://Stackoverflow.com/users/24105",
"pm_score": 7,
"selected": false,
"text": "git gui\n"
},
{
"answer_id": 8975450,
"author": "powlo",
"author_id": 944717,
"author_profile": "https://Stackoverflow.com/users/944717",
"pm_score": 5,
"selected": false,
"text": "git reset <path_to_file>\nfatal: ambiguous argument '<path_to_file>': unknown revision or path not in the working tree.\nUse '--' to separate paths from revisions\n\ngit reset -- <path_to_file>\nUnstaged changes after reset:\nM <path_to_file>\n"
},
{
"answer_id": 10209776,
"author": "Alex North-Keys",
"author_id": 1306959,
"author_profile": "https://Stackoverflow.com/users/1306959",
"pm_score": 6,
"selected": false,
"text": "git add -i $ git add foo\n$ git status\n# On branch master\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n# new file: foo\n#\n# Untracked files:\n# (use \"git add <file>...\" to include in what will be committed)\n# [...]#\n $ git add -i\n staged unstaged path\n 1: +1/-0 nothing foo\n\n*** Commands ***\n 1: [s]tatus 2: [u]pdate 3: [r]evert 4: [a]dd untracked\n 5: [p]atch 6: [d]iff 7: [q]uit 8: [h]elp\nWhat now> r\n staged unstaged path\n 1: +1/-0 nothing [f]oo\nRevert>> 1\n staged unstaged path\n* 1: +1/-0 nothing [f]oo\nRevert>> \nnote: foo is untracked now.\nreverted one path\n\n*** Commands ***\n 1: [s]tatus 2: [u]pdate 3: [r]evert 4: [a]dd untracked\n 5: [p]atch 6: [d]iff 7: [q]uit 8: [h]elp\nWhat now> q\nBye.\n$\n $ git status\n# On branch master\n# Untracked files:\n# (use \"git add <file>...\" to include in what will be committed)\n# [...]\n# foo\nnothing added to commit but untracked files present (use \"git add\" to track)\n$\n"
},
{
"answer_id": 11664712,
"author": "Zorayr",
"author_id": 577878,
"author_profile": "https://Stackoverflow.com/users/577878",
"pm_score": 5,
"selected": false,
"text": "git reset *\n"
},
{
"answer_id": 14629554,
"author": "wallerjake",
"author_id": 1876427,
"author_profile": "https://Stackoverflow.com/users/1876427",
"pm_score": 4,
"selected": false,
"text": "git reset HEAD filename.txt\n git add -p \n"
},
{
"answer_id": 15702135,
"author": "sjas",
"author_id": 805284,
"author_profile": "https://Stackoverflow.com/users/805284",
"pm_score": 7,
"selected": false,
"text": "git add . git add <file> git reset HEAD <file>\n # Think `svn revert <file>` IIRC.\n git reset HEAD <file>\n git checkout <file>\n\n # If you have a `<branch>` named like `<file>`, use:\n git checkout -- <file>\n git reset --hard HEAD <file> git rm --cached <file>\n <file> git rm <file>\n"
},
{
"answer_id": 18475609,
"author": "boulder_ruby",
"author_id": 1276506,
"author_profile": "https://Stackoverflow.com/users/1276506",
"pm_score": 5,
"selected": false,
"text": "* git reset HEAD *.prj\ngit reset HEAD *.bmp\ngit reset HEAD *gdb*\n"
},
{
"answer_id": 21171527,
"author": "Michael_Scharf",
"author_id": 2297345,
"author_profile": "https://Stackoverflow.com/users/2297345",
"pm_score": 7,
"selected": false,
"text": "git add git rm --cached file git reset HEAD file git reset HEAD file\n git rm --cached file git commit git status On branch master\nChanges to be committed:\n (use \"git reset HEAD <file>...\" to unstage)\n\n new file: my_new_file.txt\n modified: my_modified_file.txt\n"
},
{
"answer_id": 33281737,
"author": "Jonathan",
"author_id": 964102,
"author_profile": "https://Stackoverflow.com/users/964102",
"pm_score": 4,
"selected": false,
"text": "git add -i\n"
},
{
"answer_id": 34152896,
"author": "miva2",
"author_id": 2808913,
"author_profile": "https://Stackoverflow.com/users/2808913",
"pm_score": 4,
"selected": false,
"text": "reset"
},
{
"answer_id": 38313960,
"author": "Rahul Sinha",
"author_id": 3389121,
"author_profile": "https://Stackoverflow.com/users/3389121",
"pm_score": 6,
"selected": false,
"text": "git reset filename.txt\n filename.txt"
},
{
"answer_id": 39818808,
"author": "Anirudh Sood",
"author_id": 1308638,
"author_profile": "https://Stackoverflow.com/users/1308638",
"pm_score": 4,
"selected": false,
"text": "git add git reset filename\n"
},
{
"answer_id": 39850612,
"author": "Vidura Mudalige",
"author_id": 3719179,
"author_profile": "https://Stackoverflow.com/users/3719179",
"pm_score": 5,
"selected": false,
"text": "newFile.txt git add newFile.txt git reset newFile.txt"
},
{
"answer_id": 44782247,
"author": "Mohideen bin Mohammed",
"author_id": 4453737,
"author_profile": "https://Stackoverflow.com/users/4453737",
"pm_score": 4,
"selected": false,
"text": "git add myfile.txt git reset HEAD myfile.txt # This will undo it.\n"
},
{
"answer_id": 44800259,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 7,
"selected": false,
"text": "myfile.txt git reset HEAD myfile.txt\n git reset Head"
},
{
"answer_id": 46961177,
"author": "Joseph Mathew",
"author_id": 7800475,
"author_profile": "https://Stackoverflow.com/users/7800475",
"pm_score": 4,
"selected": false,
"text": "git reset filename.txt \n"
},
{
"answer_id": 54418554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "git reset git add git reset HEAD <file to change> git checkout HEAD <file(s) or path(s)> git reset --hard git reset -hard HEAD git checkout HEAD --soft git reset --mixed"
},
{
"answer_id": 62569076,
"author": "prosoitos",
"author_id": 9210961,
"author_profile": "https://Stackoverflow.com/users/9210961",
"pm_score": 6,
"selected": false,
"text": "git restore --staged <file>\n git restore --staged .\n git restore --staged git status git reset HEAD <file>"
},
{
"answer_id": 63580068,
"author": "Sam Macharia",
"author_id": 7842910,
"author_profile": "https://Stackoverflow.com/users/7842910",
"pm_score": 2,
"selected": false,
"text": "git reset <filename> git add . git reset git reset git add . Folder/SubFolder1/file1.txt\nFolder/SubFolder2/fig1.png\nFolder/SubFolderX/fig.svg\nFolder/SubFolder3/<manyfiles>\nFolder/SubFolder4/<file1.py, file2.py, ..., file60.py, ...>\n fig1.png SubFolderX file60.py bash shell script git_add.sh git reset git reset -- git_add.sh git_add.sh #!/bin/bash\n\ngit add .\ngit reset -- Folder/SubFolder2/fig1.png\ngit reset -- Folder/SubFolderX\ngit reset -- Folder/SubFolder4/file60.py\n #!/bin/bash source git_add.sh git commit -m \"some comment\" git push -u origin master git add . .gitignore"
},
{
"answer_id": 63851961,
"author": "akhtarvahid",
"author_id": 6544460,
"author_profile": "https://Stackoverflow.com/users/6544460",
"pm_score": 5,
"selected": false,
"text": "git reset File.txt\n git reset File1.txt File2.txt File3.txt\n git reset src/components/home/Home.js src/components/listItem/ListItem.js src/components/update/Update.js\n git gui\n"
},
{
"answer_id": 64420270,
"author": "Rahmat Oktrifianto",
"author_id": 11054420,
"author_profile": "https://Stackoverflow.com/users/11054420",
"pm_score": 3,
"selected": false,
"text": "git restore --staged <filename>\n git reset HEAD <filename>\n"
},
{
"answer_id": 69238370,
"author": "Supratim Roy",
"author_id": 4397470,
"author_profile": "https://Stackoverflow.com/users/4397470",
"pm_score": 3,
"selected": false,
"text": "git restore --staged . git restore --staged <filename> git rm --cached git rm"
},
{
"answer_id": 69251810,
"author": "Gerard de Visser",
"author_id": 2314443,
"author_profile": "https://Stackoverflow.com/users/2314443",
"pm_score": 3,
"selected": false,
"text": "git reset HEAD~1 --mixed\n"
},
{
"answer_id": 73566382,
"author": "dev.sochokuchnaya.com",
"author_id": 12674966,
"author_profile": "https://Stackoverflow.com/users/12674966",
"pm_score": 3,
"selected": false,
"text": "git add -A\n git reset\n git add <filename> git add git reset <filename>"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
348,187 | <p>I am trying to use the range property of the jQuery slider so that the slider control displays two handles from which the user can select a price range for real estate. The code I have is:</p>
<pre><code>$("#price").slider({ range: true, minValue: 0, maxValue: 2000000,
change:
function(e, ui) {
var range = (Math.round(ui.range) * 10) + " to " + ui.value;
$("#pricedesc").text(range);
}
});
</code></pre>
<p>The price range should be from $0 to $2,000,000. When I slide the handles on the slider though I get unusual values such as "690 to 13". How exactly is the double handle slider meant to work?</p>
| [
{
"answer_id": 348273,
"author": "Brian Fisher",
"author_id": 43816,
"author_profile": "https://Stackoverflow.com/users/43816",
"pm_score": 4,
"selected": true,
"text": "$(document).ready(function(){\n $(\"#price\").slider(\n { range: true, \n min: 0, \n max: 2000000, \n change: function(e,ui) { \n alert($(\"#price\").slider(\"value\", 0) + ' - ' + $(\"#price\").slider(\"value\", 1) );\n }});\n $(\"#price\").slider(\"moveTo\", 500000, 1);\n });\n"
},
{
"answer_id": 1238063,
"author": "Mehmet Melik Kose",
"author_id": 143808,
"author_profile": "https://Stackoverflow.com/users/143808",
"pm_score": 1,
"selected": false,
"text": "$(\"#price\").slider(\"moveTo\", 500000, 1);\n var max = $('#price').slider('option', 'max');\n$(\"#price\").slider( 'values' , 1 , max );\n"
},
{
"answer_id": 4283289,
"author": "sonal",
"author_id": 521062,
"author_profile": "https://Stackoverflow.com/users/521062",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\nvar str;\n$(function() {\n\n $(\"#slider-range\").slider({\n range: true,\n min: 250,\n max: 2500,\n values: [500, 1000],\n slide: function(event, ui) {\n $(\"#amount\").val('Rs' + ui.values[0] + ' - Rs' + ui.values[1]); \n }\n });\n $(\"#amount\").val('Rs' + $(\"#slider-range\").slider(\"values\", 0) + ' - Rs' + $(\"#slider-range\").slider(\"values\", 1));\n //document.getElementById('valueofslide').value = arrIntervals[ui.values[1]];\n});\n\n\n\n</script>\n\nin html\n<div id=\"Priceslider\" class=\"demo\" style=\"margin-top:5px; \" >\n <%--<Triggers>\n <asp:AsyncPostBackTrigger ControlID=\"Chk1\" />\n\n </Triggers>--%>\n <asp:UpdatePanel ID=\"UpdatePanel2\" runat=\"server\">\n <ContentTemplate>\n <asp:TextBox ID=\"amount\" runat=\"server\" \n style=\"border:0; color:#f6931f; font-weight:bold;margin-bottom:7px;\" OnTextChanged=\"amount_TextChanged\" AutoPostBack=\"True\"></asp:TextBox>\n </ContentTemplate> \n </asp:UpdatePanel> \n <div id=\"slider-range\"></div> \n <asp:TextBox ID=\"valueofslide\" runat=\"server\" AutoPostBack=\"True\"></asp:TextBox> \n </div>\n\n\n <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"False\" \n AllowPaging=\"True\" PageSize=\"5\" Width=\"555px\" \n onpageindexchanging=\"GridView1_PageIndexChanging\">\n <Columns>\n <asp:TemplateField>\n <ItemTemplate>\n <div class=\"propertyName\">\n <asp:CheckBox ID=\"chkProperty\" runat=\"server\" Text='<%# Eval(\"PropertyName\") %>' />,\n <asp:Label ID=\"lblLocation\" runat=\"server\" Text='<%# Eval(\"PropertyLocality\") %>'></asp:Label>,\n <asp:Label ID=\"lblCity\" runat=\"server\" Text='<%# Eval(\"CityName\") %>'></asp:Label>\n </div>\n\n <div class=\"property-image\">\n <asp:Image ID=\"Image1\" runat=\"server\" ImageUrl='<%# Eval(\"PhotoPath\") %>' Height=\"100\" Width=\"100\" />\n \n </div>\n\n <div>\n <div style=\"float: left; width: 380px; margin: 10px; border: thin solid black;\">\n <div style=\"height: 80px; width: 80px; border: 1px solid; float: right; margin-top: 10px; margin-right: 10px;\">\n <font size=\"2\">Weekdays Price:<span id=\"weekdayPrice6\"><%# Eval(\"WeekdayPrice\")%></span></font><br>\n <font size=\"2\">Weekend Price: <span id=\"weekendPrice6\"><%# Eval(\"WeekendPrice\")%></span></font><br>\n <input name=\"getamt\" value=\"Get your amount\" style=\"font-size: 8px;\" type=\"button\">\n </div>\n\n <div style=\"float: right; width: 280px;\">\n <input name=\"Map\" value=\"Map\" onclick=\"showPropertyMap(6)\" type=\"button\">\n <input name=\"availability\" value=\"Check Availability\" onclick=\"showPropertyAvailabilityCalender(6)\" type=\"button\"><br>\n\n Ratings : <img src=\"images/star<%# Eval(\"PropertyRating\") %>.PNG\" alt=\"'<%# Eval(\"PropertyRating\") %>'\"/> (Votes : <span></span>)\n\n <br>\n\n View <span></span> times, <span>\n <asp:Label ID=\"Label1\" runat=\"server\" Text='<%# Eval(\"NumberOfReviews\") %>'></asp:Label></span> Reviews<br>\n\n <span></span><%# Eval(\"PropertyRecommended\")%> % Recommend<br>\n Check in <%# Eval(\"CheckinTime\") %> Check out <%# Eval(\"CheckoutTime\")%><br>\n <div id='<%# Eval(\"PropertyId\") %>' class=\"property\">\n <%-- <input name=\"Book\" value=\"Book\" type=\"button\">--%>\n <asp:Button ID=\"Book\" runat=\"server\" Text=\"Book\" \n OnClientClick=\"return retrivPropertyId(this);\" onclick=\"Book_Click\"/>\n <input name=\"Save\" value=\"Save\" type=\"button\">\n <input name=\"Details\" value=\"Details\" type=\"button\" onclick=\"return retreivePId(this);\">\n\n <asp:Button ID=\"Contact\" runat=\"server\" Text=\"Contact\" \n OnClientClick=\"return retreivePropId(this);\" onclick=\"Contact_Click\" />\n <br>\n </div> \n </div>\n </div>\n\n </div>\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n </asp:GridView>\n"
},
{
"answer_id": 15786189,
"author": "user2239888",
"author_id": 2239888,
"author_profile": "https://Stackoverflow.com/users/2239888",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css\" />\n<script src=\"http://code.jquery.com/jquery-1.9.1.js\"></script>\n<script src=\"http://code.jquery.com/ui/1.10.2/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"/resources/demos/style.css\" />\n<script type=\"text/javascript\">\n var str;\n $(function () {\n\n $(\"#slider-range\").slider({\n range: true,\n min: 250,\n max: 2500,\n values: [500, 1000],\n slide: function (event, ui) {\n $(\"#amount\").val('Rs' + ui.values[0] + ' - Rs' + ui.values[1]);\n }\n });\n $(\"#amount\").val('Rs' + $(\"#slider-range\").slider(\"values\", 0) + ' - Rs' + $(\"#slider-range\").slider(\"values\", 1));\n //document.getElementById('valueofslide').value = arrIntervals[ui.values[1]];\n });\n <div id=\"Priceslider\" class=\"demo\" style=\"margin-top:5px; \" >\n\n <asp:UpdatePanel ID=\"UpdatePanel2\" runat=\"server\">\n <ContentTemplate>\n <asp:TextBox ID=\"amount\" runat=\"server\" \n style=\"border:0; color:#f6931f; font-weight:bold;margin-bottom:7px;\" OnTextChanged=\"amount_TextChanged\" AutoPostBack=\"True\"></asp:TextBox>\n </ContentTemplate> \n </asp:UpdatePanel> \n <div id=\"slider-range\"></div> \n <asp:TextBox ID=\"valueofslide\" runat=\"server\" AutoPostBack=\"True\"></asp:TextBox> \n </div>\n</form>\n"
},
{
"answer_id": 62714675,
"author": "Surya R Praveen",
"author_id": 714707,
"author_profile": "https://Stackoverflow.com/users/714707",
"pm_score": 0,
"selected": false,
"text": "<div id=\"slider-range\"></div>\n .ui-draggable, .ui-droppable {\n background-position: top;\n}\n.ui-widget-header {background: #006fba;}\n.value { position: absolute; top: 30px; left: 50%; margin: 0 0 0 -20px; width: 40px; text-align: center; display: block; font-weight: normal;}\n $( function() {\n $( \"#slider-range\" ).slider({\n range: true,\n min: 0,\n max: 500,\n values: [ 75, 300 ],\n slide: function( event, ui ) {\n $('.ui-slider-handle:eq(0) .price-range-min').html('$' + ui.values[ 0 ]);\n $('.ui-slider-handle:eq(1) .price-range-max').html('$' + ui.values[ 1 ]);\n }\n });\n $('.ui-slider-handle:eq(0)').append('<span class=\"price-range-min value\">$' + $('#slider-range').slider('values', 0) + '</span>');\n $('.ui-slider-handle:eq(1)').append('<span class=\"price-range-max value\">$' + $('#slider-range').slider('values', 1) + '</span>');\n } );\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
348,196 | <p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p>
<p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p>
<p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p>
<p>So how do you write objects to a list within a loop?</p>
<p>Here's my simplified code</p>
<pre><code>class SimpleClass(object):
pass
x = SimpleClass
# Then create an empty list
simpleList = []
#Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass
for count in range(0,4):
# each iteration creates a slightly different attribute value, and then prints it to
# prove that step is working
# but the problem is, I'm always updating a reference to 'x' and what I want to add to
# simplelist is a new instance of x that contains the updated attribute
x.attr1= '*Bob* '* count
print "Loop Count: %s Attribute Value %s" % (count, x.attr1)
simpleList.append(x)
print '-'*20
# And here I print out each instance of the object stored in the list 'simpleList'
# and the problem surfaces. Every element of 'simpleList' contains the same attribute value
y = SimpleClass
print "Reading the attributes from the objects in the list"
for count in range(0,4):
y = simpleList[count]
print y.attr1
</code></pre>
<p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
| [
{
"answer_id": 348215,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 6,
"selected": false,
"text": "for count in xrange(4):\n x = SimpleClass()\n x.attr = count\n simplelist.append(x)\n simplelist = [SimpleClass(count) for count in xrange(4)]\n"
},
{
"answer_id": 348222,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 2,
"selected": false,
"text": "import copy\n\nx = SimpleClass()\n\nfor count in range(0,4):\n y = copy.deepcopy(x)\n (...)\n y.attr1= '*Bob* '* count\n"
},
{
"answer_id": 348284,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 4,
"selected": false,
"text": "x = SimpleClass\n x = SimpleClass()\n"
},
{
"answer_id": 352505,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 6,
"selected": false,
"text": "instancelist = [MyClass() for i in range(29)]\n *"
},
{
"answer_id": 49146953,
"author": "user737489",
"author_id": 9455966,
"author_profile": "https://Stackoverflow.com/users/9455966",
"pm_score": 2,
"selected": false,
"text": "# coding: utf-8\n\nclass Class():\n count = 0\n names = []\n\n def __init__(self,name):\n self.number = Class.count\n self.name = name\n Class.count += 1\n Class.names.append(name)\n\nl=[]\nl.append(Class(\"uno\"))\nl.append(Class(\"duo\"))\nprint l\nprint l[0].number, l[0].name\nprint l[1].number, l[1].name\nprint Class.count, Class.names\n [<__main__.Class instance at 0x6311b2c>, \n<__main__.Class instance at 0x63117ec>]\n0 uno\n1 duo\n2 ['uno', 'duo']\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,201 | <p>Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)</p>
| [
{
"answer_id": 348242,
"author": "gcores",
"author_id": 40256,
"author_profile": "https://Stackoverflow.com/users/40256",
"pm_score": 9,
"selected": true,
"text": "string MyString = number.ToString(\"+0;-#\");\n string MyString = number.ToString(\"+#;-#;0\");\n"
},
{
"answer_id": 556853,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 6,
"selected": false,
"text": "string MyString = number.ToString(\"+#;-#;0\");\n"
},
{
"answer_id": 17274884,
"author": "Edward",
"author_id": 158675,
"author_profile": "https://Stackoverflow.com/users/158675",
"pm_score": 5,
"selected": false,
"text": "var f = string.Format(\"{0}, Force sign {0:+#;-#;+0}, No sign for zero {0:+#;-#;0}\", number);\n string.Format var f = $\"{number}, Force sign {number:+#;-#;+0}, No sign for zero {number:+#;-#;0}\";\n"
},
{
"answer_id": 31988586,
"author": "Kamil Szot",
"author_id": 166921,
"author_profile": "https://Stackoverflow.com/users/166921",
"pm_score": 4,
"selected": false,
"text": "String.Format(\"{0:+#;-#;+0}\", 0)); // output: +0\n String.Format(\"{0:+0;-#}\", 0)); // output: +0\n +#;-# + +0 String.Format(\"{0:+0.##;-#.##}\", 0)); // output: +0\n String.Format(\"{0:+0.00;-#.00}\", 0)); // output: +0.00\n"
},
{
"answer_id": 50524434,
"author": "Tom Blodget",
"author_id": 2226988,
"author_profile": "https://Stackoverflow.com/users/2226988",
"pm_score": 1,
"selected": false,
"text": "+###,###,###,###,###,###,###,###,###,##0.###,###,###,###,###,###,###,###,###,###;-###,###,###,###,###,###,###,###,###,##0.###,###,###,###,###,###,###,###,###,###;0\n"
},
{
"answer_id": 58111490,
"author": "Peter Kriegel",
"author_id": 1165195,
"author_profile": "https://Stackoverflow.com/users/1165195",
"pm_score": 0,
"selected": false,
"text": "\"$([System.DateTime]::Now.ToString('HH:mm:ss.fff'))$($([System.TimeZoneInfo]::Local.GetUtcOffset([System.DateTime]::Now).TotalMinutes.ToString('+0;-#')))\"\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14537/"
] |
348,202 | <p>I want to warn users of Internet Explorer 6 using my site, that IE6 has had serious compatibility issues with my site in the past. What is the best way to do this?</p>
<p>Ideally, I want to have a message appear (not a new window, but a message box, if possible) that warns IE6 users of the issues and reccommends they update to either IE7, Firefox 3 or Opera 9.5.</p>
| [
{
"answer_id": 348219,
"author": "different",
"author_id": 3654,
"author_profile": "https://Stackoverflow.com/users/3654",
"pm_score": 5,
"selected": false,
"text": "<!--[if IE 6]>\n<h1>Please upgrade your browser!</h1>\n<![endif]-->\n"
},
{
"answer_id": 348220,
"author": "dave",
"author_id": 41477,
"author_profile": "https://Stackoverflow.com/users/41477",
"pm_score": 3,
"selected": false,
"text": "<!--[if IE 6]>\nSpecial instructions for IE 6 here\n<![endif]-->\n"
},
{
"answer_id": 348243,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "<div> <blink>"
},
{
"answer_id": 348331,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\n// check if browser is IE6 (when IE) or not FF6 (when FF)\nif (($.browser.msie && $.browser.version.substr(0,1) == '6')\n || ($.browser.mozilla && $.browser.version.substr(0,1) != '3')) {\n $('#browserWarning').show();\n}\n</script>\n <style type=\"text/css\">\n/* this would probably be in a CSS file */\n#browserWarning { display:none; }\n</style>\n<!--[if IE 6]>\n<style type=\"text/css\">\n#browserWarning { display:; }\n</style>\n<![endif]-->\n"
},
{
"answer_id": 722913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<!--[if lte IE 6]>\n<div id=\"warning\">\n<h4 class=\"red\">Your Browser Is Not Supported!</h4><br />\n<p>Please upgrade to <a href='http://getfirefox.com'>FireFox</a>, <a href='http://www.opera.com/download/'>Opera</a>, <a href='http://www.apple.com/safari/'>Safari</a> or <a href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx'>Internet Explorer 7 or 8</a>. Thank You! <a href=\"#\" onClick=\"document.getElementById('warning').style.display = 'none';\"><b>Close Window</b></a></p>\n</div>\n<![endif]-->\n #warning {position:relative; top:0px; width:100%; height:40px; background-color:#fff; margin-top:0px; padding:4px; border-bottom:solid 4px #000066}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5509/"
] |
348,236 | <p>I'm working on an AJAXy project (Dojo and Rails, if the particulars matter). There are several places where the user should be able to sort, group, and filter results. There are also places where a user fills out a short form and the resulting item gets added to a list on the same page.</p>
<p>The non-AJAXy implementation works fine -- the view layer server-side already knows how to render this stuff, so it can just do it again in a different order or with an extra element. This, however, adds lots of burden to the server.</p>
<p>So we switched to sending JSON from the server and doing lots of (re-)rendering client-side. The downside is that now we have duplicate code for rendering every page: once in Rails, which was built for this, and once in Dojo, which was not. The latter is basically just string concatenation.</p>
<p>So question part one: is there a good Javascript MVC framework we could use to make the rendering on the client-side more maintainable?</p>
<p>And question part two: is there a way to generate the client-side views in Javascript and the server-side views in ERB from the same template? I think that's what the Pragmatic Programmers would do.</p>
<p>Alternatively, question part three: am I completely missing another angle? Perhaps send JSON from the server but also include the HTML snippet as an attribute so the Javascript can do the filtering, sorting, etc. and then just insert the given fragment?</p>
| [
{
"answer_id": 348565,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 1,
"selected": false,
"text": "innerHTML"
},
{
"answer_id": 348608,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "render_table_initially:\n if nojs:\n render big_html_table\n else:\n render empty_table_with_callback_to_load_table\n\n\nload_table:\n render '{ rows: [\n { foo: \"a\", bar: \"b\", renderedHTML: \"<tr><td>...</td></tr>\" },\n { foo: \"c\", bar: \"d\", renderedHTML: \"<tr><td>...</td></tr>\" },\n ...\n ]}'\n dojo.xhrGet({\n url: '/load_table',\n handleAs: 'json',\n load: function(response) {\n dojo.global.all_available_data = response;\n dojo.each(response.rows, function(row) {\n insert_row(row.renderedHTML);\n }\n }\n});\n all_available_data"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
348,249 | <p>I have no clue about trigonometry, despite learning it in school way back when, and I figure this should be pretty straightforward, but trawling through tons of trig stuff on the web makes my head hurt :) So maybe someone could help me...</p>
<p>The title explains exactly what I want to do, I have a line:
x1,y1 and x2,y2
and want a function to find x3,y3 to complete an isosceles triangle, given the altitude. </p>
<p>Just to be clear, the line x1,y2 -> x2,y2 will be the base, and it will not be aligned any axis (it will be at a random angle..) </p>
<p>Does anyone have a simple function for this??</p>
| [
{
"answer_id": 348258,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "altitude dx = x1 - x2\nmidpoint = ((x1 + x2) / 2, (y1 + y2) / 2)\nslope = -dx / (y1 - y2)\nx = sqrt(altitude*altitude - dx*dx) / slope + midpoint.x\ny = slope * (x - midpoint.x) + midpoint.y\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,251 | <p>Hopefully (but not necessarily) one that is independent of language or framework?</p>
| [
{
"answer_id": 348258,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "altitude dx = x1 - x2\nmidpoint = ((x1 + x2) / 2, (y1 + y2) / 2)\nslope = -dx / (y1 - y2)\nx = sqrt(altitude*altitude - dx*dx) / slope + midpoint.x\ny = slope * (x - midpoint.x) + midpoint.y\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31641/"
] |
348,256 | <p>I want to match a block of code <em>multiple</em> times in a file but can't work out the regular expression to do this. An example of the code block is:</p>
<pre><code>//@debug
...
// code in here
...
//@end-debug (possibly more comments here on same line)
</code></pre>
<p>Each code block I'm trying to match will start with <code>//@debug</code> and stop at the end of the line containing <code>//@end-debug</code></p>
<p>I have this at the moment:</p>
<pre><code>/(\/{2}\@debug)(.|\s)*(\/{2}\@end-debug).*/
</code></pre>
<p>But this matches one big block from the first <code>//@debug</code> all the way to end of the line of the very last <code>//@end-debug</code> in the file.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 348309,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "(.|\\s) /\\/\\/@debug.*?^\\/\\/@end-debug[^\\r\\n]*/sg\n /s .* [^\\r\\n]* /g"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40754/"
] |
348,260 | <p>I am writing a Firefox extension. I would like to search the current webpage for a set of words, and count how many times each occurs. This activity is only performed when the user asks, but it must still happen reasonably quickly.</p>
<p>I am currently using indexOf on the BODY tag's innerHTML element, but am finding it too slow to run repeatedly in the following manner:</p>
<pre><code>function wordcount(doc, match)
{
var count = 0;
var pos = 0;
for(;;)
{
len=doc.indexOf(match, pos);
if(len == -1)
{
break;
}
pos = len + match.length;
count++;
}
return count;
}
var html = content.document.body.innerHTML.toLowerCase()
for(var i=0; i<keywords.length; i++)
{
var kw = keywords[i];
myDump(kw + ": " + wordcount(html, kw));
}
</code></pre>
<p>With 100 keywords, this takes approximately 10 to 20 seconds to run. There is some scope to reduce the number of keywords, but it will still need to run much quicker.</p>
<p>Is there a more obvious way to do this? What is the most efficient method? I have some ideas, but am reluctant to code each up without some idea of the performance I can expect:</p>
<ul>
<li>Navigate the DOM rather than using
innerHTML. Will this be likely
quicker or slower? It would have the
benefit of only searching textual
content.</li>
<li>Loop through the document word by
word, accumulating a count of each
word's occurence simultaneously.
With this method I would have to do
a bit more work parsing the HTML.</li>
</ul>
<p><em>Edit: Turns out that the slowest part was the myDump function writing to the error console. Duh! Nevertheless, there some interesting more efficient alternatives have been presented, which I am intending to use.</em></p>
| [
{
"answer_id": 348302,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "var keywords = new Hash(); // from prototype or use your own\n\nfunction traverseNode( node ) {\n if (node.nodeName == '#text') {\n indexNode( node );\n }\n else {\n for (var i = 0, len node.ChildNodes.length; i < len; ++i) {\n traverse( node.childNodes[i] );\n }\n }\n}\n\nfunction indexNode( node ) {\n var words = node.NodeValue.split( /\\s/ );\n for (var i = 0, len = words.length; i < len; ++i) {\n if (keywords.hasItem( words[i]) ) {\n keywords.setItem( words[i], keywords.getItem(words[i]) + 1 );\n }\n else {\n keywords.setItem( words[i], 1 );\n }\n }\n}\n\ntraverseNode( document.body );\n"
},
{
"answer_id": 348345,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 1,
"selected": false,
"text": "textContent innerHTML"
},
{
"answer_id": 348437,
"author": "Bryan J Swift",
"author_id": 1357024,
"author_profile": "https://Stackoverflow.com/users/1357024",
"pm_score": 3,
"selected": true,
"text": "var words = document.body.innerHTML.replace(/<.*?>/g,'').split(/\\s+/);\nvar i = words.length;\nvar keywordCounts = {'keyword': 0, 'javascript': 0, 'today': 0};\nvar keywords = [];\nvar keywordMatcher = '';\nvar word;\nfor (word in keywordCounts) {\n keywords[keywords.length] = word ;\n keywordMatcher = keywordMatcher + '(' + word + ')?';\n}\nvar regex = new RegExp(keywordMatcher);\nvar j = keywords.length;\nvar matched, keyword;\nif (i && j) {\n do {\n i = i - 1;\n matched = words[i].match(regex);\n if (!matched) continue;\n j = keywords.length;\n do {\n j = j - 1;\n if (matched[j + 1]) {\n keyword = keywords[j];\n keywordCounts[keyword] = keywordCounts[keyword] + 1;\n }\n } while (j);\n } while (i);\n}\n"
},
{
"answer_id": 348844,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 2,
"selected": false,
"text": "function prepareCount(words) {\n var result = {};\n for (var i=0,len=words.length; i < len; i++) {\n result[words[i]] = 0;\n }\n return result;\n}\n function countKeywords(text,wordcount) {\n text.replace(/[^\\s]+/g,function(s) {\n if (wordcount[s]!==undefined) { ++wordcount[s];}\n return \"\";\n });\n return wordcount;\n}\n var wordcount = countKeywords(document.documentElement.textContent.toLowerCase(),prepareCount([\"my\",\"key\",\"words\"]));\n /[^\\s\\x00-\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x7F]+/g\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42974/"
] |
348,266 | <p>I'm writing a basic planet viewer OpenGL Perl application, just for fun.
I have the basics working, with the glorious planet, implemented through a <code>gluSphere()</code>, rotating with the classic earth texture map applied.</p>
<p>Now, what if I want to apply a second texture map through OpenGL (say, the "earth clouds")?</p>
<p>Of course, I can mix the two texture maps myself in PhotoShop or some other graphic application, but is there a way through OpenGL API?</p>
<p>I tried loading the two textures and generating the mipmaps but the planet is shown with only the first texture applied, not the second.</p>
| [
{
"answer_id": 348566,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "glEnable(GL_TEXTURE_2D);\n\nglActiveTexture(GL_TEXTURE0);\nglBindTexture(GL_TEXTURE_2D, texture0ID);\nglTexEnvf(GL_TEXTURE_ENV, ..., ...);\n\nglActiveTexture(GL_TEXTURE1);\nglBindTexture(GL_TEXTURE_2D, texture1ID);\nglTexEnvf(GL_TEXTURE_ENV, ..., ...);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303/"
] |
348,268 | <p>I have a procedure that is run for a lot of items, skipping over certain items who don't meet a criterion. However, I then go back and run it for some of the individuals who were missed in the first pass. I currently do this by manually re-running the procedure for each individual person, but would ideally like a solution a little more hands off.</p>
<p>Something my boss suggested might be effective would be creating a List (as in Data -> Lists) that contains the names of the items in question, and then iterating over the list. Sadly, my help-file fu seems to be failing me - I don't know whether I just don't know what to look for, or what.</p>
<p>Running the "Generate Macro" command shows that the VBA to create a list in the first place is along the lines of
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1"), , xlYes).Name = "List1"</p>
<p>Unfortunately, I can't seem to figure out how to then do stuff with the resulting list. I'm looking to making a loop along the lines of</p>
<pre><code>For Each ListItem in List
Run the procedure on the text in ListItem.Value
Next ListItem
</code></pre>
<p>Any suggestions?</p>
| [
{
"answer_id": 348362,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "Dim Counter 'module level '\n\nSub RunSomeProc()\n Counter = 0\n '1st test '\n SomeProc\n\n '2nd Test skipped items'\n For Each c In Range(\"c1:c\" & Counter)\n SomeProc\n Next\n\nEnd Sub\n\nSub SomeProc()\nFor Each c In Range(\"NamedRange1\")\n If SomeTest=SomeVal Then\n 'Write to 2nd test range '\n Range(\"C1\").Offset(Counter, 0) = c 'Value of cell'\n Counter = Counter + 1\n End If\nNext\nEnd Sub\n"
},
{
"answer_id": 1077311,
"author": "Margaret",
"author_id": 27290,
"author_profile": "https://Stackoverflow.com/users/27290",
"pm_score": 1,
"selected": true,
"text": "For each item in Sheets(\"Sheet1\").Range(\"Range1\")\n Do stuff\nNext item\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27290/"
] |
348,282 | <p>I'm working on a site with multiple subdomains, some of which should get their own session.</p>
<p>I think I've got it worked out, but have noticed something about cookie handling that I don't understand. I don't see anything in the docs that explains it, so thought I would see if anyone here has some light to shed on the question.</p>
<p>If I just do:</p>
<pre><code>session_start();
</code></pre>
<p>I end up with a session cookie like this:</p>
<p>subdomain.example.net</p>
<p>However, if I make any attempt to set the cookie domain myself, either like</p>
<pre><code>ini_set('session.cookie_domain', 'subdomain.example.net');
</code></pre>
<p>or like</p>
<pre><code>session_set_cookie_params( 0, "/", "subdomain.example.net", false, false);
</code></pre>
<p>I end up with a cookie for .subdomain.example.net (note the opening dot), which I believe means "match all subdomains (or in this case sub-subdomains).</p>
<p>This seems to happen with all my cookies actually, not just session. If I set the cookie domain myself, it automatically has the dot prepended, meaning this domain and all subs of it. If I don't set the domain, then it gets it right by using only the current domain.</p>
<p>Any idea what causes this, and what I can do to control that prepending dot?</p>
<p>Thanks!</p>
| [
{
"answer_id": 348336,
"author": "Brian Fisher",
"author_id": 43816,
"author_profile": "https://Stackoverflow.com/users/43816",
"pm_score": 6,
"selected": true,
"text": "header(\"Set-Cookie: cookiename=cookievalue; expires=Tue, 06-Jan-2009 23:39:49 GMT; path=/; domain=subdomain.example.net\");\n"
},
{
"answer_id": 745738,
"author": "Kevin Campion",
"author_id": 83833,
"author_profile": "https://Stackoverflow.com/users/83833",
"pm_score": 5,
"selected": false,
"text": "setcookie('cookiename','cookievalue',time()+(3600*24),'/');\n"
},
{
"answer_id": 9443886,
"author": "Alex",
"author_id": 940479,
"author_profile": "https://Stackoverflow.com/users/940479",
"pm_score": 4,
"selected": false,
"text": "session_set_cookie_params(0, '/', NULL, TRUE, TRUE);\n"
},
{
"answer_id": 54974755,
"author": "Gendrith",
"author_id": 1347299,
"author_profile": "https://Stackoverflow.com/users/1347299",
"pm_score": 0,
"selected": false,
"text": "$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;\n\nsetcookie(\"cookie_name\", 'cookie_value', 0, '/', $domain);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27580/"
] |
348,304 | <p>I am developing a State Machine Workflow using C# and WF in visual studio 2008. On one of my states I need to wait for multiple events to happen until the workflow can transition to the next state. As an example think of a unanimous voting scenario. I cannot find a way to do this. Does anyone have a solution or workaround for this problem? </p>
| [
{
"answer_id": 348336,
"author": "Brian Fisher",
"author_id": 43816,
"author_profile": "https://Stackoverflow.com/users/43816",
"pm_score": 6,
"selected": true,
"text": "header(\"Set-Cookie: cookiename=cookievalue; expires=Tue, 06-Jan-2009 23:39:49 GMT; path=/; domain=subdomain.example.net\");\n"
},
{
"answer_id": 745738,
"author": "Kevin Campion",
"author_id": 83833,
"author_profile": "https://Stackoverflow.com/users/83833",
"pm_score": 5,
"selected": false,
"text": "setcookie('cookiename','cookievalue',time()+(3600*24),'/');\n"
},
{
"answer_id": 9443886,
"author": "Alex",
"author_id": 940479,
"author_profile": "https://Stackoverflow.com/users/940479",
"pm_score": 4,
"selected": false,
"text": "session_set_cookie_params(0, '/', NULL, TRUE, TRUE);\n"
},
{
"answer_id": 54974755,
"author": "Gendrith",
"author_id": 1347299,
"author_profile": "https://Stackoverflow.com/users/1347299",
"pm_score": 0,
"selected": false,
"text": "$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;\n\nsetcookie(\"cookie_name\", 'cookie_value', 0, '/', $domain);\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22769/"
] |
348,305 | <p>I have a program that needs to do a <strong>compile time checkable</strong> map from one known set of values to another known set of values:</p>
<pre>
in out
------------
8 37
10 61
12 92
13 1/4 109
15 1/4 151
etc
</pre>
<p>This would be easy if the inputs were either integers or evenly spaced. I'm going to be iterating over the rows but also want to be able to do lookups in a readable manor.</p>
<p>My current thought (that I'm not liking) is to define an enum like</p>
<pre><code>enum Size
{
_8,
_10,
_12,
_13_25,
_15_25,
// etc
}
</code></pre>
<p>and then set it up for 2 lookups.</p>
<p>Any better ideas?</p>
<p><strong>Edit:</strong> My primary concern is limiting what I can <em>try</em> to look up. I'd like stuff to <em>not even compile</em> if the code might try and look up something that is invalid.</p>
<p>The set is small and iteration times are almost totally irrelevant. </p>
<p>I haven't seen anything that gains me anything over the enum so for now I'm going with that. OTOH I'll keep watching this question.</p>
<p><code>*</code> Note: I'm not worried about catching issues with pointers and what not, just straight forward code like for loops and variable assignments.</p>
<hr>
<p><strong>The nitty grity</strong>: I over simplified the above for clarity and generality. I actually have a table that has 3 non-integer, non-uniform axes and one non-numeric axis. And at this point I'm not sure what directions I'm going to need to enumerate it in.</p>
<p>a few links to give a flavor of what I'm looking for:</p>
<p><a href="http://www.boost.org/doc/libs/1_37_0/boost/units/systems/si.hpp" rel="nofollow noreferrer">Boost::SI</a> and my <a href="http://www.dsource.org/projects/scrapple/browser/trunk/units" rel="nofollow noreferrer">D version</a> of <a href="http://www.dsource.org/projects/scrapple/browser/trunk/units/constants.d" rel="nofollow noreferrer">the</a> same <a href="http://www.dsource.org/projects/scrapple/browser/trunk/units/types.d" rel="nofollow noreferrer">idea</a></p>
| [
{
"answer_id": 348452,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 0,
"selected": false,
"text": "// this could be loaded from a file potentially\n// notice that the keys have been sorted.\nconst char* keys[] = { \"10\", \"12\", \"13 1/4\", \"15 1/4\", \"8\", 0 };\nfloat values[] = { 61, 92, 109, 151, 37, 0 };\nint key_count = 0;\nwhile (keys[key_count]) ++key_count;\n\nbool find(const char* key, float* val) {\n int idx = bsearch(key, keys, sizeof(const char*), key_count, strcmp);\n if (idx < 0) return false;\n *val = values[idx];\n return true;\n}\n"
},
{
"answer_id": 351331,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 1,
"selected": false,
"text": "IN maps to Key\n-- --- \n8 32 \n10 40\n12 48 \n13 1/4 53\n15 1/4 61 \n\nKeyMin= 32\n"
},
{
"answer_id": 352024,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 0,
"selected": false,
"text": "typedef struct{\n float input;\n int output;\n}m_lookup;\nm_lookup in_out[] = \n{ \n (float) 8 , 37,\n (float)10 , 61,\n (float)12 , 92,\n (float)13.25,109,\n (float)15.25,151,\n};\n\nint get_Var(float input)\n{\n int i=0;\n for(i=0;i<sizeof(in_out);i++)\n if(in_out[i].input == input)\n return in_out[i].output;\n // Here you could make some special code for your compiler\n return 0;\n}\nint main(void)\n{\n printf(\"Input 15.25 : Output %d\\n\",get_Var(15.25));\n printf(\"Input 13,25 : Output %d\\n\",get_Var(13.25));\n printf(\"Illegal input:\\n\");\n printf(\"Input 5 : Output %d\\n\",get_Var(5));\n system( \"pause\" );\n return 0;\n}\n enum Size\n{\n i_8=37,\n i_10=61,\n i_12=92,\n i_13_25=109,\n i_15_25=151,\n // etc\n}\n"
},
{
"answer_id": 354111,
"author": "RossFabricant",
"author_id": 20754,
"author_profile": "https://Stackoverflow.com/users/20754",
"pm_score": 1,
"selected": false,
"text": "class Size\n{\n public decimal Val{get;set;}\n private Size(decimal val){this.val = val;}\n public static Size _8 = new Size(8.0); \n //...\n public Dictionary<Size, Size> sizeMap = new Dictionary<Size, Size>\n {\n {_8, _37}, \n //...\n };\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.