qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
226,221
<p>I'd like to do something like this</p> <blockquote> <pre><code>raiserror(concat('Error in case @isFishy =', @isFishy, ' @isSmarmy=', @isSmarmy, ' @isTasty = ', @isTasty), 10, 1) --or raiserror('Error in case @isFishy =' + @isFishy + ' @isSmarmy=' + @isSmarmy + ' @isTasty = ' + @isTasty, 10, 1) </code></pre> </blockquote> <p>But it just isn't working. How do I accomplish this? I'm in SQL Server 2005.</p>
[ { "answer_id": 226474, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 5, "selected": true, "text": "raiserror(N'Error in case @isFishy = %d @isSmarmy = %d @isTasty = %d',10,1,@isFishy,@isSmarmy,@isTasty)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435/" ]
226,271
<p>I know how to find out the current domain name in PHP already, the problem is when I put this code into a file and then include it from another server it shows the domain name of where the file is located. Is there any way for it to find out the domain or the site containing the include() code?</p>
[ { "answer_id": 226335, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 1, "selected": false, "text": "include 'http://example.com/script.php';\n <? \n//do something\necho '$v = '.$_SERVER['HTTP_HOST'].';'\n?>\n <?\n//do something\n?>\n$v = $_SERVER['HTTP_HOST'];\n" }, { "answer_id": 228018, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 1, "selected": true, "text": "eval(file_get_contents(\"http://someDomain.com/somePhpscript.txt\"));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
226,272
<p>I have one user who gets an error message when he closes his browser. This only happens when he has visited a page which contains my applet. It seems to have been registered as a bug at Sun but that was many years ago. He is using Java 1.6 and IE7.</p> <p>Has anyone seen this before and know a solution or work-around?</p> <pre><code>java.lang.NullPointerException: null pData at sun.awt.windows.WComponentPeer.hide(Native Method) at java.awt.Component.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeAll(Unknown Source) at sun.plugin.viewer.frame.IExplorerEmbeddedFrame.windowClosed(Unknown Source) at java.awt.Window.processWindowEvent(Unknown Source) at java.awt.Window.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) </code></pre> <p><strong>UPDATE</strong> The user removed Google Desktop and the problem has not occured since. So there you go... Thanks everyone!</p>
[ { "answer_id": 1458976, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<SCRIPT language = \"JavaScript\">\n window.onunload = function() { document.body.innerHTML = \"\"; } \n</script>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11249/" ]
226,279
<p>I'm trying to decode a WBXML encoded SyncML message from a Nokia N95. My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of &lt;unknown&gt; tags and a big chunk of binary within a &lt;Collection&gt; tag. I tried running the contents of the &lt;Collection&gt; through by itself but it failed. Is there something I'm missing?</p> <p>Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...</p>
[ { "answer_id": 1826223, "author": "Engrost", "author_id": 127734, "author_profile": "https://Stackoverflow.com/users/127734", "pm_score": 0, "selected": false, "text": "params.lang wbxml2xml params.lang = WBXML_LANG_UNKNOWN\n class WBXMLParseError(Exception):\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11542/" ]
226,280
<p>In eclipse 3.4 I'm trying to do some performance tests on a large product, one of the included libraries is the vecmath.jar (javax.vecmath package) from the Java3D project. Everything was working fine and then when trying to run it yesterday I get this exception/error not long after starting it up:</p> <pre><code>java.lang.UnsupportedClassVersionError: javax/vecmath/Point2f (Unsupported major.minor version 49.0) </code></pre> <p>Which I believe means that I'm trying to load a java 1.5 class file into a 1.4 jvm which is unsupported. However when I went to the class file to check this I saw this in the eclipse class file viewer:</p> <pre><code>Compiled from Point2f.java (version 1.2 : 46.0, super bit) </code></pre> <p>So the class loader says it is version 49.0 but the class file says its 46.0. I've tried cleaning and fully rebuilding the project, I've confirmed that the compiler version for the project is 1.4, the JRE is 1.4 and for the run configuration the 1.4 jvm is selected. I'm totally stuck on this, does anyone have any idea what might be causing this?</p> <p>Thanks</p> <p>===EDIT===</p> <p>It turns out that a version of java3d which was incompatible with java 1.4.2 had been installed in C:\Program Files\java\j2re1.4.2_18\lib\ext. I installed a newer version of Java3D to play around with in java6 and i guess it installed the libs in all my JREs even the ones which were incompatible.</p>
[ { "answer_id": 226552, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "Window\n -> Preferences\n -> Java\n -> Compiler\n -> Compiler Compliance Level\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25920/" ]
226,282
<p>I'm not talking about algorithmic stuff (eg use quicksort instead of bubblesort), and I'm not talking about simple things like loop unrolling.</p> <p>I'm talking about the <em>hardcore</em> stuff. Like <a href="http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html" rel="noreferrer">Tiny Teensy ELF</a>, <a href="http://catb.org/jargon/html/story-of-mel.html" rel="noreferrer">The Story of Mel</a>; practically everything in the demoscene, and so on.</p>
[ { "answer_id": 226350, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "movsx" }, { "answer_id": 226367, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "switch case" }, { "answer_id": 597406, "author": "Grant Peters", "author_id": 68241, "author_profile": "https://Stackoverflow.com/users/68241", "pm_score": 3, "selected": false, "text": "float InvSqrt (float x)\n{\n float xhalf = 0.5f*x;\n int i = *(int*)&x;\n i = 0x5f3759df - (i>>1); // Now this is what you call a real magic number\n x = *(float*)&i;\n x = x*(1.5f - xhalf*x*x);\n return x;\n}\n" }, { "answer_id": 1321551, "author": "j_random_hacker", "author_id": 47984, "author_profile": "https://Stackoverflow.com/users/47984", "pm_score": 3, "selected": false, "text": "doFoo() doBar()" }, { "answer_id": 7102096, "author": "Lucas", "author_id": 332406, "author_profile": "https://Stackoverflow.com/users/332406", "pm_score": 3, "selected": false, "text": "code_buff: PEA $0000 ; rightmost word (16-bits = 4 pixels)\n PEA $0000 ; background 1\n PEA $0000 ; background 1\n PEA $0000 ; background 1\n LDA (72),y ; background 2\n PHA\n LDA (70),y ; background 2\n PHA\n JMP word_68 ; mix the data\nword_68_rtn: PEA $0000 ; more background 1\n ...\n PEA $0000\n BRA *+40 ; patched exit code\n\n ... \nword_68: LDA (68),y ; load data for background 2\n AND #$00FF ; mask\n ORA #$AB00 ; blend with data from background 1\n PHA\n JMP word_68_rtn ; jump back\nword_66: LDA (66),y\n ...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
226,288
<p>When creating a new build in Team Foundation Server, I get the following error when attempting to run the new build:</p> <blockquote> <p>The path C:\Build\ProductReleases\FullBuildv5.4.2x\Sources is already mapped to workspace BuildServer_23.</p> </blockquote> <p>I am unable to see a workspace by that name in the workspaces dialog.</p>
[ { "answer_id": 226304, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 8, "selected": true, "text": "C:\\YourWorkspaceFolder>tf workspaces /owner:*\n C:\\YourWorkspaceFolder>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAME\n" }, { "answer_id": 14530847, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 1, "selected": false, "text": "Build Definition -> Workspace -> Build Agent Folder\n c:\\some\\path\n $(SourceDir)\n" }, { "answer_id": 25196199, "author": "rpstex", "author_id": 3920861, "author_profile": "https://Stackoverflow.com/users/3920861", "pm_score": 2, "selected": false, "text": "c:/users/myuser/appdata" }, { "answer_id": 40492823, "author": "AyeVeeKay", "author_id": 5292948, "author_profile": "https://Stackoverflow.com/users/5292948", "pm_score": 2, "selected": false, "text": "tf workspaces /remove:*\n" }, { "answer_id": 54839336, "author": "Majid", "author_id": 2040375, "author_profile": "https://Stackoverflow.com/users/2040375", "pm_score": 0, "selected": false, "text": "workspace /delete \"the-workspace-name\"\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
226,292
<p>I could write myself a helper class that does this when given a functor, but I was wondering if there's a better approach, or if there's something already in the standard library (seems like there should be).</p> <p>Answers I've found on StackOverflow are all for C# which doesn't help me.</p> <p>Thanks</p>
[ { "answer_id": 226326, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 4, "selected": true, "text": "commons-collections" }, { "answer_id": 2063544, "author": "Mario Fusco", "author_id": 112779, "author_profile": "https://Stackoverflow.com/users/112779", "pm_score": 2, "selected": false, "text": "List<User> topUsers = \n select(users, having(on(User.class).getReputation(), greaterThan(20000)));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
226,300
<p>What I want to do is an outer join to a table, where I exclude records from the joined table based on matching a constant, however keep records from the main table. For example:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id AND b.bar = 'foo' </code></pre> <p>Expected results:</p> <pre> id other baz -- ---------- ------- 1 Has foo Include 2 Has none (null) 3 Has foobar (null) </pre> <p>I can't get the same results by putting it in the filter condition. If I use the following:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id WHERE (b.bar IS NULL OR b.bar = 'foo') </code></pre> <p>I get these incorrect results:</p> <pre> id other baz -- -------- ------- 1 Has foo Include 2 Has none (null) </pre> <p>Where it excluded records of A that happen to match a record of B where bar = 'foobar'. I don't want that, I want A to be present, but B to be nulls in that case.</p> <p>Table B will have multiple records that need excluding, so I don't think I can filter this on the Crystal side without doing a lot of messing around to avoid problems from duplicate records from table A.</p> <p>I cannot use a SQL command object, as the third party application that we are running the reports from seems to choke on SQL command objects.</p> <p>I cannot use views, as our support contract does not permit database modifications, and our vendor considers adding views a database modification.</p> <p>I am working with Crystal Reports XI, specifically version 11.0.0.895. In case it makes a difference, I am running against a Progress 9.1E04 database using the SQL-92 ODBC driver.</p> <p>The sample tables and data used in the examples can be created with the following:</p> <pre><code>CREATE TABLE a (id INTEGER, other VARCHAR(32)); CREATE TABLE b (id INTEGER, bar VARCHAR(32), baz VARCHAR(32)); insert into A (id, other) values ('1', 'Has foo'); insert into A (id, other) values ('2', 'Has none'); insert into A (id, other) values ('3', 'Has foobar'); insert into B (id, bar, baz) values ('1', 'foo', 'Include'); insert into B (id, bar, baz) values ('1', 'foobar', 'Exclude'); insert into B (id, bar, baz) values ('1', 'another', 'Exclude'); insert into B (id, bar, baz) values ('1', 'More', 'Exclude'); insert into B (id, bar, baz) values ('3', 'foobar', 'Exclude'); </code></pre>
[ { "answer_id": 231338, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 0, "selected": false, "text": "SELECT a.id, x.baz\nFROM a\nLEFT OUTER JOIN \n (SELECT id, baz FROM b WHERE bar = 'foo') As x ON a.id = x.id\n" }, { "answer_id": 5824988, "author": "craig", "author_id": 134367, "author_profile": "https://Stackoverflow.com/users/134367", "pm_score": 0, "selected": false, "text": "(Isnull({b.bar}) OR {b.bar} = \"foo\")\n" }, { "answer_id": 13473350, "author": "nospamthanks", "author_id": 865435, "author_profile": "https://Stackoverflow.com/users/865435", "pm_score": 2, "selected": false, "text": "select * from b where bar= 'foo'" }, { "answer_id": 43273395, "author": "iMet", "author_id": 5268203, "author_profile": "https://Stackoverflow.com/users/5268203", "pm_score": 0, "selected": false, "text": "b.bar is null or b.bar = 'foo' if b.bar = 'foo'" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
226,302
<p>It seems safe to cast the result of my vector's <code>size()</code> function to an <code>unsigned int</code>. How can I tell for sure, though? My documentation isn't clear about how <code>size_type</code> is defined.</p>
[ { "answer_id": 226413, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": -1, "selected": false, "text": "BOOST_STATIC_ASSERT() BOOST_STATIC_ASSERT( sizeof( unsigned int) >= sizeof( size_type));\n" }, { "answer_id": 226575, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "std::vector<T>::size_type\n std::vector<std::string>::size_type i ;\nstd::vector<int>::size_type j ;\nstd::vector<std::vector<double> >::size_type k ;\n void doSomething(const std::vector<double> & p_aData)\n{\n std::vector<double>::size_type i = p_aData.size() ; // Old/Current way\n\n auto j = p_aData.size() ; // New C++0x way, definition\n decltype(p_aData.size()) k; // New C++0x way, declaration\n}\n typedef std::vector<int>::size_type VIntSize ;\n\nVIntSize getIndexOfSomeItem(const std::vector<int> p_aInt)\n{\n return /* the found value, or some kind of std::npos */\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
226,315
<p>I'm using polar plots (POLAR(THETA,RHO)) in MATLAB.</p> <p>Is there an easy way to fix the range for the radial axis to say, 1.5?</p> <p>I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.</p>
[ { "answer_id": 226493, "author": "Tim Whitcomb", "author_id": 24895, "author_profile": "https://Stackoverflow.com/users/24895", "pm_score": 4, "selected": true, "text": "theta = linspace(0,2*pi,100);\nr = sin(2*theta) .* cos(2*theta);\nr_max = 1;\nh_fake = polar(theta,r_max*ones(size(theta)));\nhold on;\nh = polar(theta, r);\nset(h_fake, 'Visible', 'Off');\n" }, { "answer_id": 1358809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "polar(0,30,'-k')\nhold on\n hold off\n" }, { "answer_id": 1991143, "author": "CalPolyAero", "author_id": 242242, "author_profile": "https://Stackoverflow.com/users/242242", "pm_score": 2, "selected": false, "text": "rlim = 10;\naxis([-1 1 -1 1]*rlim);\n" }, { "answer_id": 12380669, "author": "Ayesha Hakim", "author_id": 1664539, "author_profile": "https://Stackoverflow.com/users/1664539", "pm_score": 3, "selected": false, "text": "fake=100;\npolar(0,fake,'w');\nhold on;\n\nreal=10;\npolar(0,real,'w');\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20688/" ]
226,354
<p>I'm trying to drag a <code>CALayer</code> in an iOS app.</p> <p>As soon as I change its position property it tries to animate to the new position and flickers all over the place:</p> <pre><code> layer.position = CGPointMake(x, y) </code></pre> <p>How can I move <code>CALayers</code> instantly? I can't seem to get my head around the Core Animation API.</p>
[ { "answer_id": 226761, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 8, "selected": true, "text": "[CATransaction begin]; \n[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];\nlayer.position = CGPointMake(x, y);\n[CATransaction commit];\n" }, { "answer_id": 7409649, "author": "Biclops", "author_id": 465446, "author_profile": "https://Stackoverflow.com/users/465446", "pm_score": 5, "selected": false, "text": "[CATransaction setDisableActions:YES] \n" }, { "answer_id": 16381287, "author": "So Over It", "author_id": 423565, "author_profile": "https://Stackoverflow.com/users/423565", "pm_score": 4, "selected": false, "text": "CATransaction setDisableActions setAnimationDuration 0.0 [CATransaction begin];\n[CATransaction setAnimationDuration:0.0];\nlayer.position = CGPointMake(x, y);\n[CATransaction commit];\n" }, { "answer_id": 33961937, "author": "CryingHippo", "author_id": 4720722, "author_profile": "https://Stackoverflow.com/users/4720722", "pm_score": 5, "selected": false, "text": "extension CALayer {\n class func performWithoutAnimation(_ actionsWithoutAnimation: () -> Void){\n CATransaction.begin()\n CATransaction.setValue(true, forKey: kCATransactionDisableActions)\n actionsWithoutAnimation()\n CATransaction.commit()\n }\n}\n CALayer.performWithoutAnimation(){\n someLayer.position = newPosition\n}\n" }, { "answer_id": 53430084, "author": "Giles", "author_id": 978300, "author_profile": "https://Stackoverflow.com/users/978300", "pm_score": 3, "selected": false, "text": "extension CALayer\n{\n class func perform(withDuration duration: Double, actions: () -> Void) {\n CATransaction.begin()\n CATransaction.setAnimationDuration(duration)\n actions()\n CATransaction.commit()\n }\n}\n CALayer.perform(withDuration: 0.0) {\n aLayer.frame = aFrame\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30420/" ]
226,356
<p>I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time.</p> <p>I am using .NET 3.5 (thank god) but It's still baffling me.</p> <p>Thanks</p> <p>EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for. </p>
[ { "answer_id": 226408, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "var tzi = TimeZoneInfo.FindSystemTimeZoneById(\"Pacific Standard Time\");\nvar dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);\nConsole.WriteLine(dto);\nConsole.ReadLine();\n" }, { "answer_id": 227072, "author": "discorax", "author_id": 30408, "author_profile": "https://Stackoverflow.com/users/30408", "pm_score": 4, "selected": true, "text": "// _timeZoneId is the String value found in the System Registry.\n// You can look up the list of TimeZones on your system using this:\n// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones();\n// As long as your _timeZoneId string is in the registry \n// the _now DateTime object will contain\n// the current time (adjusted for Daylight Savings Time) for that Time Zone.\nstring _timeZoneId = \"Pacific Standard Time\";\nDateTime startTime = DateTime.UtcNow;\nTimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);\n_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);\n" }, { "answer_id": 5267140, "author": "CZahrobsky", "author_id": 888792, "author_profile": "https://Stackoverflow.com/users/888792", "pm_score": 1, "selected": false, "text": "//C#.NET\n public static bool IsDaylightSavingTime()\n {\n return IsDaylightSavingTime(DateTime.Now);\n }\n public static bool IsDaylightSavingTime(DateTime timeToCheck)\n {\n bool isDST = false;\n System.Globalization.DaylightTime changes \n = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);\n if (timeToCheck >= changes.Start && timeToCheck <= changes.End)\n {\n isDST = true;\n }\n return isDST;\n }\n\n\n'' VB.NET\nConst noDate As Date = #1/1/1950#\nPublic Shared Function IsDaylightSavingTime( _ \n Optional ByVal timeToCheck As Date = noDate) As Boolean\n Dim isDST As Boolean = False\n If timeToCheck = noDate Then timeToCheck = Date.Now\n Dim changes As DaylightTime = TimeZone.CurrentTimeZone _\n .GetDaylightChanges(timeToCheck.Year)\n If timeToCheck >= changes.Start And timeToCheck <= changes.End Then\n isDST = True\n End If\n Return isDST\nEnd Function\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30408/" ]
226,365
<p>I have a UIImagePickerController as one view in a TabBar setup. Is it possible to tell the UIImagePickerController to not show the Cancel button in the top navigation bar when browsing photos libraries?</p>
[ { "answer_id": 226408, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "var tzi = TimeZoneInfo.FindSystemTimeZoneById(\"Pacific Standard Time\");\nvar dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);\nConsole.WriteLine(dto);\nConsole.ReadLine();\n" }, { "answer_id": 227072, "author": "discorax", "author_id": 30408, "author_profile": "https://Stackoverflow.com/users/30408", "pm_score": 4, "selected": true, "text": "// _timeZoneId is the String value found in the System Registry.\n// You can look up the list of TimeZones on your system using this:\n// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones();\n// As long as your _timeZoneId string is in the registry \n// the _now DateTime object will contain\n// the current time (adjusted for Daylight Savings Time) for that Time Zone.\nstring _timeZoneId = \"Pacific Standard Time\";\nDateTime startTime = DateTime.UtcNow;\nTimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);\n_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);\n" }, { "answer_id": 5267140, "author": "CZahrobsky", "author_id": 888792, "author_profile": "https://Stackoverflow.com/users/888792", "pm_score": 1, "selected": false, "text": "//C#.NET\n public static bool IsDaylightSavingTime()\n {\n return IsDaylightSavingTime(DateTime.Now);\n }\n public static bool IsDaylightSavingTime(DateTime timeToCheck)\n {\n bool isDST = false;\n System.Globalization.DaylightTime changes \n = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);\n if (timeToCheck >= changes.Start && timeToCheck <= changes.End)\n {\n isDST = true;\n }\n return isDST;\n }\n\n\n'' VB.NET\nConst noDate As Date = #1/1/1950#\nPublic Shared Function IsDaylightSavingTime( _ \n Optional ByVal timeToCheck As Date = noDate) As Boolean\n Dim isDST As Boolean = False\n If timeToCheck = noDate Then timeToCheck = Date.Now\n Dim changes As DaylightTime = TimeZone.CurrentTimeZone _\n .GetDaylightChanges(timeToCheck.Year)\n If timeToCheck >= changes.Start And timeToCheck <= changes.End Then\n isDST = True\n End If\n Return isDST\nEnd Function\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29263/" ]
226,382
<p>I have SQL query, which is working nice on Oracle and MSSQL. Now I'm trying this on PostgreSQL and it gives a strange exception: <code>org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "main"</code></p> <p>Here is the query: </p> <pre><code>SELECT * FROM "main" main INNER JOIN "something_link" something_link ON main."id" = something_link."mainid" INNER JOIN "something" somehting ON something_link."somethingid" = something."id" INNER JOIN "type" type ON something."typeid" = type."id" </code></pre> <p>This is quite simple query and I can't see why it is not working on Windows XP SP2, PostgreSQL 8.3?</p>
[ { "answer_id": 228813, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 2, "selected": false, "text": "add_missing_from = on\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
226,392
<p>We have an intranet asp.net web application which uses the OOTB ASP.net membership and role providers. </p> <p>Now we are planning to expose the application to internet, by moving the web server to the DMZ as represented in the following (crappy) text diagram</p> <pre> External Internal internet --- Firewall --- Web server --- Firewall --- App Server --- Database DMZ Intranet </pre> <p>Now the problem is that the asp.net membership and role providers on the web server cant connect to the sql server because of the internal firewall.</p> <p>Have you ever faced such a scenario before? Will you recommend opening up ports in the internal firewall so that the webserver can directly connect to the SQL server? What other alternatives do I have (otherthan wring a custom provider myself)?</p>
[ { "answer_id": 227055, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": true, "text": "<roleManager enabled=\"true\" defaultProvider=\"RemoteRoleProvider\">\n <providers>\n <add name=\"RemoteRoleProvider\" type=\"MyCorp.RemoteRoleProvider, MyCorp\" serviceUrl=\"http://some_internal_url/RoleProviderService.svc\" />\n </providers>\n</roleManager>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747/" ]
226,405
<p>Anyone know how to get the position of a node using XPath?</p> <p>Say I have the following xml:</p> <pre><code>&lt;a&gt; &lt;b&gt;zyx&lt;/b&gt; &lt;b&gt;wvu&lt;/b&gt; &lt;b&gt;tsr&lt;/b&gt; &lt;b&gt;qpo&lt;/b&gt; &lt;/a&gt; </code></pre> <p>I can use the following xpath query to select the third &lt;b&gt; node (&lt;b&gt;tsr&lt;/b&gt;):</p> <pre><code>a/b[.='tsr'] </code></pre> <p>Which is all well and good but I want to <strong>return</strong> the ordinal position of that node, something like:</p> <pre><code>a/b[.='tsr']/position() </code></pre> <p>(but a bit more working!)</p> <p>Is it even possible?</p> <p><strong>edit</strong>: Forgot to mention am using .net 2 so it's xpath 1.0!</p> <hr /> <p><strong>Update</strong>: Ended up using <a href="https://stackoverflow.com/users/207/james-sulak">James Sulak</a>'s <a href="https://stackoverflow.com/questions/226405/find-position-of-a-node-using-xpath#227080">excellent answer</a>. For those that are interested here's my implementation in C#:</p> <pre><code>int position = doc.SelectNodes(&quot;a/b[.='tsr']/preceding-sibling::b&quot;).Count + 1; // Check the node actually exists if (position &gt; 1 || doc.SelectSingleNode(&quot;a/b[.='tsr']&quot;) != null) { Console.WriteLine(&quot;Found at position = {0}&quot;, position); } </code></pre>
[ { "answer_id": 226616, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" encoding=\"utf-8\" indent=\"yes\" \n omit-xml-declaration=\"yes\"/>\n <xsl:template match=\"a/*[text()='tsr']\">\n <xsl:number value-of=\"position()\"/>\n </xsl:template>\n <xsl:template match=\"text()\"/>\n</xsl:stylesheet>\n" }, { "answer_id": 227080, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 8, "selected": true, "text": "count(a/b[.='tsr']/preceding-sibling::*)+1.\n" }, { "answer_id": 228932, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Xml;\n\npublic class XpathFinder\n{\n public static void Main(string[] args)\n {\n XmlDocument xmldoc = new XmlDocument();\n xmldoc.Load(args[0]);\n foreach ( XmlNode xn in xmldoc.SelectNodes(args[1]) )\n {\n for (int i = 0; i < xn.ParentNode.ChildNodes.Count; i++)\n {\n if ( xn.ParentNode.ChildNodes[i].Equals( xn ) )\n {\n Console.Out.WriteLine( i );\n break;\n }\n }\n }\n }\n}\n" }, { "answer_id": 285164, "author": "geoffc", "author_id": 32247, "author_profile": "https://Stackoverflow.com/users/32247", "pm_score": 0, "selected": false, "text": "count(attr/value[.='$TARGET']/preceding-sibling::*)+1\n count(attr/value[.='$TARGET']/preceding::*) + 1\n" }, { "answer_id": 3437009, "author": "user414661", "author_id": 414661, "author_profile": "https://Stackoverflow.com/users/414661", "pm_score": 3, "selected": false, "text": "count(a/b[.='tsr']/preceding::a)+1.\n count(a/b[.='tsr']/preceding::*)+1.\n" }, { "answer_id": 27173072, "author": "Claus Jensen", "author_id": 4300603, "author_profile": "https://Stackoverflow.com/users/4300603", "pm_score": 2, "selected": false, "text": "count(a/b[.='tsr']/preceding-sibling::*)+number(boolean(a/b[.='tsr']))\n" }, { "answer_id": 32699932, "author": "CroWell", "author_id": 1400990, "author_profile": "https://Stackoverflow.com/users/1400990", "pm_score": 3, "selected": false, "text": "index-of(//b, //b[.='tsr'])\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6124/" ]
226,420
<p>Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.</p> <p>I mean something like this:</p> <pre><code>[TriggersMyCustomAction()] public void DoSomeStuff() { } </code></pre> <p>I am totally clueless how to do it or if it possible at all, but <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx" rel="noreferrer">System.Diagnostic.ConditionalAttribute</a> might do a similar thing in the background. I am not sure though.</p> <p><strong>EDIT</strong>: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.</p>
[ { "answer_id": 226472, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": false, "text": "//proxy\npublic override void DoSomeStuff()\n{\n if(MethodHasTriggerAttribute)\n Trigger();\n\n _innerClass.DoSomeStuff();\n}\n" }, { "answer_id": 21461846, "author": "Matt", "author_id": 1016343, "author_profile": "https://Stackoverflow.com/users/1016343", "pm_score": 5, "selected": false, "text": "ExceptionFilterAttribute AuthorizeAttribute System.Web.Http.Filters public class myAuthorizationAttribute : AuthorizeAttribute\n{\n protected override bool IsAuthorized(HttpActionContext actionContext)\n {\n // do any stuff here\n // it will be invoked when the decorated method is called\n if (CheckAuthorization(actionContext)) \n return true; // authorized\n else\n return false; // not authorized\n }\n\n}\n [myAuthorization]\npublic HttpResponseMessage Post(string id)\n{\n // ... your code goes here\n response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status\n return response;\n}\n Post IsAuthorized myAuthorization Post false IsAuthorized Post ExceptionFilter AuthorizeAttribute DivideByZeroExceptionFilter ExceptionFilterAttribute OnException public class DivideByZeroExceptionFilter : ExceptionFilterAttribute\n{\n public override void OnException(HttpActionExecutedContext actionExecutedContext)\n {\n if (actionExecutedContext.Exception is DivideByZeroException)\n {\n actionExecutedContext.Response = new HttpResponseMessage() { \n Content = new StringContent(\"A DIV error occured within the application.\",\n System.Text.Encoding.UTF8, \"text/plain\"), \n StatusCode = System.Net.HttpStatusCode.InternalServerError\n };\n }\n }\n}\n [DivideByZeroExceptionFilter]\npublic void Delete(int id)\n{\n // Just for demonstration purpose, it\n // causes the DivideByZeroExceptionFilter attribute to be triggered:\n throw new DivideByZeroException(); \n\n // (normally, you would have some code here that might throw \n // this exception if something goes wrong, and you want to make\n // sure it aborts properly in this case)\n}\n IExceptionFilter namespace System.Web.Http.Filters\n{\n public interface IExceptionFilter : IFilter\n {\n // Executes an asynchronous exception filter.\n // Returns: An asynchronous exception filter.\n Task ExecuteExceptionFilterAsync(\n HttpActionExecutedContext actionExecutedContext, \n CancellationToken cancellationToken);\n }\n}\n ExceptionFilterAttribute namespace System.Web.Http.Filters\n{\n // Represents the attributes for the exception filter.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, \n Inherited = true, AllowMultiple = true)]\n public abstract class ExceptionFilterAttribute : FilterAttribute, \n IExceptionFilter, IFilter\n {\n // Raises the exception event.\n // actionExecutedContext: The context for the action.\n public virtual void OnException(\n HttpActionExecutedContext actionExecutedContext)\n {\n }\n // Asynchronously executes the exception filter.\n // Returns: The result of the execution.\n Task IExceptionFilter.ExecuteExceptionFilterAsync(\n HttpActionExecutedContext actionExecutedContext, \n CancellationToken cancellationToken)\n {\n if (actionExecutedContext == null)\n {\n throw Error.ArgumentNull(\"actionExecutedContext\");\n }\n this.OnException(actionExecutedContext);\n return TaskHelpers.Completed();\n }\n }\n}\n ExecuteExceptionFilterAsync OnException public class CustomerService\n{\n [RetryOnException(MaxRetries = 5)]\n public void Save(Customer customer)\n {\n // Database or web-service call.\n }\n}\n Save [PSerializable]\npublic class RetryOnExceptionAttribute : MethodInterceptionAspect\n{\n public RetryOnExceptionAttribute()\n {\n this.MaxRetries = 3;\n }\n\n public int MaxRetries { get; set; }\n\n public override void OnInvoke(MethodInterceptionArgs args)\n {\n int retriesCounter = 0;\n\n while (true)\n {\n try\n {\n args.Proceed();\n return;\n }\n catch (Exception e)\n {\n retriesCounter++;\n if (retriesCounter > this.MaxRetries) throw;\n\n Console.WriteLine(\n \"Exception during attempt {0} of calling method {1}.{2}: {3}\",\n retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);\n }\n }\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
226,433
<p>When I first load data into a Silverlight DataGrid control, how can I make the screen look exactly as if the user had just clicked the header of the first column? In other words, the data should be sorted in ascending order according to that column's values, AND the little sort arrow should be displayed in the first column's header.</p> <p>Assuming that's possible, can I also make it look as if the user had clicked the first column and then shift-clicked the second? In other words, can I programatically apply a two-part sort and have the screen look as if the user had done it?</p>
[ { "answer_id": 4427732, "author": "Valentin", "author_id": 443379, "author_profile": "https://Stackoverflow.com/users/443379", "pm_score": 3, "selected": false, "text": "if (pcv.CanSort == true)\n{\n pcv.SortDescriptions.Add(new SortDescription(\"ProductionStatus\", ListSortDirection.Ascending));\n pcv.SortDescriptions.Add(new SortDescription(\"Date\", ListSortDirection.Descending));\n}\n" }, { "answer_id": 14439885, "author": "Jonathan Collins", "author_id": 1997218, "author_profile": "https://Stackoverflow.com/users/1997218", "pm_score": 1, "selected": false, "text": "<riaControls:DomainDataSource.SortDescriptors>\n <riaControls:SortDescriptor PropertyPath=\"ColumnName\" Direction=\"Descending\" />\n</riaControls:DomainDataSource.SortDescriptors>\n" }, { "answer_id": 24814658, "author": "George Birbilis", "author_id": 903783, "author_profile": "https://Stackoverflow.com/users/903783", "pm_score": 0, "selected": false, "text": " <Window.Resources>\n <app:MyData x:Key=\"MyData\"/>\n <CollectionViewSource x:Key=\"cvs\" Source={StaticResource MyData}>\n <CollectionViewSource.SortDescriptions>\n <SortDescription Property=\"Name\"/>\n </CollectionViewSource.SortDescriptions>\n </CollectionViewSource>\n </Window.Resources>\n\n <DataGrid ItemsSource=\"{Binding Source={StaticResource cvs}}\"/> \n <sort:SortDescription \n PropertyName=\"Name\"\n Direction=\"Ascending\"\n xmlns:sort=\"clr-namespace:System.ComponentModel;assembly=System.Windows\"\n /> \n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
226,436
<p>I have a custom control that exposes a property. When I set it using a fixed value, everything works correctly. But if I try to set its value using the &lt;%= %> tags, it goes a little whacky:</p> <pre><code>&lt;cc:CustomControl ID="CustomControl" runat="server" Property1='&lt;%= MyProperty %&gt;' /&gt; &lt;%= MyProperty %&gt; </code></pre> <p>When this gets rendered, the &lt;%= MyProperty %> tag underneat the custom control is rendered as I expect (with the value of MyProperty). However, when I step into the Render function of the CustomControl, the value for Property1 is literally the string "&lt;%= MyProperty %>" instead of the actual underlying value of MyProperty.</p>
[ { "answer_id": 226483, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": true, "text": "OnInit MyProperty OnInit <cc:CustomControl ID=\"CustomControl\" runat=\"server\" Property1='<%# MyProperty %>' />\n DataBind() CustomControl.Property1 = MyProperty;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
226,442
<p>I've been reading up on this subject for a while. Suddenly the day has come where this solution is a necessity, not just a dream.</p> <p>Through my reading, I've seen the popular differences being (file based, memcached, shared memory (mm), sql table, and custom).</p> <p>The original idea we thought of was using a ZFS or AFS mounted on each of the application servers (LAMP boxes), and pointing the <code>session.save_path</code> php.ini setting to a directory from that mounted path.</p> <p>I'd like to hear of success stories.</p>
[ { "answer_id": 226523, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "$options = array('memcache' => $memcache);\n $memcache" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14363/" ]
226,445
<p>As every Haxe developer knows, you could use <code>haxe.Timer.delayed()</code> to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?</p>
[ { "answer_id": 226489, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 3, "selected": true, "text": "function delayed(f, time) {\n neko.vm.Thread.create(function() {\n neko.Sys.sleep(time);\n f();\n });\n}\n" }, { "answer_id": 2861163, "author": "Tom", "author_id": 45974, "author_profile": "https://Stackoverflow.com/users/45974", "pm_score": 1, "selected": false, "text": "package;\nimport neko.Sys;\n\n class NekoTimer \n {\n private static var threadActive:Bool = false;\n private static var timersList:Array<TimerInfo> = new Array<TimerInfo>();\n private static var timerInterval:Float = 0.1;\n\n public static function addTimer(interval:Int, callMethod:Void->Void):Int\n {\n //setup timer thread if not yet active\n if (!threadActive) setupTimerThread();\n\n //add the given timer\n return timersList.push(new TimerInfo(interval, callMethod, Sys.time() * 1000)) - 1;\n }\n\n public static function delTimer(id:Int):Void\n {\n timersList.splice(id, 1);\n }\n\n private static function setupTimerThread():Void\n {\n threadActive = true;\n neko.vm.Thread.create(function() {\n while (true) {\n Sys.sleep(timerInterval);\n for (timer in timersList) {\n if (Sys.time() * 1000 - timer.lastCallTimestamp >= timer.interval) {\n timer.callMethod();\n timer.lastCallTimestamp = Sys.time() * 1000;\n }\n }\n }\n });\n }\n}\n\nprivate class TimerInfo\n{\n public var interval:Int;\n public var callMethod:Void->Void;\n public var lastCallTimestamp:Float;\n\n public function new(interval:Int, callMethod:Void->Void, lastCallTimestamp:Float) {\n this.interval = interval;\n this.callMethod = callMethod;\n this.lastCallTimestamp = lastCallTimestamp;\n }\n}\n package ;\n\nimport neko.Lib;\n\nclass Main \n{\n private var timerId:Int;\n\n public function new()\n {\n trace(\"setting up timer...\");\n timerId = NekoTimer.addTimer(5000, timerCallback);\n trace(timerId);\n\n //idle main app\n while (true) { }\n }\n\n private function timerCallback():Void\n {\n trace(\"it's now 5 seconds later\");\n NekoTimer.delTimer(timerId);\n trace(\"removed timer\");\n }\n\n //neko constructor\n static function main() \n {\n new Main();\n }\n}\n" }, { "answer_id": 20688200, "author": "Raul", "author_id": 3120179, "author_profile": "https://Stackoverflow.com/users/3120179", "pm_score": 1, "selected": false, "text": "//timer.lastCallTimestamp = Sys.time() * 1000;\ntimer.lastCallTimestamp = timer.lastCallTimestamp + timer.interval;\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6258/" ]
226,455
<p>Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized.</p> <p>Honestly I can't see the reasoning. I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why? What problems does it prevent? (And if it's actually necessary, why can't the wait method get the monitor itself?)</p> <p>I'm looking for a fairly in-depth why or maybe a reference to an article. I couldn't find one in a quick google.</p> <p>Oh, also, how does thread.sleep compare?</p> <p>edit: Great set of answers--I really wish I could select more than one because they all helped me understand what was going on.</p>
[ { "answer_id": 226479, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 4, "selected": true, "text": "public void doStuffOnThisObject()\n public void wait()\n" }, { "answer_id": 226644, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "public void synchWait() {\n syncronized { wait(); }\n}\n" }, { "answer_id": 227120, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "synchronized(o) {\n while(! checkCondition()) {\n o.wait();\n }\n}\n Lock lock = new ReentrantLock();\n Condition condition = lock.newCondition();\n lock.lock();\n try {\n while (! checkCondition()) {\n condition.await();\n }\n } finally {\n lock.unlock();\n }\n" }, { "answer_id": 1169781, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "If(queue is empty)\n queue.wait();\n Synchornized(queue)\n{\n if(queue is empty)\n queue.wait();\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12943/" ]
226,460
<p>I am trying to write a query for SQL Server 2005 but I can't figure out how to do it. I have a table with the following fields:</p> <p><strong>MessageID int<br/> CategoryID int<br/> Priority tinyint<br/> MessageText NVARCHAR(MAX)<br/></strong></p> <p>I need a query that will return * for each row that has the highest priority within a Category. For example, if I had the following data:</p> <p><strong>MessageID, CategoryID, Priority, MessageText</strong><br/> 1, 100, 1, Error #1234 occurred<br/> 2, 100, 2, Error #243 occurred<br/> 3, 100, 3, Error #976 occurred<br/> 4, 200, 4, Error #194 occurred<br/> 5, 200, 1, Error #736 occurred<br/> 6, 300, 3, Error #54 occurred<br/> 7, 300, 2, Error #888 occurred<br/></p> <p>then the result would be:</p> <p><strong>MessageID, CategoryID, Priority, MessageText</strong><br/> 3, 100, 3, Error #976 occurred<br/> 4, 200, 4, Error #194 occurred<br/> 6, 300, 3, Error #54 occurred<br/></p> <p>Notice that it returns one row per category, and that it is the row which had the highest priority for that Category.</p> <p>Can anyone tell me how I can write this query?</p>
[ { "answer_id": 226490, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "SELECT\n M.MessageId,\n M.CategoryId,\n M.Priority,\n M.MessageText\nFROM \n(\n SELECT \n CategoryId,\n MAX(Priority) AS Priority\n FROM Messages\n GROUP BY CategoryId\n) AS MaxValues\n INNER JOIN Messages M\n ON (MaxValues.CategoryId = M.CategoryId\n AND MaxValues.Priority = M.Priority)\n" }, { "answer_id": 226522, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": 0, "selected": false, "text": "SELECT\n Messages.MessageID\n , Messages.CategoryID\n , Messages.Priority\n , Messages. MessageText\nFROM\n Messages\n INNER JOIN\n (\n SELECT \n CategoryID\n , MAX(Priority) AS Priority\n FROM \n Messages\n GROUP BY\n CategoryID\n ) AS MaxResults\n ON\n (\n Messages.CategoryID = MaxResults.CategoryID\n AND\n Messages.Priority = MaxResults.Priority\n )\n" }, { "answer_id": 226527, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 4, "selected": true, "text": "SELECT\n highest_priority_messages.*\nFROM\n(\n SELECT\n m.MessageID\n , m.CategoryID\n , m.Priority\n , m.MessageText\n , Rank() OVER \n (PARTITION BY m.CategoryID ORDER BY m.Priority DESC) AS p_rank\n FROM [Message] m\n GROUP BY \n m.CategoryID \n , m.Priority\n , m.MessageID\n , m.MessageText\n) highest_priority_messages\nWHERE \n p_rank = 1\n" }, { "answer_id": 226617, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "select ms.*\nfrom \n messages ms\n ,(\n select ms1.categoryid, max(ms1.priority) as max_priority\n from messages ms1\n group by ms1.categoryid\n ) tmp\nwhere ms.categoryid = tmp.categoryid\n and ms.priority = tmp.max_priority;\n" }, { "answer_id": 227404, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "SELECT\n MessageID,\n CategoryID,\n Priority,\n MessageText\nFROM\n dbo.Messages M1\nLEFT OUTER JOIN dbo.Messages M2 ON\n M2.CategoryID = M1.CategoryID AND\n M2.Priority > M1.Priority\nWHERE\n M2.MessageID IS NULL\n" }, { "answer_id": 227742, "author": "Jeff", "author_id": 5685, "author_profile": "https://Stackoverflow.com/users/5685", "pm_score": 0, "selected": false, "text": "SELECT\n highest_priority_messages.*\nFROM\n(\n SELECT\n m.MessageID\n , m.CategoryID\n , m.Priority\n , m.MessageText\n , Rank() OVER \n (PARTITION BY m.CategoryID ORDER BY m.Priority DESC, m.MessageID DESC) AS p_rank\n FROM [Message] m\n GROUP BY \n m.CategoryID \n , m.Priority\n , m.MessageID\n , m.MessageText\n) highest_priority_messages\nWHERE \n p_rank = 1\n insert into [Message] (MessageID, CategoryID, Priority, MessageText)\nselect 8, 100, 3, 'Error #976-2 occurred'\n" }, { "answer_id": 4002209, "author": "Raj", "author_id": 484825, "author_profile": "https://Stackoverflow.com/users/484825", "pm_score": 1, "selected": false, "text": "select distinct query1.* from\n\n(select categoryId,msgText,max(priorityId) as MAX_PRIORITY\n from message\n group by categoryId,msgText\n order by categoryId\n) query1,\n\n\n(select categoryId,max(priorityId) as MAX_PRIORITY\n from message\n group by categoryId\n order by categoryId\n) query2\n\nwhere query1.MAX_PRIORITY = query2.MAX_PRIORITY\n\norder by query1.categoryId\n" }, { "answer_id": 8132344, "author": "Kamy", "author_id": 1027052, "author_profile": "https://Stackoverflow.com/users/1027052", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT CategoryId,PS.Priority,MessageID,MessageText\nFROM Priority_Scene PS\nJOIN (SELECT MAX(Priority) AS Priority FROM Priority_Scene GROUP BY CategoryId) A\nON A.Priority = PS.Priority\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
226,464
<p>How do you solve the problem with soft hyphens on your web pages? In a text there can be long words which you might want to line break with a hyphen. But you do not want the hyphen to show if the whole word is on the same line.</p> <p>According to comments on <a href="http://www.thefutureoftheweb.com/blog/breaking-long-urls" rel="noreferrer">this page</a> <code>&lt;wbr&gt;</code> is a non standard "tag soup invented by Netscape". It seems like <code>&amp;shy;</code> <a href="http://www.cs.tut.fi/~jkorpela/shy.html" rel="noreferrer">has its problems with standard compliance as well</a>. There seems to be <a href="http://www.quirksmode.org/oddsandends/wbr.html" rel="noreferrer">no way to get a working solution for all browsers</a>.</p> <p>Which is your way for handling soft hyphens and why did you choose it? Is there a preferred solution or best practice?</p> <p><hr> See related SO Discussion <a href="https://stackoverflow.com/questions/904/in-html-how-to-word-break-on-a-dash">here</a>.</p>
[ { "answer_id": 227284, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 8, "selected": true, "text": "&shy &shy;" }, { "answer_id": 2091298, "author": "anthonyv", "author_id": 252895, "author_profile": "https://Stackoverflow.com/users/252895", "pm_score": 2, "selected": false, "text": "(function($) { \n $.fn.breakWords = function() { \n this.each(function() { \n if(this.nodeType !== 1) { return; } \n\n if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { \n //Lazy Function Definition Pattern, Peter's Blog \n //From http://peter.michaux.ca/article/3556 \n this.runtimeStyle.wordBreak = 'break-all'; \n } \n else if(document.createTreeWalker) { \n\n //Faster Trim in Javascript, Flagrant Badassery \n //http://blog.stevenlevithan.com/archives/faster-trim-javascript \n\n var trim = function(str) { \n str = str.replace(/^\\s\\s*/, ''); \n var ws = /\\s/, \n i = str.length; \n while (ws.test(str.charAt(--i))); \n return str.slice(0, i + 1); \n }; \n\n //Lazy Function Definition Pattern, Peter's Blog \n //From http://peter.michaux.ca/article/3556 \n\n //For Opera, Safari, and Firefox \n var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); \n var node,s,c = String.fromCharCode('8203'); \n while (dWalker.nextNode()) { \n node = dWalker.currentNode; \n //we need to trim String otherwise Firefox will display \n //incorect text-indent with space characters \n s = trim( node.nodeValue ).split('').join(c); \n node.nodeValue = s; \n } \n } \n }); \n\n return this; \n }; \n})(jQuery); \n" }, { "answer_id": 14797954, "author": "Dominik", "author_id": 202974, "author_profile": "https://Stackoverflow.com/users/202974", "pm_score": 5, "selected": false, "text": "&shy;" }, { "answer_id": 14891395, "author": "Matthias Ronge", "author_id": 1503237, "author_profile": "https://Stackoverflow.com/users/1503237", "pm_score": 5, "selected": false, "text": "&shy; &shy; Spargelder Spar-gel-der Spargel- Wachstube Wach-stu-be Wachs-tu-be" }, { "answer_id": 21920078, "author": "Tommy Kronkvist", "author_id": 3334719, "author_profile": "https://Stackoverflow.com/users/3334719", "pm_score": 0, "selected": false, "text": "&#173; &shy;" }, { "answer_id": 23589405, "author": "dmitry_romanov", "author_id": 774971, "author_profile": "https://Stackoverflow.com/users/774971", "pm_score": 2, "selected": false, "text": "\\u00AD s = u'Языки и методы програм\\u00ADми\\u00ADро\\u00ADва\\u00ADния' ¦ $(document).ready(...) s = u'Языки и методы про¦гра¦м¦ми¦ро¦ва¦ния'.replace('¦', u'\\u00AD') s = u'Языки и методы про\\u00ADг\\u00ADра\\u00ADм\\u00ADми\\u00ADро\\u00ADва\\u00ADния'" }, { "answer_id": 28672471, "author": "user56reinstatemonica8", "author_id": 568458, "author_profile": "https://Stackoverflow.com/users/568458", "pm_score": 6, "selected": false, "text": "&#173; &shy; &#173; <wbr> &shy; &#173; &shy; &#173; &#173; &shy; &shy; confumbabbl&shy;ication&shy;ism <wbr> donfounbabbl<wbr>ication<wbr>ism <wbr/> &#173; eonfulbabbl&#173;ication&#173;ism ZZZconfumbabblicationismZZZdonfounbabblicationismZZZeonfulbabblicationismZZZ &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; word-wrap &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; <wbr> &shy; &#173; &shy; &#173; &shy; &#173; &#173; &shy; &shy; &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173; &shy; <wbr> &#173;" }, { "answer_id": 29720524, "author": "Andreas Rejbrand", "author_id": 282848, "author_profile": "https://Stackoverflow.com/users/282848", "pm_score": 4, "selected": false, "text": "<wbr> &shy; &shy; innehålls&shy;förteckning\n innehållsförteckning\n innehålls-\nförteckning\n wbr wbr ABCDEFG<wbr/>abcdefg\n ABCDEFGabcdefg\n ABCDEFG\nabcdefg\n" }, { "answer_id": 32973100, "author": "AVL geek", "author_id": 5414475, "author_profile": "https://Stackoverflow.com/users/5414475", "pm_score": 3, "selected": false, "text": "<wbr> &#8203;\n &#8288;\n" }, { "answer_id": 34821256, "author": "Weijing Jay Lin", "author_id": 1257916, "author_profile": "https://Stackoverflow.com/users/1257916", "pm_score": 2, "selected": false, "text": "wbr <p>这里有一段很长,很长的<wbr\n></wbr>文字;这里有一段</p>\n &shy;" }, { "answer_id": 56836890, "author": "Roberto Góes", "author_id": 5273803, "author_profile": "https://Stackoverflow.com/users/5273803", "pm_score": 0, "selected": false, "text": " https://stackoverflow.com/questions/226464/soft-hyphen-in-html-wbr-vs-shy\n div{\n max-width: 130px;\n border-width: 2px;\n border-style: dashed;\n border-color: #f00;\n padding: 10px;\n} <div>https://<wbr>stackoverflow.com<wbr>/questions/226464<wbr>/soft-hyphen-in-<wbr>html-wbr-vs-shy</div>\n\n<div>É im&shy;pos&shy;sí&shy;vel pa&shy;ra um ho&shy;mem a&shy;pren&shy;der a&shy;qui&shy;lo que ele acha que já sa&shy;be.</div>" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5392/" ]
226,465
<p>Here's a silly fun question:</p> <p>Let's say we have to perform a simple operation where we need half of the value of a variable. There are <em>typically</em> two ways of doing this:</p> <pre><code>y = x / 2.0; // or... y = x * 0.5; </code></pre> <p>Assuming we're using the standard operators provided with the language, which one has better performance?</p> <p>I'm guessing multiplication is typically better so I try to stick to that when I code, but I would like to confirm this. </p> <p>Although personally I'm interested in the answer for <strong>Python</strong> 2.4-2.5, feel free to also post an answer for other languages! And if you'd like, feel free to post other fancier ways (like using bitwise shift operators) as well.</p>
[ { "answer_id": 226502, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": " int y = 10;\n y = y >> 1;\n Console.WriteLine(\"value halved: \" + y);\n y = y << 1;\n Console.WriteLine(\"now value doubled: \" + y);\n" }, { "answer_id": 226515, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "y = x / 3.0;\ny = x * 0.333333; // how many 3's should there be, and how will the compiler round?\n x = 100.0;\nx / 3.0 == x * (1.0/3.0) // is false in the test I just performed\n" }, { "answer_id": 226563, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 6, "selected": false, "text": "time python -c 'for i in xrange(int(1e8)): t=12341234234.234 / 2.0'\nreal 0m26.676s\nuser 0m25.154s\nsys 0m0.076s\n\ntime python -c 'for i in xrange(int(1e8)): t=12341234234.234 * 0.5'\nreal 0m17.932s\nuser 0m16.481s\nsys 0m0.048s\n time lua -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'\nreal 0m7.956s\nuser 0m7.332s\nsys 0m0.032s\n\ntime lua -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'\nreal 0m7.997s\nuser 0m7.516s\nsys 0m0.036s\n time luajit -O -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'\nreal 0m1.921s\nuser 0m1.668s\nsys 0m0.004s\n\ntime luajit -O -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'\nreal 0m1.843s\nuser 0m1.676s\nsys 0m0.000s\n" }, { "answer_id": 228058, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": ">>> for i in range(7):\n... a=1/(10.0**i)\n... b=(1/10.0)**i\n... print i, a, b, a-b\n... \n0 1.0 1.0 0.0\n1 0.1 0.1 0.0\n2 0.01 0.01 -1.73472347598e-18\n3 0.001 0.001 -2.16840434497e-19\n4 0.0001 0.0001 -1.35525271561e-20\n5 1e-05 1e-05 -1.69406589451e-21\n6 1e-06 1e-06 -4.23516473627e-22\n" }, { "answer_id": 656525, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 5, "selected": false, "text": "y = x * (1.0 / 2.0);\n y = x / 2.0" }, { "answer_id": 1965541, "author": "Carson Myers", "author_id": 84478, "author_profile": "https://Stackoverflow.com/users/84478", "pm_score": 4, "selected": false, "text": "int main() {\n\n volatile int a;\n volatile int b;\n\n asm(\"## 5/2\\n\");\n a = 5;\n a = a / 2;\n\n asm(\"## 5*0.5\");\n b = 5;\n b = b * 0.5;\n\n asm(\"## done\");\n\n return a + b;\n\n}\n gcc tdiv.c -O1 -o tdiv.s -S movl $5, -4(%ebp)\nmovl -4(%ebp), %eax\nmovl %eax, %edx\nshrl $31, %edx\naddl %edx, %eax\nsarl %eax\nmovl %eax, -4(%ebp)\n movl $5, -8(%ebp)\nmovl -8(%ebp), %eax\npushl %eax\nfildl (%esp)\nleal 4(%esp), %esp\nfmuls LC0\nfnstcw -10(%ebp)\nmovzwl -10(%ebp), %eax\norw $3072, %ax\nmovw %ax, -12(%ebp)\nfldcw -12(%ebp)\nfistpl -16(%ebp)\nfldcw -10(%ebp)\nmovl -16(%ebp), %eax\nmovl %eax, -8(%ebp)\n int double flds LC0\nfstl -8(%ebp)\nfldl -8(%ebp)\nflds LC1\nfmul %st, %st(1)\nfxch %st(1)\nfstpl -8(%ebp)\nfxch %st(1)\n fstpl -16(%ebp)\nfldl -16(%ebp)\nfmulp %st, %st(1)\nfstpl -16(%ebp)\n main() a + b ## 5/2\n\n## 5*0.5\n## done\n\nmovl $5, %eax\nleave\nret\n" }, { "answer_id": 4112754, "author": "Chris", "author_id": 499165, "author_profile": "https://Stackoverflow.com/users/499165", "pm_score": 1, "selected": false, "text": "1*1e-6F;\n\n1/1e6F;\n" }, { "answer_id": 7730288, "author": "PiotrK", "author_id": 151150, "author_profile": "https://Stackoverflow.com/users/151150", "pm_score": 1, "selected": false, "text": "public void Mutiplication()\n{\n float a = 1.0f;\n\n for(int i=0; i<1000000; i++)\n {\n a *= 0.5f;\n }\n}\npublic void Division()\n{\n float a = 1.0f;\n\n for(int i=0; i<1000000; i++)\n {\n a /= 2.0f;\n }\n}\n Multiplications(): time/call: 1524.375 ms\nDivision(): time/call: 1220.003 ms\n" }, { "answer_id": 8943848, "author": "satnhak", "author_id": 323316, "author_profile": "https://Stackoverflow.com/users/323316", "pm_score": -1, "selected": false, "text": "x y y^{-1} y*y^{-1} = 1 x*y^{-1} y^{-1} y" }, { "answer_id": 11271369, "author": "Gene", "author_id": 1161878, "author_profile": "https://Stackoverflow.com/users/1161878", "pm_score": 3, "selected": false, "text": "0.5 * x 1.0/2.0 * x x / 2.0" }, { "answer_id": 50582198, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 0, "selected": false, "text": "double half(double x) => x / 2.0;\n double half(double x) => x * 0.5;\n double quantize(double x)\n{\n if (half(x) > threshold))\n return 1;\n else\n return -1;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494/" ]
226,473
<p>I'm betting that someone has already solved this and maybe I'm using the wrong search terms for google to tell me the answer, but here is my situation.</p> <p>I have a script that I want to run, but I want it to run only when scheduled and only one at a time. (can't run the script simultaneously) </p> <p>Now the sticky part is that say I have a table called "myhappyschedule" which has the data I need and the scheduled time. This table can have multiple scheduled times even at the same time, each one would run this script. So essentially I need a queue of each time the script fires and they all need to wait for each one before it to finish. (sometimes this can take just a minute for the script to execute sometimes its many many minutes)</p> <p>What I'm thinking about doing is making a script that checks myhappyschedule every 5 min and gathers up those that are scheduled, puts them into a queue where another script can execute each 'job' or occurrence in the queue in order. Which all of this sounds messy. </p> <p>To make this longer - I should say that I'm allowing users to schedule things in myhappyschedule and not edit crontab. </p> <p>What can be done about this? File locks and scripts calling scripts?</p>
[ { "answer_id": 226661, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 3, "selected": true, "text": "exec_status myhappytable time_started time_finished [create/check pid lock (optional, but see \"A potential pitfall\" below)]\nget number of rows from myhappytable where (exec_status == executing_now)\nif it is > 0, exit\nbegin loop\n get one row from myhappytable\n where (exec_status == not_yet_run) and (scheduled_time <= now)\n order by scheduled_time asc\n if no such row, exit\n set row exec_status to executing_now (maybe set time_started to now)\n execute whatever command the row contains\n set row exec_status to completed\n (maybe also store the command output/return as well, set time_finished to now)\nend loop\n[delete pid lock file (complementary to the starting pid lock check)]\n if exists pidlockfile then\n check if process id given in file exists\n if not exists then\n update myhappytable set exec_status = error_cronscript_died_while_executing_this \n where exec_status == executing_now\n delete pidlockfile\n else (previous instance still running)\n exit\n endif\nendif\ncreate pidlockfile containing cron script process id\n" }, { "answer_id": 836955, "author": "Nick Zalutskiy", "author_id": 1959, "author_profile": "https://Stackoverflow.com/users/1959", "pm_score": 0, "selected": false, "text": "./pipeline \"<any command and arguments go here>\" ./pipeline sleep 10 &\n./pipeline shabugabu &\n./pipeline single_instance_script some arguments &\n./pipeline single_instance_script some other_argumnts &\n./pipeline \"single_instance_script some yet_other_arguments > output.txt\" &\n..etc\n sleep shabugabu single_instance_script single_instance_script some arguments some other_arguments at at now <<< \"./pipeline some_script\" #!/bin/bash -Eue\n\n# Using command name as the pipeline name\npipeline=$(basename $(expr \"$1\" : '\\(^[^[:space:]]*\\)')).pipe\nis_reader=false\n\nfunction _pipeline_cleanup {\n if $is_reader; then\n rm -f $pipeline\n fi\n rm -f $pipeline.lock\n\n exit\n}\ntrap _pipeline_cleanup INT TERM EXIT\n\n# Dispatch/initialization section, critical\nlockfile $pipeline.lock\n if [[ -p $pipeline ]]\n then\n echo \"$*\" > $pipeline\n exit\n fi\n\n is_reader=true\n mkfifo $pipeline\n echo \"$*\" > $pipeline &\nrm -f $pipeline.lock\n\n# Reader section\nwhile read command < $pipeline\ndo\n echo \"$(date) - Executing $command\"\n ($command) &> /dev/null\ndone\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30413/" ]
226,505
<p>I have the following regex that does a great job matching urls: </p> <pre><code>((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&amp;]*)` </code></pre> <p>However, it does not handle urls without a prefix, ie. <strong>stackoverflow.com</strong> or <strong>www.google.com</strong> do not match. Anyone know how I can modify this regex to not care if there is a prefix or not?</p> <hr> <p>EDIT: Does my question too vague? Does it need more details?</p> <hr> <pre><code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\)))?[\w\d:#@%/;$()~_?\+-=\\\.&amp;]*) </code></pre> <p>I added a ()? around the protocols like <strong>Vinko Vrsalovic</strong> suggested, but now the regex will match nearly any string, as long as it has valid URL characters.</p> <p>My implementation of this is I have a database that I manage the contents, and it has a field that either has plain text, a phone number, a URL or an email address. I was looking for an easy way to validate the input so I can have it properly formatted, ie. creating anchor tags for the url/email, and formatting the phone number how I have the other numbers formatted throughout the site. Any suggestions?</p>
[ { "answer_id": 226556, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": -1, "selected": false, "text": ".*\n" }, { "answer_id": 226573, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": ">>> r = re.compile('(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)?[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)')\n>>> r.search('oompaloompa_is_not_an_ur%&%%l').groups()[0]\n'oompaloompa_is_not_an_ur%&%%l' #Matches!\n>>> r.search('oompaloompa_isdfjakojfsdi.sdnioknfsdjknfsdjk.fsdnjkfnsdjknfsdjk').groups()[0]\n'oompaloompa_isdfjakojfsdi.sdnioknfsdjknfsdjk.fsdnjkfnsdjknfsdjk' #Matches!\n>>> \n" }, { "answer_id": 226621, "author": "marto", "author_id": 29555, "author_profile": "https://Stackoverflow.com/users/29555", "pm_score": 0, "selected": false, "text": "(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)? (((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)?[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)" }, { "answer_id": 226709, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 2, "selected": false, "text": "\\b\n# Match the leading part (proto://hostname, or just hostname)\n(\n # ftp://, http://, or https:// leading part\n (ftp|https?)://[-\\w]+(\\.\\w[-\\w]*)+\n |\n # or, try to find a hostname with our more specific sub-expression\n (?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \\. )+ # sub domains\n # Now ending .com, etc. For these, require lowercase\n (?-i: com\\b\n | edu\\b\n | biz\\b\n | gov\\b\n | in(?:t|fo)\\b # .int or .info\n | mil\\b\n | net\\b\n | org\\b\n | name\\b\n | coop\\b\n | aero\\b\n | museum\\b\n | [a-z][a-z]\\b # two-letter country codes\n )\n)\n\n# Allow an optional port number\n( : \\d+ )?\n\n# The rest of the URL is optional, and begins with / . . . \n(\n /\n # The rest are heuristics for what seems to work well\n [^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]*\n (?:\n [.!,?]+ [^.!,?;\"'<>()\\[\\]{}\\s\\x7F-\\xFF]+\n )*\n)?\n" }, { "answer_id": 226893, "author": "caskey", "author_id": 114986, "author_profile": "https://Stackoverflow.com/users/114986", "pm_score": 1, "selected": false, "text": "scheme ':' schemepart\n frob -> http://frob\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
226,510
<p>Say I have a form like:</p> <pre><code>class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) </code></pre> <p>And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:</p> <pre><code>rest of page ... &lt;form ..&gt; GeneralForm(data,prefix="form1").as_table() GeneralForm(data,prefix="form2").as_table() &lt;input type="submit" /&gt; &lt;/form&gt; rest of page ... </code></pre> <p>When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms" rel="noreferrer">This was the only documentation</a> I could find and it's peckish.</p>
[ { "answer_id": 226568, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "def some_view(request):\n if request.method == 'POST':\n form1 = GeneralForm(request.POST, prefix='form1')\n form2 = GeneralForm(request.POST, prefix='form2')\n if all([form1.is_valid(), form2.is_valid()]):\n pass # Do stuff with the forms\n else:\n form1 = GeneralForm(prefix='form1')\n form2 = GeneralForm(prefix='form2')\n return render_to_response('some_template.html', {\n 'form1': form1,\n 'form2': form2,\n })\n" }, { "answer_id": 276697, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 3, "selected": false, "text": "class GeneralForm(forms.Form):\n field1 = forms.IntegerField(required=False)\n field2 = forms. IntegerField(required=False)\n\nfrom django.forms.formsets import formset_factory\n\n# GeneralSet is a formset with 2 occurrences of GeneralForm \n# ( as a formset allows the user to add new items, this enforces\n# 2 fixed items, no less, no more )\nGeneralSet = formset_factory(GeneralForm, extra=2, max_num=2)\n\n# example view\n\ndef someview(request):\n general_set = GeneralSet(request.POST)\n if general_set.is_valid():\n for form in general_set.forms:\n # do something with data\n return render_to_response(\"template.html\", {'form': general_set}, RequestContext(request))\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
226,514
<p>I seem to remember reading that it's possible to declare taglib directives such as:</p> <pre><code>&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; </code></pre> <p>in web.xml. This eliminates the need to duplicate this directive in every JSP file where the taglib is used. Could someone tell me <em>how</em> these directives can be added to web.xml?</p>
[ { "answer_id": 228430, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 6, "selected": true, "text": "taglib taglib taglib <%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n <%@ taglib prefix=\"ex\" uri=\"/taglib.tld\" %>\n taglib <taglib>\n <taglib-uri>\n http://www.example.com/taglib\n </taglib-uri>\n <taglib-location>\n /taglib.tld\n </taglib-location>\n</taglib>\n <%@ taglib prefix=\"ex\" uri=\"http://www.example.com/taglib\" %>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
226,528
<p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p> <p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p> <p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
[ { "answer_id": 226536, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 4, "selected": false, "text": "<a href=\"/\"> /" }, { "answer_id": 226540, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "from django.conf.urls.defaults import *\n\nurlpatterns = patterns('myproject.views',\n url(r'^$', 'index', name='index'),\n)\n <a href=\"{% url index %}\">...\n <a href=\"{% url 'index' %}\">...\n" }, { "answer_id": 226793, "author": "ryansholin", "author_id": 23980, "author_profile": "https://Stackoverflow.com/users/23980", "pm_score": 3, "selected": false, "text": "context_instance=RequestContext(request) {{ SITE_URL }}" }, { "answer_id": 3374528, "author": "justin jools", "author_id": 407048, "author_profile": "https://Stackoverflow.com/users/407048", "pm_score": 2, "selected": false, "text": "(r'^$', 'django.views.generic.simple.redirect_to', {'url': '/home/'}),\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
226,555
<p>I am trying to make a view slide from top to bottom. This is not a big deal, I used <code>CABasicAnimation</code> for this. The problem is when I want to remove the view. I use this animation.</p> <pre><code>CABasicAnimation *animation; animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setDelegate:self]; animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.view.layer.position.x, 0 - self.view.bounds.size.height / 2)]; animation.fromValue = [NSValue valueWithCGPoint:self.view.layer.position]; animation.autoreverses = NO; animation.repeatCount = 0; animation.duration = 0.25; animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]; [self.view.layer addAnimation:animation forKey:@"moveX"]; </code></pre> <p>Which animates the view perfectly. But, after the animation finishes, my view appears again. So I added this line :</p> <pre><code>[self.view removeFromSuperview]; </code></pre> <p>Which removes the view, but with no animation. So I decided to add the remove code to this delegate:</p> <pre><code>-(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag </code></pre> <p>So now, the animation works, the view disappears, but sometimes, I can see the view appear and disappear faster, is like after the animation, the view appears, then the <code>animationDidStop</code> delegate is called, and the view disappears, obviously this is awful. What am I doing wrong?</p>
[ { "answer_id": 226645, "author": "Rob Drimmie", "author_id": 24213, "author_profile": "https://Stackoverflow.com/users/24213", "pm_score": -1, "selected": false, "text": "self.view.hidden = YES;\n [self.view setHidden:YES];\n" }, { "answer_id": 226707, "author": "danimal", "author_id": 29263, "author_profile": "https://Stackoverflow.com/users/29263", "pm_score": 0, "selected": false, "text": "set.view.hidden = YES;\n" }, { "answer_id": 227798, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": " [self.view.layer addAnimation:animation forKey:@\"moveX\"];\nself.view.layer.position = [animation.toValue CGPointValue];\n" }, { "answer_id": 250754, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "animation.fillMode = kCAFillModeForwards;\nanimation.removedOnCompletion = NO; -(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag {\n if (animation == [containerView.layer animationForKey:@\"moveX\"]) {\n // remove view here, add another view and/or start another transition\n }\n}\n" }, { "answer_id": 15075455, "author": "FreeAsInBeer", "author_id": 632736, "author_profile": "https://Stackoverflow.com/users/632736", "pm_score": 2, "selected": false, "text": "CAAnimationGroup *animGroup = [CAAnimationGroup animation];\n\n// MAKE SURE YOU HAVE THESE TWO LINES.\nanimGroup.removedOnCompletion = NO;\nanimGroup.fillMode = kCAFillModeForwards;\n\nanimGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim, nil];\nanimGroup.duration = tAnimationDuration;\n[tImageView.layer addAnimation:animGroup forKey:nil];\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29642/" ]
226,562
<p>I am not very good with Regex but I am learning.</p> <p>I would like to remove some html tag by the class name. This is what I have so far :</p> <pre><code>&lt;div class=&quot;footer&quot;.*?&gt;(.*?)&lt;/div&gt; </code></pre> <p>The first .*? is because it might contain other attribute and the second is it might contain other html stuff.</p> <p>What am I doing wrong? I have try a lot of set without success.</p> <h3>Update</h3> <p>Inside the DIV it can contain multiple line and I am playing with Perl regex.</p>
[ { "answer_id": 226583, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 0, "selected": false, "text": "<div class=\\\"footer\\\".*?>(.*?)<\\/div>\n" }, { "answer_id": 226586, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": -1, "selected": false, "text": "<div class=\"footer\".*?</div>" }, { "answer_id": 226591, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "<div[^>]*class=\"footer\"[^>]*>(.*?)</div>\n <div>\n <div class=\"footer\">\n <div>Hi!</div>\n </div>\n</div>\n document = //load document\ndivs = document.getElementsByTagName(\"div\");\nfor(div in divs) {\n if(div.getAttributes[\"class\"] == \"footer\") {\n parent = div.getParent();\n for(child in div.getChildren()) {\n // filter attribute types?\n parent.insertBefore(div, child);\n }\n parent.removeChild(div);\n }\n}\n" }, { "answer_id": 226594, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 0, "selected": false, "text": "<([^\\s]+).*?class=\"footer\".*?>([.\\n]*?)</([^\\s]+)>\n <div class=\"footer\"><b></b></div>\n </b> </div>" }, { "answer_id": 226601, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "/s" }, { "answer_id": 226604, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 0, "selected": false, "text": ".*? </div> <div class=\"SomethingElse\"><div class=\"footer\"> stuff </div></div> <div class=\"footer\"> stuff </div></div>" }, { "answer_id": 226669, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 4, "selected": false, "text": "use HTML::TreeBuilder::XPath;\n\nmy $tree = HTML::TreeBuilder::XPath->new;\n$tree->parse_file( 'yourdocument.html' );\n\nfor my $node ( $tree->findnodes( '//*[@class=\"footer\"]' ) ) {\n $node->replace_with_content; # delete element, but not the children\n}\n\nprint $tree->as_HTML;\n" }, { "answer_id": 514525, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<div[^>]*class=\"footer\"[^>]*>(.*?)</div>\n <div[^>]*class=\\\"footer\\\"[^>]*>(.*?)<\\/div>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
226,565
<p>I've been spoiled by Visual studio 2008 and Eclipse and have to do a little maintainence work on a VB6 app.</p> <p>Does anyone know of an alternative/ updated IDE for VB6?</p> <p>A rewrite is not an option I'm just fixing a couple of bugs and it's a big codebase.</p>
[ { "answer_id": 232476, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "set PATH=\"d:\\Program Files\\Microsoft Visual Studio\\VB98\\\";%PATH%\nvb6.exe /out ErrorFile.txt /make MyProject.vbp\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
226,577
<p>Strange program hang, what does this mean in debug?</p> <p>After attaching windbg I found the following:</p> <pre> (1714.258): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=009a8ca0 esi=09fbf698 edi=09fbf594 eip=005ae2f7 esp=09fbf4a4 ebp=09fbf594 iopl=0 nv up ei ng nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286 TestApplication!std::_Container_base::_Orphan_all+0x57: 005ae2f7 c70100000000 mov dword ptr [ecx],0 ds:0023:dddddddd=???????? </pre> <p>Call stack:</p> <pre> TestApplication!std::_Container_base::_Orphan_all+0x57 TestApplication!std::vector >::operator=+0x37 TestApplication!boost::asio::detail::win_iocp_io_service::do_one+0x189 TestApplication!boost::asio::detail::win_iocp_io_service::run+0xa2 TestApplication!boost::asio::io_service::run+0x3a </pre>
[ { "answer_id": 226659, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 3, "selected": false, "text": "0xdddddddd 0xdd" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
226,596
<p>What's the best way to initialize an array in PowerShell?</p> <p>For example, the code</p> <pre><code>$array = @() for($i=0; $i -lt 5;$i++) { $array[$i] = $FALSE } </code></pre> <p>generates the error</p> <pre><code>Array assignment failed because index '0' was out of range. At H:\Software\PowerShell\TestArray.ps1:4 char:10 + $array[$ &lt;&lt;&lt;&lt; i] = $FALSE </code></pre>
[ { "answer_id": 226600, "author": "Eric Ness", "author_id": 18891, "author_profile": "https://Stackoverflow.com/users/18891", "pm_score": 3, "selected": false, "text": "$array = new-object object[] 5 \nfor($i=0; $i -lt $array.Length;$i++)\n{\n $array[$i] = $FALSE\n}\n" }, { "answer_id": 226631, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": false, "text": "$al = New-Object System.Collections.ArrayList\nfor($i=0; $i -lt 5; $i++)\n{\n $al.Add($i)\n}\n" }, { "answer_id": 226649, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 7, "selected": true, "text": "for ($i = 0; $i -lt 5; $i++) \n{ \n $arr += @($false) \n}\n" }, { "answer_id": 226657, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 4, "selected": false, "text": "$array = @()\nfor($i=0; $i -lt 5; $i++)\n{\n $array += $i\n}\n" }, { "answer_id": 226947, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 6, "selected": false, "text": "> $a = new-object bool[] 5\n> $a\nFalse\nFalse\nFalse\nFalse\nFalse\n > $a = ($false, $false, $false, $false, $false)\n> $a\nFalse\nFalse\nFalse\nFalse\nFalse\n" }, { "answer_id": 230195, "author": "Peter Seale", "author_id": 25911, "author_profile": "https://Stackoverflow.com/users/25911", "pm_score": 4, "selected": false, "text": "$array = 1..5 | foreach { $false }\n" }, { "answer_id": 234060, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 7, "selected": false, "text": "$arr1 = @(0) * 20\n$arr2 = ,0 * 20\n" }, { "answer_id": 28015246, "author": "Celery Man", "author_id": 4467899, "author_profile": "https://Stackoverflow.com/users/4467899", "pm_score": 5, "selected": false, "text": "New-Object @(somevalue)*n n..m Add() for() ForEach-Object foreach % += (1..10)*10 -join \" \" ('one',2,3)*3 $false $false $true New-Object type[] n PS> Measure-Command -Expression {$a = new-object object[] 100000} | Format-List -Property \"Ticks\"\nTicks : 20039\n\nPS> Measure-Command -Expression {for($i=0; $i -lt $a.Length;$i++) {$a[$i] = $false}} | Format-List -Property \"Ticks\"\nTicks : 28866028\n PS> Measure-Command -Expression {$a = New-Object bool[] 100000} | Format-List -Property \"Ticks\"\nTicks : 130968\n PS> $a=@()\nPS> Measure-Command -Expression { for ($i=0; $i -lt 100000; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\n PS> $a=@()\nPS> Measure-Command -Expression { for ($i=0; $i -lt 100; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\nTicks : 147663\nPS> $a=@()\nPS> Measure-Command -Expression { for ($i=0; $i -lt 1000; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\nTicks : 2194398\n PS> Measure-Command -Expression { $a = @($false) * 100000 } | Format-List -Property \"Ticks\"\nTicks : 20131\n PS> $al = New-Object System.Collections.ArrayList\nPS> Measure-Command -Expression { for($i=0; $i -lt 1000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 447133\nPS> $al = New-Object System.Collections.ArrayList\nPS> Measure-Command -Expression { for($i=0; $i -lt 10000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 2097498\nPS> $al = New-Object System.Collections.ArrayList\nPS> Measure-Command -Expression { for($i=0; $i -lt 100000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 19866894\n Where-Object PS> Measure-Command -Expression { $a = 1..100000 } | Format-List -Property \"Ticks\"\nTicks : 239863\nMeasure-Command -Expression { $a | % {$false} } | Format-List -Property \"Ticks\"\nTicks : 102298091\n $a=$null" }, { "answer_id": 34995276, "author": "AdamL", "author_id": 1980228, "author_profile": "https://Stackoverflow.com/users/1980228", "pm_score": 4, "selected": false, "text": "$arr = [System.Array]::CreateInstance([System.Object], 5)\n$arr.GetType()\n$arr.Length\n\n$arr = [Object[]]::new(5)\n$arr.GetType()\n$arr.Length\n IsPublic IsSerial Name BaseType \n-------- -------- ---- -------- \nTrue True Object[] System.Array \n5\nTrue True Object[] System.Array \n5\n new() New-Object" }, { "answer_id": 52958445, "author": "Michael Koza", "author_id": 10548845, "author_profile": "https://Stackoverflow.com/users/10548845", "pm_score": 0, "selected": false, "text": "[bool[]]$tf=((,$False)*5)\n" }, { "answer_id": 58343378, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 1, "selected": false, "text": "$array = for($i = 0; $i -le 4; $i++) { $false }\n" }, { "answer_id": 69179109, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 0, "selected": false, "text": "$array = foreach($i in 1..5) { $false }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18891/" ]
226,599
<p>So I have xml that looks like this: </p> <pre class="lang-html prettyprint-override"><code>&lt;todo-list&gt; &lt;id type="integer"&gt;#{id}&lt;/id&gt; &lt;name&gt;#{name}&lt;/name&gt; &lt;description&gt;#{description}&lt;/description&gt; &lt;project-id type="integer"&gt;#{project_id}&lt;/project-id&gt; &lt;milestone-id type="integer"&gt;#{milestone_id}&lt;/milestone-id&gt; &lt;position type="integer"&gt;#{position}&lt;/position&gt; &lt;!-- if user can see private lists --&gt; &lt;private type="boolean"&gt;#{private}&lt;/private&gt; &lt;!-- if the account supports time tracking --&gt; &lt;tracked type="boolean"&gt;#{tracked}&lt;/tracked&gt; &lt;!-- if todo-items are included in the response --&gt; &lt;todo-items type="array"&gt; &lt;todo-item&gt; ... &lt;/todo-item&gt; &lt;todo-item&gt; ... &lt;/todo-item&gt; ... &lt;/todo-items&gt; &lt;/todo-list&gt; </code></pre> <p>How would I go about using .NET's serialization library to deserialize this into C# objects? </p> <p>Currently I'm using reflection and I map between the xml and my objects using the naming conventions.</p>
[ { "answer_id": 226614, "author": "Steve Horn", "author_id": 10589, "author_profile": "https://Stackoverflow.com/users/10589", "pm_score": 5, "selected": false, "text": "xsd.exe \"%xsdFile%\" /c /out:\"%outDirectory%\" /l:\"%language%\"\n public GeneratedClassFromXSD GetObjectFromXML()\n{\n var settings = new XmlReaderSettings();\n var obj = new GeneratedClassFromXSD();\n var reader = XmlReader.Create(urlToService, settings);\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));\n obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);\n\n reader.Close();\n return obj;\n}\n" }, { "answer_id": 226620, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "system.xml.serialization.xmlserializer" }, { "answer_id": 12556344, "author": "Keith", "author_id": 65775, "author_profile": "https://Stackoverflow.com/users/65775", "pm_score": 4, "selected": false, "text": "T function T Deserialize<T>(string serializedResults)\n{\n var serializer = new XmlSerializer(typeof(T));\n using (var stringReader = new StringReader(serializedResults))\n return (T)serializer.Deserialize(stringReader);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
226,618
<p>How can I transform a time value into YYYY-MM-DD format in Java?</p> <pre><code>long lastmodified = file.lastModified(); String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ </code></pre>
[ { "answer_id": 226638, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 6, "selected": true, "text": "Date lm = new Date(lastmodified);\nString lasmod = new SimpleDateFormat(\"yyyy-MM-dd\").format(lm);\n" }, { "answer_id": 226650, "author": "Instantsoup", "author_id": 9861, "author_profile": "https://Stackoverflow.com/users/9861", "pm_score": 2, "selected": false, "text": "String lasmod = new SimpleDateFormat(\"yyyy-MM-dd\").format(new Date(lastmodified));\n" }, { "answer_id": 226651, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "Date d = new Date(lastmodified);\nDateFormat form = new SimpleDateFormat(\"yyyy-MM-dd\");\nString lasmod = form.format(d);\n" }, { "answer_id": 226653, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 2, "selected": false, "text": "final Date modDate = new Date(lastmodified);\nfinal SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MM-dd\");\nfinal String lasmod = f.format(modDate);\n" }, { "answer_id": 226662, "author": "James Cooper", "author_id": 25198, "author_profile": "https://Stackoverflow.com/users/25198", "pm_score": 1, "selected": false, "text": "import java.text.SimpleDateFormat;\nimport java.util.Date;\n\nlong lastmodified = file.lastModified();\nSimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\nString lastmod = format.format(new Date(lastmodified));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
226,637
<p>On a page from a website (one of ours) I can enter in the url the following code:</p> <pre><code>javascript:createNewWindow('Something', 100, 100, 'Text') </code></pre> <p>Is there a way someone can exploit this?</p> <pre><code>function createNewWindow(url, widthIn, heightIn, title) { var strOptions='toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=' + widthIn + ',height=' + heightIn; var newWin = open( url,title,strOptions ); newWin.focus(); } </code></pre>
[ { "answer_id": 226882, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 1, "selected": false, "text": "javascript:createNewWindow('Something', 100, 100, 'Text')\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
226,655
<p>Website started life originally under IIS 6 and the site worked great there. Now after relocating to a new server running W2K8S, everything but mail delivery from the website now works great under IIS 7.</p> <p>Researched briefly on the Web to see if anybody had a good resolution, but no avail... Not even a glimmer of hope on Microsoft's own support site.</p> <p>Here are the steps taken so far on the new W2K8S box:</p> <ul> <li>Added the feature for SMTP under the Server Manager</li> <li>Enabled SMTP e-mail for the site itself in IIS 7 Manager to deliver e-mail to SMTP server local host, unsuccessful</li> <li>Enabled SMTP e-mail for the root site in IIS 7 Manager (not sure if that needs to be on to enable sites) to deliver e-mail to SMTP server local host, unsuccessful</li> </ul> <p>After failing those basic setups, I wanted to be sure I can actually talk from/to the serveron port 25. And I can successfully telnet from/to the server in question to a test e-mail on port 25 get a HELO, etc. So I do not believe it is a firewall config issue.</p> <p>The IIS 7 setup test was performed with both anonymous and Windows authentication - no luck either way.</p> <p>Manually checked Web Config file and it reflects correct entry for the server to use the localhost.</p> <p>Read the manual and no luck there either... :-/</p>
[ { "answer_id": 5414585, "author": "john", "author_id": 674269, "author_profile": "https://Stackoverflow.com/users/674269", "pm_score": 1, "selected": false, "text": "SmtpClient client = new SmtpClient(\"smtp.gmail.com\", 587);\nclient.DeliveryMethod = SmtpDeliveryMethod.Network;\nclient.UseDefaultCredentials = false; // use your smart host login client.Credentials = new NetworkCredential(\"xxxxx@gmail.com\", \"password\");\nclient.EnableSsl = true;\n SmtpClient client = new SmtpClient(\"your server ip\", 25);\nclient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;\nclient.EnableSsl = false; // you can't use ssl with a pickup folder\nclient.UseDefaultCredentials = true; // use windows credentials\n NETWORK_SERVICE" }, { "answer_id": 14161374, "author": "Dirk Brockhaus", "author_id": 233095, "author_profile": "https://Stackoverflow.com/users/233095", "pm_score": 1, "selected": false, "text": "<smtp deliveryMethod=\"PickupDirectoryFromIis\" />\n <smtp deliveryMethod=\"SpecifiedPickupDirectory\">\n <specifiedPickupDirectory pickupDirectoryLocation=\"C:\\inetpub\\mailroot\\Pickup\" />\n</smtp>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30432/" ]
226,663
<p>I want to use jQuery to parse RSS feeds. Can this be done with the base jQuery library out of the box or will I need to use a plugin?</p>
[ { "answer_id": 226679, "author": "Nathan Strutz", "author_id": 5918, "author_profile": "https://Stackoverflow.com/users/5918", "pm_score": 8, "selected": false, "text": "jQuery.getFeed({\n url: 'rss.xml',\n success: function(feed) {\n alert(feed.title);\n }\n});\n" }, { "answer_id": 226814, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": 4, "selected": false, "text": "function getFeed(sender, uri) {\n jQuery.getFeed({\n url: 'proxy.php?url=' + uri,\n success: function(feed) {\n jQuery(sender).append('<h2>'\n + '<a href=\"'\n + feed.link\n + '\">'\n + feed.title\n + '</a>'\n + '</h2>');\n\n var html = '';\n\n for(var i = 0; i < feed.items.length && i < 5; i++) {\n\n var item = feed.items[i];\n\n html += '<h3>'\n + '<a href=\"'\n + item.link\n + '\">'\n + item.title\n + '</a>'\n + '</h3>';\n\n html += '<div class=\"updated\">'\n + item.updated\n + '</div>';\n\n html += '<div>'\n + item.description\n + '</div>';\n }\n\n jQuery(sender).append(html);\n } \n });\n}\n\n<div id=\"getanewbrowser\">\n <script type=\"text/javascript\">\n getFeed($(\"#getanewbrowser\"), 'http://feeds.feedburner.com/getanewbrowser')\n </script>\n</div>\n" }, { "answer_id": 2345012, "author": "kabuski", "author_id": 282392, "author_profile": "https://Stackoverflow.com/users/282392", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\" src=\"./js/jquery/jquery.js\"></script>\n<script type=\"text/javascript\" src=\"./js/jFeed/build/dist/jquery.jfeed.pack.js\"></script>\n<script type=\"text/javascript\">\n function loadFeed(){\n $.getFeed({\n url: 'url=http://sports.espn.go.com/espn/rss/news/',\n success: function(feed) {\n\n //Title\n $('#result').append('<h2><a href=\"' + feed.link + '\">' + feed.title + '</a>' + '</h2>');\n\n //Unordered List\n var html = '<ul>';\n\n $(feed.items).each(function(){\n var $item = $(this);\n\n //trace( $item.attr(\"link\") );\n html += '<li>' +\n '<h3><a href =\"' + $item.attr(\"link\") + '\" target=\"_new\">' +\n $item.attr(\"title\") + '</a></h3> ' +\n '<p>' + $item.attr(\"description\") + '</p>' +\n // '<p>' + $item.attr(\"c:date\") + '</p>' +\n '</li>';\n });\n\n html += '</ul>';\n\n $('#result').append(html);\n }\n });\n }\n</script>\n" }, { "answer_id": 3012293, "author": "Alderete", "author_id": 11062, "author_profile": "https://Stackoverflow.com/users/11062", "pm_score": 2, "selected": false, "text": "<div id=\"test\"><div>\n\n<script type=\"text/javascript\">\n$(document).ready(function () {\n $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {\n limit: 5\n });\n});\n</script>\n" }, { "answer_id": 6271906, "author": "Andrew Childs", "author_id": 440094, "author_profile": "https://Stackoverflow.com/users/440094", "pm_score": 9, "selected": true, "text": "function parseRSS(url, callback) {\n $.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n}\n" }, { "answer_id": 7067582, "author": "David Hammond", "author_id": 331541, "author_profile": "https://Stackoverflow.com/users/331541", "pm_score": 7, "selected": false, "text": "$.get(rssurl, function(data) {\n var $xml = $(data);\n $xml.find(\"item\").each(function() {\n var $this = $(this),\n item = {\n title: $this.find(\"title\").text(),\n link: $this.find(\"link\").text(),\n description: $this.find(\"description\").text(),\n pubDate: $this.find(\"pubDate\").text(),\n author: $this.find(\"author\").text()\n }\n //Do something with item here...\n });\n});\n" }, { "answer_id": 7407723, "author": "Dylan Valade", "author_id": 638452, "author_profile": "https://Stackoverflow.com/users/638452", "pm_score": 3, "selected": false, "text": "<!-- Load RSS Through Google as JSON using jQuery -->\n<script type=\"text/javascript\">\n\n function displaySkiReport (feedResponse) {\n\n // Get ski report content strings\n var itemString = feedResponse.entries[0].content;\n var publishedDate = feedResponse.entries[0].publishedDate;\n\n // Clean up strings manually as needed\n itemString = itemString.replace(\"Primary: N/A\", \"Early Season Conditions\"); \n publishedDate = publishedDate.substring(0,17);\n\n // Parse ski report data from string\n var itemsArray = itemString.split(\"/\");\n\n\n //Build Unordered List\n var html = '<h2>' + feedResponse.entries[0].title + '</h2>';\n html += '<ul>';\n\n html += '<li>Skiing Status: ' + itemsArray[0] + '</li>';\n // Last 48 Hours\n html += '<li>' + itemsArray[1] + '</li>';\n // Snow condition\n html += '<li>' + itemsArray[2] + '</li>';\n // Base depth\n html += '<li>' + itemsArray[3] + '</li>';\n\n html += '<li>Ski Report Date: ' + publishedDate + '</li>';\n\n html += '</ul>';\n\n $('body').append(html); \n\n }\n\n\n function parseRSS(url, callback) {\n $.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n }\n\n $(document).ready(function() { \n\n // Ski report\n parseRSS(\"http://www.onthesnow.com/michigan/boyne-highlands/snow.rss\", displaySkiReport);\n\n });\n\n</script>\n" }, { "answer_id": 7902369, "author": "sdepold", "author_id": 568203, "author_profile": "https://Stackoverflow.com/users/568203", "pm_score": 4, "selected": false, "text": "const RSS = require('vanilla-rss');\nconst rss = new RSS(\n document.querySelector(\"#your-div\"),\n \"http://www.recruiter.com/feed/career.xml\",\n { \n // options go here\n }\n);\nrss.render().then(() => {\n console.log('Everything is loaded and rendered');\n});\n\n $(\"#your-div\").rss(\"http://www.recruiter.com/feed/career.xml\", {\n limit: 3,\n layoutTemplate: '<ul class=\"inline\">{entries}</ul>',\n entryTemplate: '<li><a href=\"{url}\">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'\n})\n <div id=\"your-div\">\n <ul class=\"inline\">\n <entries></entries>\n </ul>\n <ul class=\"inline\">\n <li><a href=\"http://www.recruiter.com/i/when-to-go-over-a-recruiter%e2%80%99s-head/\">[@Tue, 10 Sep 2013 22:23:51 -0700] When to Go Over a Recruiter's Head</a><br>Job seekers tend to have a certain \"fear\" of recruiters and hiring managers, and I mean fear in the reverence and respect ...</li>\n <li><a href=\"http://www.recruiter.com/i/the-perfect-job/\">[@Tue, 10 Sep 2013 14:52:40 -0700] The Perfect Job</a><br>Having long ago dealt with the \"perfect resume\" namely God's, in a previous article of mine, it makes sense to consider the ...</li>\n <li><a href=\"http://www.recruiter.com/i/unemployment-benefits-applications-remain-near-5-year-low-decline-again/\">[@Mon, 09 Sep 2013 12:49:17 -0700] Unemployment Benefits Applications Remain Near 5-Year Low, Decline Again</a><br>As reported by the U.S. Department of Labor, the number of workers seeking unemployment benefits continued to sit near ...</li>\n </ul>\n</div>\n" }, { "answer_id": 9328162, "author": "John Magnolia", "author_id": 560287, "author_profile": "https://Stackoverflow.com/users/560287", "pm_score": 3, "selected": false, "text": "(function(url, callback) {\n jQuery.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n})('http://news.hitb.org/rss.xml', function(feed){ // Change to desired URL\n var entries = feed.entries, feedList = '';\n for (var i = 0; i < entries.length; i++) {\n feedList +='<li><a href=\"' + entries[i].link + '\">' + entries[i].title + '</a></li>';\n }\n jQuery('.feed > ul').append(feedList);\n});\n\n\n<div class=\"feed\">\n <h4>Hacker News</h4>\n <ul></ul>\n</div>\n" }, { "answer_id": 12788982, "author": "Daniel Magnusson", "author_id": 63678, "author_profile": "https://Stackoverflow.com/users/63678", "pm_score": 0, "selected": false, "text": "<script src=\"http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n/*\n* How to load a feed via the Feeds API.\n*/\n\ngoogle.load(\"feeds\", \"1\");\n\n// Our callback function, for when a feed is loaded.\nfunction feedLoaded(result) {\n if (!result.error) {\n // Grab the container we will put the results into\n var container = document.getElementById(\"content\");\n container.innerHTML = '';\n\n // Loop through the feeds, putting the titles onto the page.\n // Check out the result object for a list of properties returned in each entry.\n // http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON\n for (var i = 0; i < result.feed.entries.length; i++) {\n var entry = result.feed.entries[i];\n var div = document.createElement(\"div\");\n div.appendChild(document.createTextNode(entry.title));\n container.appendChild(div);\n }\n }\n}\n\nfunction OnLoad() {\n // Create a feed instance that will grab Digg's feed.\n var feed = new google.feeds.Feed(\"http://www.digg.com/rss/index.xml\");\n\n // Calling load sends the request off. It requires a callback function.\n feed.load(feedLoaded);\n}\n\ngoogle.setOnLoadCallback(OnLoad);\n</script>\n" }, { "answer_id": 13771909, "author": "SpYk3HH", "author_id": 900807, "author_profile": "https://Stackoverflow.com/users/900807", "pm_score": 3, "selected": false, "text": "console (function($) {\n if (!$.jQRSS) { \n $.extend({ \n jQRSS: function(rss, options, func) {\n if (arguments.length <= 0) return false;\n\n var str, obj, fun;\n for (i=0;i<arguments.length;i++) {\n switch(typeof arguments[i]) {\n case \"string\":\n str = arguments[i];\n break;\n case \"object\":\n obj = arguments[i];\n break;\n case \"function\":\n fun = arguments[i];\n break;\n }\n }\n\n if (str == null || str == \"\") {\n if (!obj['rss']) return false;\n if (obj.rss == null || obj.rss == \"\") return false;\n }\n\n var o = $.extend(true, {}, $.jQRSS.defaults);\n\n if (typeof obj == \"object\") {\n if ($.jQRSS.methods.getObjLength(obj) > 0) {\n o = $.extend(true, o, obj);\n }\n }\n\n if (str != \"\" && !o.rss) o.rss = str;\n o.rss = escape(o.rss);\n\n var gURL = $.jQRSS.props.gURL \n + $.jQRSS.props.type \n + \"?v=\" + $.jQRSS.props.ver\n + \"&q=\" + o.rss\n + \"&callback=\" + $.jQRSS.props.callback;\n\n var ajaxData = {\n num: o.count,\n output: o.output,\n };\n\n if (o.historical) ajaxData.scoring = $.jQRSS.props.scoring;\n if (o.userip != null) ajaxData.scoring = o.userip;\n\n $.ajax({\n url: gURL,\n beforeSend: function (jqXHR, settings) { if (window['console']) { console.log(new Array(30).join('-'), \"REQUESTING RSS XML\", new Array(30).join('-')); console.log({ ajaxData: ajaxData, ajaxRequest: settings.url, jqXHR: jqXHR, settings: settings, options: o }); console.log(new Array(80).join('-')); } },\n dataType: o.output != \"xml\" ? \"json\" : \"xml\",\n data: ajaxData,\n type: \"GET\",\n xhrFields: { withCredentials: true },\n error: function (jqXHR, textStatus, errorThrown) { return new Array(\"ERROR\", { jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown } ); },\n success: function (data, textStatus, jqXHR) { \n var f = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : null : null,\n e = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed['entries'] ? data.responseData.feed.entries : null : null : null\n if (window['console']) {\n console.log(new Array(30).join('-'), \"SUCCESS\", new Array(30).join('-'));\n console.log({ data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e });\n console.log(new Array(70).join('-'));\n }\n\n if (fun) {\n return fun.call(this, data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : data.responseData : null);\n }\n else {\n return { data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e };\n }\n }\n });\n }\n });\n $.jQRSS.props = {\n callback: \"?\",\n gURL: \"http://ajax.googleapis.com/ajax/services/feed/\",\n scoring: \"h\",\n type: \"load\",\n ver: \"1.0\"\n };\n $.jQRSS.methods = {\n getObjLength: function(obj) {\n if (typeof obj != \"object\") return -1;\n var objLength = 0;\n $.each(obj, function(k, v) { objLength++; })\n return objLength;\n }\n };\n $.jQRSS.defaults = {\n count: \"10\", // max 100, -1 defaults 100\n historical: false,\n output: \"json\", // json, json_xml, xml\n rss: null, // url OR search term like \"Official Google Blog\"\n userip: null\n };\n }\n})(jQuery);\n // Param ORDER does not matter, however, you must have a link and a callback function\n// link can be passed as \"rss\" in options\n// $.jQRSS(linkORsearchString, callbackFunction, { options })\n\n$.jQRSS('someUrl.xml', function(feed) { /* do work */ })\n\n$.jQRSS(function(feed) { /* do work */ }, 'someUrl.xml', { count: 20 })\n\n$.jQRSS('someUrl.xml', function(feed) { /* do work */ }, { count: 20 })\n\n$.jQRSS({ count: 20, rss: 'someLink.xml' }, function(feed) { /* do work */ })\n {\n count: // default is 10; max is 100. Setting to -1 defaults to 100\n historical: // default is false; a value of true instructs the system to return any additional historical entries that it might have in its cache. \n output: // default is \"json\"; \"json_xml\" retuns json object with xmlString / \"xml\" returns the XML as String\n rss: // simply an alternate place to put news feed link or search terms\n userip: // as this uses Google API, I'll simply insert there comment on this:\n /* Reference: https://developers.google.com/feed/v1/jsondevguide\n This argument supplies the IP address of the end-user on \n whose behalf the request is being made. Google is less \n likely to mistake requests for abuse when they include \n userip. In choosing to utilize this parameter, please be \n sure that you're in compliance with any local laws, \n including any laws relating to disclosure of personal \n information being sent.\n */\n}\n" }, { "answer_id": 18003983, "author": "Jeromy French", "author_id": 1430996, "author_profile": "https://Stackoverflow.com/users/1430996", "pm_score": 0, "selected": false, "text": "$(\"#rss-feeds\").rss(\"http://www.recruiter.com/feed/career.xml\")\n" }, { "answer_id": 34233982, "author": "jQP", "author_id": 4149457, "author_profile": "https://Stackoverflow.com/users/4149457", "pm_score": 2, "selected": false, "text": "$('#divRss').FeedEk({\n FeedUrl:'http://jquery-plugins.net/rss'\n});\n $('#divRss').FeedEk({\n FeedUrl:'http://jquery-plugins.net/rss',\n MaxCount : 5,\n ShowDesc : true,\n ShowPubDate:true,\n DescCharacterLimit:100,\n TitleLinkTarget:'_blank',\n DateFormat: 'MM/DD/YYYY',\n DateFormatLang:'en'\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
226,664
<p>I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this: </p> <pre> <code> public class Service : System.Web.Services.WebService { [WebMethod] public string Foo(string ticket) { SessionPool.getSession(ticket); } private class SessionPool { public static Session getSession(string ticket) { // this is what i want to do, but I can't access Context return (Session)Context.Session[ticket]; } } } </code> </pre> <p>Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?</p>
[ { "answer_id": 226670, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "System.Web.HttpContext.Current\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
226,683
<p>I've got a ant <code>build.xml</code> that uses the <code>&lt;copy&gt;</code> task to copy a variety of xml files. It uses filtering to merge in properties from a <code>build.properties</code> file. Each environment (dev, stage, prod) has a different <code>build.properties</code> that stores configuration for that environment.</p> <p>Sometimes we add new properties to the Spring XML or other config files that requires updating the <code>build.properties</code> file.</p> <p>I want ant to fail fast if there are properties missing from <code>build.properties</code>. That is, if any raw <code>@...@</code> tokens make it into the generated files, I want the build to die so that the user knows they need to add one or more properties to their local build.properties.</p> <p>Is this possible with the built in tasks? I couldn't find anything in the docs. I'm about to write a custom ant task, but maybe I can spare myself the effort.</p> <p>Thanks</p>
[ { "answer_id": 226731, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<property file=\"${filter.file}\" prefix=\"filter\"> fail <exec> <exec command=\"grep \\\"@\\\" ${build.dir} | wc -l\" outputproperty=\"token.count\"/>\n<condition property=\"token.found\">\n <not>\n <equals arg1=\"${token.count}\" arg2=\"0\"/>\n </not>\n</condition>\n<fail if=\"token.found\" message=\"Found token @ in files\"/>\n" }, { "answer_id": 291371, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<exec executable=\"grep\">\n <arg line=\"@ ${build.dir}\"/>\n <redirector outputproperty=\"grep.out\"/>\n</exec>\n<exec executable=\"wc\" inputstring=\"${grep.out}\">\n <arg line=\"-l\"/>\n <redirector outputproperty=\"token.found\"/>\n</exec>\n <condition property=\"token.found\">\n <not>\n <equals arg1=\"${token.count}\" arg2=\"0\"/>\n </not>\n</condition>\n<fail if=\"token.found\" message=\"Found token @ in files\"/>\n" }, { "answer_id": 291515, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 5, "selected": true, "text": "LoadFile match <loadfile property=\"all-build-properties\" srcFile=\"build.properties\"/>\n<condition property=\"missing-properties\">\n <matches pattern=\"@[^@]*@\" string=\"${all-build-properties}\"/>\n</condition>\n<fail message=\"Some properties not set!\" if=\"missing-properties\"/>\n" }, { "answer_id": 653844, "author": "dovetalk", "author_id": 78972, "author_profile": "https://Stackoverflow.com/users/78972", "pm_score": 7, "selected": false, "text": "<fail unless=\"my.property\">Computer says no. You forgot to set 'my.property'!</fail>\n" }, { "answer_id": 19533292, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 0, "selected": false, "text": "condition fail <macrodef name=\"required-property\">\n <attribute name=\"name\"/>\n <attribute name=\"prop\" default=\"@{name}\"/>\n <attribute name=\"if\" default=\"___\"/>\n <attribute name=\"unless\" default=\"___\"/>\n <sequential>\n <fail message=\"You must set property '@{name}'\">\n <condition>\n <and>\n <not><isset property=\"@{prop}\"/></not>\n <or>\n <equals arg1=\"@{if}\" arg2=\"___\"/>\n <isset property=\"@{if}\"/>\n </or>\n <or>\n <equals arg1=\"@{unless}\" arg2=\"___\"/>\n <not><isset property=\"@{unless}\"/></not>\n </or>\n </and>\n </condition>\n </fail>\n </sequential>\n</macrodef>\n\n<target name=\"required-property.test\">\n <property name=\"prop\" value=\"\"/>\n <property name=\"cond\" value=\"set\"/>\n <required-property name=\"prop\"/>\n <required-property name=\"prop\" if=\"cond\"/>\n <required-property name=\"prop\" unless=\"cond\"/>\n <required-property name=\"prop\" if=\"cond2\"/>\n <required-property name=\"prop\" unless=\"cond2\"/>\n <required-property name=\"prop\" if=\"cond\" unless=\"cond\"/>\n <required-property name=\"prop\" if=\"cond\" unless=\"cond2\"/>\n <required-property name=\"prop\" if=\"cond2\" unless=\"cond\"/>\n <required-property name=\"prop\" if=\"cond2\" unless=\"cond2\"/>\n <required-property name=\"prop2\" unless=\"cond\"/>\n <required-property name=\"prop2\" if=\"cond2\"/>\n <required-property name=\"prop2\" if=\"cond2\" unless=\"cond\"/>\n <required-property name=\"prop2\" if=\"cond\" unless=\"cond\"/>\n <required-property name=\"prop2\" if=\"cond2\" unless=\"cond2\"/>\n <required-property name=\"success\"/>\n</target>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25198/" ]
226,689
<p>I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an <code>id</code> attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script). I can't store the references in my script because when I need them, the GreaseMonkey script itself will have gone out of scope. Is there some way to get at an "internal" ID that the browser uses, for example? A Firefox-only solution is fine; a cross-browser solution that could be applied in other scenarios would be awesome.</p> <p>Edit:</p> <ul> <li><p><strong>If the GreaseMonkey script is out of scope, how are you referencing the elements later?</strong> They GreaseMonkey script is adding events to DOM objects. I can't store the references in an array or some other similar mechanism because when the event fires, the array will be gone because the GreaseMonkey script will have gone out of scope. So the event needs some way to know about the element reference that the script had when the event was attached. And the element in question is not the one to which it is attached.</p></li> <li><p><strong>Can't you just use a custom property on the element?</strong> Yes, but the problem is on the lookup. I'd have to resort to iterating through all the elements looking for the one that has that custom property set to the desired id. That would work, sure, but in large documents it could be very time consuming. I'm looking for something where the browser can do the lookup grunt work.</p></li> <li><p><strong>Wait, can you or can you not modify the document?</strong> I can't modify the source document, but I can make DOM changes in the script. I'll clarify in the question.</p></li> <li><p><strong>Can you not use closures?</strong> Closuses did turn out to work, although I initially thought they wouldn't. See my later post.</p></li> </ul> <p>It sounds like the answer to the question: "Is there some internal browser ID I could use?" is "No."</p>
[ { "answer_id": 226715, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "if(node.id) {\n node.myId = node.id;\n} else {\n node.myId = createId();\n}\n\n// store myId\n document.getElementById()" }, { "answer_id": 226780, "author": "Michael", "author_id": 27966, "author_profile": "https://Stackoverflow.com/users/27966", "pm_score": 2, "selected": false, "text": " $(document).ready(function(){\n\n $(\"div\").attr(\"id\", function (arr) {\n return \"div-id\" + arr;\n });\n });\n" }, { "answer_id": 226804, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "myNodes = document.body.descendants()\nalert(document.body.descendants()[1].innerHTML)\n" }, { "answer_id": 226809, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 3, "selected": false, "text": ".sourceIndex document.getElementsByTagName('*')" }, { "answer_id": 226850, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "var PseudoGuid = new (function() {\n this.empty = \"00000000-0000-0000-0000-000000000000\";\n this.GetNew = function() {\n var fourChars = function() {\n return (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1).toUpperCase();\n }\n return (fourChars() + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + fourChars() + fourChars());\n };\n})();\n\n// usage example:\nvar tempId = PseudoGuid.GetNew();\nsomeDomElement.id = tempId;\n myDomElement; // some DOM element we want later reference to\n\nsomeOtherDomElement.addEventListener(\"click\", function(e) {\n // because of the closure, here we have a reference to myDomElement\n doSomething(myDomElement);\n}, false);\n myDomElement" }, { "answer_id": 226912, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 2, "selected": false, "text": "//(function () {\n\n var idCounter = new Date().getTime();\n function getId( node ) {\n return (node.id) ? node.id : (node.id = 'tempIdPrefix_' + idCounter++ );\n }\n\n//})();\n var n = document.getElementById('someid');\ngetId(n); // returns \"someid\"\n\nvar n = document.getElementsByTagName('div')[1];\ngetId(n); // returns \"tempIdPrefix_1224697942198\"\n" }, { "answer_id": 227199, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "var saved_element = findThatDOMNode();\n\ndocument.body.onclick = function() \n{\n alert(saved_element); // it's still there!\n}\n [@id=foo]/div[4]/p[2]/a" }, { "answer_id": 230114, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 4, "selected": true, "text": "for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var button = document.createElement(\"button\");\n button.addEventListener(\"click\", function(ev) {\n // do something with element here\n }, false)\n}\n var buildListener = function(element) {\n return function(ev) {\n // do something with event here\n };\n};\n\nfor (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var button = document.createElement(\"button\");\n button.addEventListener(\"click\", buildListener(element), false)\n}\n" }, { "answer_id": 232323, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 0, "selected": false, "text": " pguid = b9j.pguid.next() // A unique id (suitable for a DOM element)\n // is generated\n // Something like \"b9j-pguid-20a9ff-0\"\n ...\n pguid = b9j.pguid.next() // Another unique one... \"b9j-pguid-20a9ff-1\"\n\n // Build a custom generator\n var sequence = new b9j.pguid.Sequence({ namespace: \"frobozz\" })\n pguid = sequence.next() \"frobozz-c861e1-0\"\n" }, { "answer_id": 44069221, "author": "wybe", "author_id": 2204864, "author_profile": "https://Stackoverflow.com/users/2204864", "pm_score": 2, "selected": false, "text": "function getUniqueKeyForNode (targetNode) {\n const pieces = ['doc'];\n let node = targetNode;\n\n while (node && node.parentNode) {\n pieces.push(Array.prototype.indexOf.call(node.parentNode.childNodes, node));\n node = node.parentNode\n }\n\n return pieces.reverse().join('/');\n}\n doc/0 doc/0/0 doc/0/1 doc/0/1/0 doc/0/1/1 <div>\n <div />\n <div>\n <div />\n <div />\n </div>\n</div>\n while break node @id reverse() pieces piece doc" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
226,691
<p>I have a requirement to export the results of a SQL query to excel. I am currently exporting it into 2007 format, but everything I have found will only run in a x86 enviroment. The web site where the export is to take place is running on a x64 version of IIS.</p> <p>Changing IIS to run x86 is not an option. My current solution is to save the export request to a DB, and write a windows service that can run in x86 and use that service to process the request.</p> <p>I have started to look at the Open XML Format SDK 2.0 as a possible better solution. </p> <p>Has anyone got any experence that would lend to a native .NET solution.</p> <p>FYI: My budget is $0.00 so buying a tool is a no-go.</p>
[ { "answer_id": 226802, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<html><body>\n<table>\n<tr><td>First column</td><td>Second column</td></tr>\n<tr><td>Value of first row in first column</td><td>Value of first row in second column</td></tr>\n<tr><td>Value of second row in first column</td><td>Value of secondrow in second column</td></tr>\n</table>\n</body></html>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
226,693
<p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p> <p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p> <p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
[ { "answer_id": 226803, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 3, "selected": false, "text": "__getitem__ __setitem__" }, { "answer_id": 228333, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 3, "selected": false, "text": "self.lengths = {}\n import shelve\nself.lengths = shelve.open('lengths.shelf')\n self.lengths[indx]\n self.lengths[str(indx)]\n" }, { "answer_id": 228837, "author": "Matthew Trevor", "author_id": 11265, "author_profile": "https://Stackoverflow.com/users/11265", "pm_score": 6, "selected": false, "text": "from shove import Shove\n\nmem_store = Shove()\nfile_store = Shove('file://mystore')\n\nfile_store['key'] = value\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
226,701
<p>QA tester was reading HTML/JS code to write a functional test of a web form, and saw:</p> <pre><code>if (form_field == empty) { ...do stuff for empty field } else if (form_field != empty) { ...do stuff for non-empty field } else { ...do stuff that will never be done } </code></pre> <p>After a couple embarrassing attempts, tester realized that they couldn't trigger the alert strings hidden in the third block.</p> <p>Things I'm wondering are if this Is this problem more or less language specific (can non-JS people learn lessons here?) and are there legitimate reasons code ended up this way?</p> <p>How can I find/address the problem?</p>
[ { "answer_id": 226732, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "if (a)\n //1\nelse if (!a)\n //2\nelse\n //3\n if (a)\n //1\nelse\n //2\n" }, { "answer_id": 226740, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 3, "selected": false, "text": "declare @test as int\n\nset @test = null\n\nif @test = 1 \n print 1\nelse if not @test = 1\n print 2\nelse \n print 3\n" }, { "answer_id": 226751, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 3, "selected": true, "text": "if(x)\n{\n //do something\n}\nelse if(!x)\n{\n //do something else\n}\nelse\n{\n //never, ever, do anything\n}\n Are there legitimate reasons code ended up this way?\n" }, { "answer_id": 226774, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 2, "selected": false, "text": "BOOL result = SomeWindowsAPI();\nif (result == TRUE)\n{\n // success\n}\nelse if (result == FALSE)\n{\n // failure\n}\nelse\n{\n // wtf?\n}\n" }, { "answer_id": 226797, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 1, "selected": false, "text": " turn = 1;\n while( flag[1] && turn == 1 );\n" }, { "answer_id": 1593575, "author": "Asher", "author_id": 156470, "author_profile": "https://Stackoverflow.com/users/156470", "pm_score": 0, "selected": false, "text": "if (A = TRUE) .. else if (A == FALSE) .. else .. cmp al,$01\njnz +$0c\n...\ntest al,al\njnz +$0c\n...\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2910/" ]
226,703
<p>I want to pause input in a shell script, and prompt the user for choices.<br> The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br> How do I accomplish this in a typical bash prompt?</p>
[ { "answer_id": 226720, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 8, "selected": false, "text": "echo \"Please enter some input: \"\nread input_variable\necho \"You entered: $input_variable\"\n" }, { "answer_id": 226722, "author": "SumoRunner", "author_id": 18975, "author_profile": "https://Stackoverflow.com/users/18975", "pm_score": 6, "selected": false, "text": "inquire () {\n echo -n \"$1 [y/n]? \"\n read answer\n finish=\"-1\"\n while [ \"$finish\" = '-1' ]\n do\n finish=\"1\"\n if [ \"$answer\" = '' ];\n then\n answer=\"\"\n else\n case $answer in\n y | Y | yes | YES ) answer=\"y\";;\n n | N | no | NO ) answer=\"n\";;\n *) finish=\"-1\";\n echo -n 'Invalid response -- please reenter:';\n read answer;;\n esac\n fi\n done\n}\n\n... other stuff\n\ninquire \"Install now?\"\n\n...\n" }, { "answer_id": 226724, "author": "Myrddin Emrys", "author_id": 9084, "author_profile": "https://Stackoverflow.com/users/9084", "pm_score": 12, "selected": true, "text": "read while true; do\n read -p \"Do you wish to install this program? \" yn\n case $yn in\n [Yy]* ) make install; break;;\n [Nn]* ) exit;;\n * ) echo \"Please answer yes or no.\";;\n esac\ndone\n select select echo \"Do you wish to install this program?\"\nselect yn in \"Yes\" \"No\"; do\n case $yn in\n Yes ) make install; break;;\n No ) exit;;\n esac\ndone\n select while true set -- $(locale LC_MESSAGES)\nyesexpr=\"$1\"; noexpr=\"$2\"; yesword=\"$3\"; noword=\"$4\"\n\nwhile true; do\n read -p \"Install (${yesword} / ${noword})? \" yn\n if [[ \"$yn\" =~ $yesexpr ]]; then make install; exit; fi\n if [[ \"$yn\" =~ $noexpr ]]; then exit; fi\n echo \"Answer ${yesword} / ${noword}.\"\ndone\n" }, { "answer_id": 226946, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 7, "selected": false, "text": "select result in Yes No Cancel\ndo\n echo $result\ndone\n" }, { "answer_id": 4886643, "author": "serg", "author_id": 601562, "author_profile": "https://Stackoverflow.com/users/601562", "pm_score": 6, "selected": false, "text": "read -p \"Are you alright? (y/n) \" RESP\nif [ \"$RESP\" = \"y\" ]; then\n echo \"Glad to hear it\"\nelse\n echo \"You need more bash programming\"\nfi\n" }, { "answer_id": 5987314, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 7, "selected": false, "text": "-p -i read -e -p \"Enter the path to the file: \" -i \"/usr/local/etc/\" FILEPATH\necho $FILEPATH\n -e read -e -p \"\nList the content of your home dir ? [Y/n] \" YN\n\n[[ $YN == \"y\" || $YN == \"Y\" || $YN == \"\" ]] && ls -la ~/\n" }, { "answer_id": 10508165, "author": "ThatLinuxGuy", "author_id": 1383344, "author_profile": "https://Stackoverflow.com/users/1383344", "pm_score": 5, "selected": false, "text": "read echo Would you like to install? \"(Y or N)\"\n\nread x\n\n# now check if $x is \"y\"\nif [ \"$x\" = \"y\" ]; then\n # do something here!\nfi\n" }, { "answer_id": 12202793, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 5, "selected": false, "text": "#!/bin/sh\n\npromptyn () {\n while true; do\n read -p \"$1 \" yn\n case $yn in\n [Yy]* ) return 0;;\n [Nn]* ) return 1;;\n * ) echo \"Please answer yes or no.\";;\n esac\n done\n}\n\nif promptyn \"is the sky blue?\"; then\n echo \"yes\"\nelse\n echo \"no\"\nfi\n" }, { "answer_id": 18968774, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 2, "selected": false, "text": "yn() {\n if [[ 'y' == `read -s -n 1 -p \"[y/n]: \" Y; echo $Y` ]];\n then eval $1;\n else eval $2;\n fi }\nyn 'echo yes' 'echo no'\nyn 'echo absent no function works too!'\n" }, { "answer_id": 19995350, "author": "Dennis", "author_id": 72321, "author_profile": "https://Stackoverflow.com/users/72321", "pm_score": 4, "selected": false, "text": "read -p \"Are you sure? (y/n) \" -n 1\necho\nif [[ $REPLY =~ ^[Yy]$ ]]; then\n do_something \nfi\n" }, { "answer_id": 20817520, "author": "Ernest A", "author_id": 1278855, "author_profile": "https://Stackoverflow.com/users/1278855", "pm_score": 3, "selected": false, "text": "ask () { # $1=question $2=options\n # set REPLY\n # options: x=..|y=..\n while $(true); do\n printf '%s [%s] ' \"$1\" \"$2\"\n stty cbreak\n REPLY=$(dd if=/dev/tty bs=1 count=1 2> /dev/null)\n stty -cbreak\n test \"$REPLY\" != \"$(printf '\\n')\" && printf '\\n'\n (\n IFS='|'\n for o in $2; do\n if [ \"$REPLY\" = \"${o%%=*}\" ]; then\n printf '\\n'\n break\n fi\n done\n ) | grep ^ > /dev/null && return\n done\n}\n $ ask 'continue?' 'y=yes|n=no|m=maybe'\ncontinue? [y=yes|n=no|m=maybe] g\ncontinue? [y=yes|n=no|m=maybe] k\ncontinue? [y=yes|n=no|m=maybe] y\n$\n REPLY y" }, { "answer_id": 22893526, "author": "Thorsten Staerk", "author_id": 236872, "author_profile": "https://Stackoverflow.com/users/236872", "pm_score": 4, "selected": false, "text": "#!/bin/bash\nif (dialog --title \"Message\" --yesno \"Want to do something risky?\" 6 25)\n# message box will have the size 25x6 characters\nthen \n echo \"Let's do something risky\"\n # do something risky\nelse \n echo \"Let's stay boring\"\nfi\n" }, { "answer_id": 23781791, "author": "user9869932", "author_id": 1183098, "author_profile": "https://Stackoverflow.com/users/1183098", "pm_score": 4, "selected": false, "text": "curl -Ss https://example.com/installer.sh | sh\n read -r yn </dev/tty printf \"These files will be uploaded. Is this ok? (y/N) \"\nread -r yn </dev/tty\n\nif [ \"$yn\" = \"y\" ]; then\n \n # Yes\nelse\n \n # No\nfi\n" }, { "answer_id": 27831208, "author": "Miguel", "author_id": 674405, "author_profile": "https://Stackoverflow.com/users/674405", "pm_score": 3, "selected": false, "text": "uniprompt(){\n while true; do\n echo -e \"$1\\c\"\n read opt\n array=($2)\n case \"${array[@]}\" in *\"$opt\"*) eval \"$3=$opt\";return 0;; esac\n echo -e \"$opt is not a correct value\\n\"\n done\n}\n unipromtp \"Select an option: (a)-Do one (x)->Do two (f)->Do three : \" \"a x f\" selection\necho \"$selection\"\n" }, { "answer_id": 27875395, "author": "F. Hauri - Give Up GitHub", "author_id": 1765658, "author_profile": "https://Stackoverflow.com/users/1765658", "pm_score": 9, "selected": false, "text": "read if ... then ... else printf 'Is this a good question (y/n)? '\nread answer\n # if echo \"$answer\" | grep -iq \"^y\" ;then\n if [ \"$answer\" != \"${answer#[Yy]}\" ] ;then # this grammar (the #[] operator) means that the variable $answer where any Y or y in 1st position will be dropped if they exist.\n echo Yes\nelse\n echo No\nfi\n printf 'Is this a good question (y/n)? '\nold_stty_cfg=$(stty -g)\nstty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with stty\nif echo \"$answer\" | grep -iq \"^y\" ;then\n echo Yes\nelse\n echo No\nfi\n #/bin/sh\nprintf 'Is this a good question (y/n)? '\nold_stty_cfg=$(stty -g)\nstty raw -echo\nanswer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )\nstty $old_stty_cfg\nif echo \"$answer\" | grep -iq \"^y\" ;then\n echo Yes\nelse\n echo No\nfi\n libncurses libgtk libqt whiptail if whiptail --yesno \"Is this a good question\" 20 60 ;then\n echo Yes\nelse\n echo No\nfi\n whiptail dialog --yesno \"Is this a good question\" 20 60 && echo Yes\n\ngdialog --yesno \"Is this a good question\" 20 60 && echo Yes\n\nkdialog --yesno \"Is this a good question\" 20 60 && echo Yes\n 20 60 DIALOG=whiptail\nif [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fi\nif [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi\n...\n$DIALOG --yesno ...\n read -p \"Is this a good question (y/n)? \" answer\ncase ${answer:0:1} in\n y|Y )\n echo Yes\n ;;\n * )\n echo No\n ;;\nesac\n case yes | ja | si | oui read read -n 1 -p \"Is this a good question (y/n)? \" answer\n read read -t 3 -n 1 -p \"Is this a good question (y/n)? \" answer\n[ -z \"$answer\" ] && answer=\"Yes\" # if 'yes' have to be default choice\n yes - no dialog --menu \"Is this a good question\" 20 60 12 y Yes n No m Maybe\n dialog --gauge \"Filling the tank\" 20 60 0 < <(\n for i in {1..100};do\n printf \"XXX\\n%d\\n%(%a %b %T)T progress: %d\\nXXX\\n\" $i -1 $i\n sleep .033\n done\n) \n #!/bin/sh\nwhile true ;do\n [ -x \"$(which ${DIALOG%% *})\" ] || DIALOG=dialog\n DIALOG=$($DIALOG --menu \"Which tool for next run?\" 20 60 12 2>&1 \\\n whiptail \"dialog boxes from shell scripts\" >/dev/tty \\\n dialog \"dialog boxes from shell with ncurses\" \\\n gdialog \"dialog boxes from shell with Gtk\" \\\n kdialog \"dialog boxes from shell with Kde\" ) || exit\n clear;echo \"Choosed: $DIALOG.\"\n for i in `seq 1 100`;do\n date +\"`printf \"XXX\\n%d\\n%%a %%b %%T progress: %d\\nXXX\\n\" $i $i`\"\n sleep .0125\n done | $DIALOG --gauge \"Filling the tank\" 20 60 0\n $DIALOG --infobox \"This is a simple info box\\n\\nNo action required\" 20 60\n sleep 3\n if $DIALOG --yesno \"Do you like this demo?\" 20 60 ;then\n AnsYesNo=Yes; else AnsYesNo=No; fi\n AnsInput=$($DIALOG --inputbox \"A text:\" 20 60 \"Text here...\" 2>&1 >/dev/tty)\n AnsPass=$($DIALOG --passwordbox \"A secret:\" 20 60 \"First...\" 2>&1 >/dev/tty)\n $DIALOG --textbox /etc/motd 20 60\n AnsCkLst=$($DIALOG --checklist \"Check some...\" 20 60 12 \\\n Correct \"This demo is useful\" off \\\n Fun \"This demo is nice\" off \\\n Strong \"This demo is complex\" on 2>&1 >/dev/tty)\n AnsRadio=$($DIALOG --radiolist \"I will:\" 20 60 12 \\\n \" -1\" \"Downgrade this answer\" off \\\n \" 0\" \"Not do anything\" on \\\n \" +1\" \"Upgrade this anser\" off 2>&1 >/dev/tty)\n out=\"Your answers:\\nLike: $AnsYesNo\\nInput: $AnsInput\\nSecret: $AnsPass\"\n $DIALOG --msgbox \"$out\\nAttribs: $AnsCkLst\\nNote: $AnsRadio\" 20 60\n done\n #!/bin/bash\n\nset -i\nHISTFILE=~/.myscript.history\nhistory -c\nhistory -r\n\nmyread() {\n read -e -p '> ' $1\n history -s ${!1}\n}\ntrap 'history -a;exit' 0 1 2 3 6\n\nwhile myread line;do\n case ${line%% *} in\n exit ) break ;;\n * ) echo \"Doing something with '$line'\" ;;\n esac\n done\n .myscript.history $HOME" }, { "answer_id": 29523713, "author": "Joshua Goldberg", "author_id": 411282, "author_profile": "https://Stackoverflow.com/users/411282", "pm_score": 2, "selected": false, "text": "xargs -p parallel --interactive echo *.xml | xargs -p -n 1 -J {} mv {} backup/\n" }, { "answer_id": 29724498, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 4, "selected": false, "text": "read -e -p \"Enter your choice: \" choice\n -e read -e -i \"yes\" -p \"Enter your choice: \" choice\n -i" }, { "answer_id": 30652018, "author": "ccDict", "author_id": 1158046, "author_profile": "https://Stackoverflow.com/users/1158046", "pm_score": 2, "selected": false, "text": "while [ -z $prompt ]; do read -p \"Continue (y/n)?\" choice;case \"$choice\" in y|Y ) prompt=true; break;; n|N ) exit 0;; esac; done; prompt=;\n while [ -z $prompt ];\n do read -p \"Continue (y/n)?\" choice;\n case \"$choice\" in\n y|Y ) prompt=true; break;;\n n|N ) exit 0;;\n esac;\ndone;\nprompt=;\n" }, { "answer_id": 31699418, "author": "Alexander Löfqvist", "author_id": 4888007, "author_profile": "https://Stackoverflow.com/users/4888007", "pm_score": 2, "selected": false, "text": "function menu(){\n title=\"Question time\"\n prompt=\"Select:\"\n options=(\"Yes\" \"No\" \"Maybe\")\n echo \"$title\"\n PS3=\"$prompt\"\n select opt in \"${options[@]}\" \"Quit/Cancel\"; do\n case \"$REPLY\" in\n 1 ) echo \"You picked $opt which is option $REPLY\";;\n 2 ) echo \"You picked $opt which is option $REPLY\";;\n 3 ) echo \"You picked $opt which is option $REPLY\";;\n $(( ${#options[@]}+1 )) ) clear; echo \"Goodbye!\"; exit;;\n *) echo \"Invalid option. Try another one.\";continue;;\n esac\n done\n return\n}\n" }, { "answer_id": 34354784, "author": "oHo", "author_id": 938111, "author_profile": "https://Stackoverflow.com/users/938111", "pm_score": 5, "selected": false, "text": "do_xxxx=y # In batch mode => Default is Yes\n[[ -t 0 ]] && # If TTY => Prompt the question\nread -n 1 -p $'\\e[1;32m\nDo xxxx? (Y/n)\\e[0m ' do_xxxx # Store the answer in $do_xxxx\nif [[ $do_xxxx =~ ^(y|Y|)$ ]] # Do if 'y' or 'Y' or empty\nthen\n xxxx\nfi\n [[ -t 0 ]] && read ... read read -n 1 $'\\e[1;32m ... \\e[0m ' [[ $do_xxxx =~ ^(y|Y|)$ ]] do_xxxx=y\n[[ -t 0 ]] && { # Timeout 5 seconds (read -t 5)\nread -t 5 -n 1 -p $'\\e[1;32m\nDo xxxx? (Y/n)\\e[0m ' do_xxxx || # read 'fails' on timeout\ndo_xxxx=n ; } # Timeout => answer No\nif [[ $do_xxxx =~ ^(y|Y|)$ ]]\nthen\n xxxx\nfi\n" }, { "answer_id": 35783292, "author": "Apurv Nerlekar", "author_id": 1266952, "author_profile": "https://Stackoverflow.com/users/1266952", "pm_score": 5, "selected": false, "text": "read -p \"<Your Friendly Message here> : y/n/cancel\" CONDITION;\n\nif [ \"$CONDITION\" == \"y\" ]; then\n # do something here!\nfi\n if" }, { "answer_id": 40483453, "author": "oOpSgEo", "author_id": 2875443, "author_profile": "https://Stackoverflow.com/users/2875443", "pm_score": 2, "selected": false, "text": "case while case break case while case #! /bin/sh \n\n# For potential users of BSD, or other systems who do not\n# have a bash binary located in /bin the script will be directed to\n# a bourne-shell, e.g. /bin/sh\n\n# NOTE: It would seem best for handling user entry errors or\n# exceptions, to put the decision required by the input \n# of the prompt in a case statement (case control structure), \n\necho Would you like us to perform the option: \"(Y|N)\"\n\nread inPut\n\ncase $inPut in\n # echoing a command encapsulated by \n # backticks (``) executes the command\n \"Y\") echo `Do something crazy`\n ;;\n # depending on the scenario, execute the other option\n # or leave as default\n \"N\") echo `execute another option`\n ;;\nesac\n\nexit\n" }, { "answer_id": 41034251, "author": "Yokai", "author_id": 5443139, "author_profile": "https://Stackoverflow.com/users/5443139", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n\nfunction ask_user() { \n\necho -e \"\n#~~~~~~~~~~~~#\n| 1.) Yes |\n| 2.) No |\n| 3.) Quit |\n#~~~~~~~~~~~~#\\n\"\n\nread -e -p \"Select 1: \" choice\n\nif [ \"$choice\" == \"1\" ]; then\n\n do_something\n\nelif [ \"$choice\" == \"2\" ]; then\n\n do_something_else\n\nelif [ \"$choice\" == \"3\" ]; then\n\n clear && exit 0\n\nelse\n\n echo \"Please select 1, 2, or 3.\" && sleep 3\n clear && ask_user\n\nfi\n}\n\nask_user\n" }, { "answer_id": 45110946, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env bash\n@confirm() {\n local message=\"$*\"\n local result=''\n\n echo -n \"> $message (Yes/No/Cancel) \" >&2\n\n while [ -z \"$result\" ] ; do\n read -s -n 1 choice\n case \"$choice\" in\n y|Y ) result='Y' ;;\n n|N ) result='N' ;;\n c|C ) result='C' ;;\n esac\n done\n\n echo $result\n}\n case $(@confirm 'Confirm?') in\n Y ) echo \"Yes\" ;;\n N ) echo \"No\" ;;\n C ) echo \"Cancel\" ;;\nesac\n #!/usr/bin/env bash\n@confirm() {\n local message=\"$*\"\n local result=3\n\n echo -n \"> $message (y/n) \" >&2\n\n while [[ $result -gt 1 ]] ; do\n read -s -n 1 choice\n case \"$choice\" in\n y|Y ) result=0 ;;\n n|N ) result=1 ;;\n esac\n done\n\n return $result\n}\n if @confirm 'Confirm?' ; then\n echo \"Yes\"\nelse\n echo \"No\"\nfi\n" }, { "answer_id": 50431319, "author": "Mike Q", "author_id": 1618630, "author_profile": "https://Stackoverflow.com/users/1618630", "pm_score": 2, "selected": false, "text": "ans=''\nwhile true; do\n read -p \"So is MikeQ the greatest or what (y/n/q) ?\" -n1 ans\n case ${ans,,} in\n y|n|q) break;;\n *) echo \"Answer y for yes / n for no or q for quit.\";;\n esac\ndone\n\necho -e \"\\nAnswer = $ans\"\n\nif [[ \"${ans,,}\" == \"q\" ]] ; then\n echo \"OK Quitting, we will assume that he is\"\n exit 0\nfi\n\nif [[ \"${ans,,}\" == \"y\" ]] ; then\n echo \"MikeQ is the greatest!!\"\nelse\n echo \"No? MikeQ is not the greatest?\"\nfi\n" }, { "answer_id": 51078339, "author": "Tom Hale", "author_id": 5353461, "author_profile": "https://Stackoverflow.com/users/5353461", "pm_score": 4, "selected": false, "text": "0 1 zsh bash N $ confirm \"Show dangerous command\" && echo \"rm *\"\nShow dangerous command [y/N]?\n [y/N]? $ confirm \"Show dangerous command\" && echo \"rm *\"\nShow dangerous command [y/N]? X\nShow dangerous command [y/N]? y\nrm *\n Y $ confirm_yes \"Show dangerous command\" && echo \"rm *\"\nShow dangerous command [Y/n]?\nrm *\n y n $ get_yes_keypress \"Here you cannot press enter. Do you like this [y/n]? \"\nHere you cannot press enter. Do you like this [y/n]? k\nHere you cannot press enter. Do you like this [y/n]?\nHere you cannot press enter. Do you like this [y/n]? n\n$ echo $?\n1\n 1 [y/n]? # Read a single char from /dev/tty, prompting with \"$*\"\n# Note: pressing enter will return a null string. Perhaps a version terminated with X and then remove it in caller?\n# See https://unix.stackexchange.com/a/367880/143394 for dealing with multi-byte, etc.\nfunction get_keypress {\n local REPLY IFS=\n >/dev/tty printf '%s' \"$*\"\n [[ $ZSH_VERSION ]] && read -rk1 # Use -u0 to read from STDIN\n # See https://unix.stackexchange.com/q/383197/143394 regarding '\\n' -> ''\n [[ $BASH_VERSION ]] && </dev/tty read -rn1\n printf '%s' \"$REPLY\"\n}\n\n# Get a y/n from the user, return yes=0, no=1 enter=$2\n# Prompt using $1.\n# If set, return $2 on pressing enter, useful for cancel or defualting\nfunction get_yes_keypress {\n local prompt=\"${1:-Are you sure [y/n]? }\"\n local enter_return=$2\n local REPLY\n # [[ ! $prompt ]] && prompt=\"[y/n]? \"\n while REPLY=$(get_keypress \"$prompt\"); do\n [[ $REPLY ]] && printf '\\n' # $REPLY blank if user presses enter\n case \"$REPLY\" in\n Y|y) return 0;;\n N|n) return 1;;\n '') [[ $enter_return ]] && return \"$enter_return\"\n esac\n done\n}\n\n# Credit: http://unix.stackexchange.com/a/14444/143394\n# Prompt to confirm, defaulting to NO on <enter>\n# Usage: confirm \"Dangerous. Are you sure?\" && rm *\nfunction confirm {\n local prompt=\"${*:-Are you sure} [y/N]? \"\n get_yes_keypress \"$prompt\" 1\n} \n\n# Prompt to confirm, defaulting to YES on <enter>\nfunction confirm_yes {\n local prompt=\"${*:-Are you sure} [Y/n]? \"\n get_yes_keypress \"$prompt\" 0\n}\n" }, { "answer_id": 53746668, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 4, "selected": false, "text": "REPLY read ja si oui read -rp \"Do you want a demo? [y/n/c] \"\n\n[[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo \"Selected Cancel\"; exit 1; }\n\nif [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then\n echo \"Positive\"\nfi\n" }, { "answer_id": 57739142, "author": "Léa Gris", "author_id": 7939871, "author_profile": "https://Stackoverflow.com/users/7939871", "pm_score": 4, "selected": false, "text": "LC_MESSAGES #!/usr/bin/env sh\n\n# Getting LC_MESSAGES values into variables\n# shellcheck disable=SC2046 # Intended IFS splitting\nIFS='\n' set -- $(locale LC_MESSAGES)\n\nyesexpr=\"$1\"\nnoexpr=\"$2\"\nyesstr=\"$3\"\nnostr=\"$4\"\nmessages_codeset=\"$5\" # unused here, but kept as documentation\n\n# Display Yes / No ? prompt into locale\necho \"$yesstr / $nostr ?\"\n\n# Read answer\nread -r yn\n\n# Test answer\ncase \"$yn\" in\n# match only work with the character class from the expression\n ${yesexpr##^}) echo \"answer $yesstr\" ;;\n ${noexpr##^}) echo \"answer $nostr\" ;;\nesac\n yesstr nostr YESSTR NOSTR yesexpr noexpr YESEXPR NOEXPR #!/usr/bin/env bash\n\nIFS=$'\\n' read -r -d '' yesexpr noexpr _ < <(locale LC_MESSAGES)\n\nprintf -v yes_or_no_regex \"(%s)|(%s)\" \"$yesexpr\" \"$noexpr\"\n\nprintf -v prompt $\"Please answer Yes (%s) or No (%s): \" \"$yesexpr\" \"$noexpr\"\n\ndeclare -- answer=;\n\nuntil [[ \"$answer\" =~ $yes_or_no_regex ]]; do\n read -rp \"$prompt\" answer\ndone\n\nif [[ -n \"${BASH_REMATCH[1]}\" ]]; then\n echo $\"You answered: Yes\"\nelse\n echo $\"No, was your answer.\"\nfi\n bash --dump-po-strings scriptname #: scriptname:8\nmsgid \"Please answer Yes (%s) or No (%s): \"\nmsgstr \"\"\n#: scriptname:17\nmsgid \"You answered: Yes\"\nmsgstr \"\"\n#: scriptname:19\nmsgid \"No, was your answer.\"\nmsgstr \"\"\n" }, { "answer_id": 61070975, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": 2, "selected": false, "text": "while true; do\n read -p \"Continue [Y/n]? \" -n 1 -r -e yn\n case \"${yn:-Y}\" in\n [YyZzOoJj]* ) echo; break ;;\n [Nn]* ) [[ \"$0\" = \"$BASH_SOURCE\" ]] && exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell\n * ) echo \"Please answer yes or no.\";;\n esac\ndone\necho \"and off we go!\"\n" }, { "answer_id": 65118202, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": 2, "selected": false, "text": "read -p \"press enter ...\" y\n Hit any key to continue #!/bin/sh\necho Backup this project\nread -p \"press enter ...\" y\nrsync -tavz . /media/hard_to_remember_path/backup/projects/yourproject/\n" }, { "answer_id": 66420668, "author": "Samir Kape", "author_id": 8312897, "author_profile": "https://Stackoverflow.com/users/8312897", "pm_score": 3, "selected": false, "text": "read -p \"Continue? (y/n): \" confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1\n" }, { "answer_id": 69495671, "author": "ish-west", "author_id": 5272636, "author_profile": "https://Stackoverflow.com/users/5272636", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\nif ! getans.sh 'Shall we proceed?' y ; then\n echo \"User said “NO”\"\n exit 1\nfi\n\necho \"User said “YES”\"\n# do something usefull\nexit 0\n" }, { "answer_id": 69672795, "author": "Ctrl-C", "author_id": 731634, "author_profile": "https://Stackoverflow.com/users/731634", "pm_score": 3, "selected": false, "text": "read -p \"Continue? [Enter] → Yes, [Ctrl]+[C] → No.\"\n" }, { "answer_id": 71503750, "author": "Diego Torres Milano", "author_id": 236465, "author_profile": "https://Stackoverflow.com/users/236465", "pm_score": 1, "selected": false, "text": "python python3 -c 'import PyInquirer; print(PyInquirer.prompt([{\"type\":\"confirm\", \"message\":\"Do you want to continue?\", \"name\":\"r\"}]).get(\"r\"))'\n" }, { "answer_id": 72237677, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 1, "selected": false, "text": "confirm() {\n local ans IFS=;\n while read -rp \"$1\" -n1 ans;\n do printf '\\n';\n case $ans in [Yy]) return 0;;\n [Nn]) return 1;;\n esac;\n done;\n}; ## Usage: if confirm \"Are you sure? \"; then ...\n\nif confirm \"Does everything look ok...reboot now? [Y/n]\"; then\n echo \"rebooting...\"\n sleep 5\n reboot\nfi\n" }, { "answer_id": 72692403, "author": "Erik Pukinskis", "author_id": 778946, "author_profile": "https://Stackoverflow.com/users/778946", "pm_score": 3, "selected": false, "text": "read -n1 -p \"Continue? (Y/n) \" confirm\n\nif ! echo $confirm | grep '^[Yy]\\?$'; then\n exit 1\nfi\n ! if else" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084/" ]
226,717
<p>When you are monitoring the TFS build from Visual Studio (2008 or 2005), you can see where it is up to.</p> <p>The issue is that I have some Post-Build custom steps I would like the developer to be able to see directly throught the UI. Those steps take some times and we can also get a "timing" of the build step.</p> <p>Any idea how to have it displayed?</p>
[ { "answer_id": 227063, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 4, "selected": true, "text": " <Target Name=\"PackageBinaries\">\n\n <!-- create the build step -->\n <BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Message=\"Creating Installer\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" >\n <Output TaskParameter=\"Id\"\n PropertyName=\"InstallerStepId\" />\n </BuildStep>\n\n <!-- Create the MSI file using WiX -->\n <MSBuild Projects=\"$(SolutionRoot)\\SetupProject\\wallboard.wixproj\"\n Properties=\"BinariesSource=$(OutDir);PublishDir=$(BinariesRoot);Configuration=%(ConfigurationToBuild.FlavourToBuild)\" >\n </MSBuild>\n\n <!-- If we sucessfully built the installer, tell TFS -->\n <BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(InstallerStepId)\"\n Status=\"Succeeded\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" />\n\n <!-- Note that the condition above means that we do not talk to TFS when doing a Desktop Build -->\n\n <!-- If we error during this step, then tell TFS we failed-->\n <OnError ExecuteTargets=\"MarkInstallerFailed\" />\n </Target>\n\n <Target Name=\"MarkInstallerFailed\">\n <!-- Called by the PackageBinaries method if creating the installer fails -->\n <BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(InstallerStepId)\"\n Status=\"Failed\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" />\n </Target>\n" }, { "answer_id": 8435110, "author": "Polyfun", "author_id": 181315, "author_profile": "https://Stackoverflow.com/users/181315", "pm_score": 0, "selected": false, "text": "<Target Name=\"AfterDropBuild\">\n <CallTarget Targets=\"CreateDelivery\"/>\n <CallTarget Targets=\"CreateInventory\"/>\n</Target>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
226,721
<p>I have a struts2 application with a single page that may show one of a number of values stored in a database. The application is for a school with many departments and each department has many programs. The department page is accessed using a url like this</p> <pre><code>department.action?id=2 </code></pre> <p>and the DepartmentAction will load the Department with id = 2 for display. All this is fine if the user is just browsing around the site but it gets uncomfortable if I want to provide a link to say the Engineering department in the newspapers. The link will have to be www.myschooldomain.com/department.action?id=2. I see a number of problems with this.</p> <p>First, it is not user friendly. Second, it is prone to be broken because the departments are dynamically maintained and the id for a department could change without warning making the link unstable.</p> <p>I would prefer to print a url like this: www.myschooldomain.com/department/engineering and have that somehow go to department.action?id=2.</p> <p>My thoughts so far: create an action that will parse the url for the department name at the end then look it up by name. Maybe I could add a friendlyurl field to the database for each department.</p> <p>But the question is: Is there a better way to do this in struts2?</p> <p>Thanks.</p> <p><strong>Update (May 2009):</strong> I just happened to stumble back over this question and thought that I would say what I did to solve it. </p> <p>I created a new package in the struts.xml called departments. In this package there is only one action mapped to *. So it catches all requests to mydomain.com/departments/anything.html.</p> <p>In the action class I simply parse the url and look for the part between departments/ and .html and that is the name of the department so I can do a lookup in the database for it. This has been working fine for almost 5 months now and I have implemented it for other areas of the site.</p>
[ { "answer_id": 226827, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": true, "text": "Map getPathInfo() null /departments/" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
226,743
<p>I am using the webbrowser control in visual studio. I think it is a wrapper around internet explorer. Anyway all is going well I am using it in edit mode however I can't get he document's keydown event to fire (in order to catch ctrl+v) anyone had similar problems with it?</p> <p>Anyone have a solution?</p>
[ { "answer_id": 226794, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 3, "selected": true, "text": " webBrowser1.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowser1_PreviewKeyDown); \n\n....\n\n private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {\n Console.WriteLine(e.KeyCode.ToString() + \" \" + e.Modifiers.ToString());\n if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V) {\n MessageBox.Show(\"ctrl-v pressed\");\n }\n }\n" }, { "answer_id": 227868, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 0, "selected": false, "text": "protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n{ \n const int WM_KEYDOWN = 0x100; \n const int WM_SYSKEYDOWN = 0x104; \n\n if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN)) \n { \n switch(keyData) \n { \n case Keys.Down: \n this.Parent.Text=\"Down Arrow Captured\"; \n break; \n\n...\n\n } \n } \n\n return base.ProcessCmdKey(ref msg,keyData); \n} \n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
226,750
<p>For example, Convert.ToDouble("0.1234567890123456789") = 0.123456789012346</p> <p>What is the maximum number of significant figures? Couldn't find it in the docs.</p>
[ { "answer_id": 226762, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 2, "selected": false, "text": "sign * 1.mantissa * 2^(exponent - bias)" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042/" ]
226,784
<p>I have downloaded Privoxy few weeks ago and for the fun I was curious to know how a simple version of it can be done.</p> <p>I understand that I need to configure the browser (client) to send request to the proxy. The proxy send the request to the web (let say it's a http proxy). The proxy will receive the answer... but how can the proxy send back the request to the browser (client)?</p> <p>I have search on the web for C# and http proxy but haven't found something that let me understand how it works behind the scene correctly. (I believe I do not want a reverse proxy but I am not sure).</p> <p>Does any of you have some explication or some information that will let me continue this small project?</p> <h2>Update</h2> <p>This is what I understand (see graphic below).</p> <p><strong>Step 1</strong> I configure the client (browser) for all request to be send to 127.0.0.1 at the port the Proxy listen. This way, request will be not sent to the Internet directly but will be processed by the proxy.</p> <p><strong>Step2</strong> The proxy see a new connection, read the HTTP header and see the request he must executes. He executes the request.</p> <p><strong>Step3</strong> The proxy receive an answer from the request. Now he must send the answer from the web to the client but how???</p> <p><img src="https://i.stack.imgur.com/zNWDc.png" alt="alt text" /></p> <h3>Useful link</h3> <p><a href="http://www.mentalis.org/soft/projects/proxy/" rel="noreferrer">Mentalis Proxy</a> : I have found this project that is a proxy (but more that I would like). I might check the source but I really wanted something basic to understand more the concept.</p> <p><a href="http://www.codeproject.com/KB/aspnet/asproxy.aspx" rel="noreferrer">ASP Proxy</a> : I might be able to get some information over here too.</p> <p><a href="http://bartdesmet.net/blogs/bart/archive/2007/02/22/httplistener-for-dummies-a-simple-http-request-reflector.aspx" rel="noreferrer">Request reflector</a> : This is a simple example.</p> <p>Here is a <a href="https://github.com/MrDesjardins/SimpleHttpProxy" rel="noreferrer">Git Hub Repository with a Simple Http Proxy</a>.</p>
[ { "answer_id": 226795, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "HttpListener HttpWebRequest" }, { "answer_id": 806378, "author": "Vadym Stetsiak", "author_id": 6952, "author_profile": "https://Stackoverflow.com/users/6952", "pm_score": 4, "selected": false, "text": "Browser Proxy HTTP server\n Open TCP connection \n Send HTTP request -----------> \n Read HTTP header\n detect Host header\n Send request to HTTP ----------->\n Server\n <-----------\n Read response and send\n <----------- it back to the browser\nRender content\n" }, { "answer_id": 58039128, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 2, "selected": false, "text": "// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068\nusing (var server = new ProxyServer(\"http://localhost:53068\", \"http://localhost:5000/\", \"http://127.0.0.1:5000/\"))\n{\n server.Start();\n Console.WriteLine(\"Press ESC to stop server.\");\n while (true)\n {\n var key = Console.ReadKey(true);\n if (key.Key == ConsoleKey.Escape)\n break;\n }\n server.Stop();\n}\n\n....\n\npublic class ProxyServer : IDisposable\n{\n private readonly HttpListener _listener;\n private readonly int _targetPort;\n private readonly string _targetHost;\n private static readonly HttpClient _client = new HttpClient();\n\n public ProxyServer(string targetUrl, params string[] prefixes)\n : this(new Uri(targetUrl), prefixes)\n {\n }\n\n public ProxyServer(Uri targetUrl, params string[] prefixes)\n {\n if (targetUrl == null)\n throw new ArgumentNullException(nameof(targetUrl));\n\n if (prefixes == null)\n throw new ArgumentNullException(nameof(prefixes));\n\n if (prefixes.Length == 0)\n throw new ArgumentException(null, nameof(prefixes));\n\n RewriteTargetInText = true;\n RewriteHost = true;\n RewriteReferer = true;\n TargetUrl = targetUrl;\n _targetHost = targetUrl.Host;\n _targetPort = targetUrl.Port;\n Prefixes = prefixes;\n\n _listener = new HttpListener();\n foreach (var prefix in prefixes)\n {\n _listener.Prefixes.Add(prefix);\n }\n }\n\n public Uri TargetUrl { get; }\n public string[] Prefixes { get; }\n public bool RewriteTargetInText { get; set; }\n public bool RewriteHost { get; set; }\n public bool RewriteReferer { get; set; } // this can have performance impact...\n\n public void Start()\n {\n _listener.Start();\n _listener.BeginGetContext(ProcessRequest, null);\n }\n\n private async void ProcessRequest(IAsyncResult result)\n {\n if (!_listener.IsListening)\n return;\n\n var ctx = _listener.EndGetContext(result);\n _listener.BeginGetContext(ProcessRequest, null);\n await ProcessRequest(ctx).ConfigureAwait(false);\n }\n\n protected virtual async Task ProcessRequest(HttpListenerContext context)\n {\n if (context == null)\n throw new ArgumentNullException(nameof(context));\n\n var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);\n using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))\n {\n msg.Version = context.Request.ProtocolVersion;\n\n if (context.Request.HasEntityBody)\n {\n msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg\n }\n\n string host = null;\n foreach (string headerName in context.Request.Headers)\n {\n var headerValue = context.Request.Headers[headerName];\n if (headerName == \"Content-Length\" && headerValue == \"0\") // useless plus don't send if we have no entity body\n continue;\n\n bool contentHeader = false;\n switch (headerName)\n {\n // some headers go to content...\n case \"Allow\":\n case \"Content-Disposition\":\n case \"Content-Encoding\":\n case \"Content-Language\":\n case \"Content-Length\":\n case \"Content-Location\":\n case \"Content-MD5\":\n case \"Content-Range\":\n case \"Content-Type\":\n case \"Expires\":\n case \"Last-Modified\":\n contentHeader = true;\n break;\n\n case \"Referer\":\n if (RewriteReferer && Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle\n {\n var builder = new UriBuilder(referer);\n builder.Host = TargetUrl.Host;\n builder.Port = TargetUrl.Port;\n headerValue = builder.ToString();\n }\n break;\n\n case \"Host\":\n host = headerValue;\n if (RewriteHost)\n {\n headerValue = TargetUrl.Host + \":\" + TargetUrl.Port;\n }\n break;\n }\n\n if (contentHeader)\n {\n msg.Content.Headers.Add(headerName, headerValue);\n }\n else\n {\n msg.Headers.Add(headerName, headerValue);\n }\n }\n\n using (var response = await _client.SendAsync(msg).ConfigureAwait(false))\n {\n using (var os = context.Response.OutputStream)\n {\n context.Response.ProtocolVersion = response.Version;\n context.Response.StatusCode = (int)response.StatusCode;\n context.Response.StatusDescription = response.ReasonPhrase;\n\n foreach (var header in response.Headers)\n {\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n foreach (var header in response.Content.Headers)\n {\n if (header.Key == \"Content-Length\") // this will be set automatically at dispose time\n continue;\n\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n var ct = context.Response.ContentType;\n if (RewriteTargetInText && host != null && ct != null &&\n (ct.IndexOf(\"text/html\", StringComparison.OrdinalIgnoreCase) >= 0 ||\n ct.IndexOf(\"application/json\", StringComparison.OrdinalIgnoreCase) >= 0))\n {\n using (var ms = new MemoryStream())\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(ms).ConfigureAwait(false);\n var enc = context.Response.ContentEncoding ?? Encoding.UTF8;\n var html = enc.GetString(ms.ToArray());\n if (TryReplace(html, \"//\" + _targetHost + \":\" + _targetPort + \"/\", \"//\" + host + \"/\", out var replaced))\n {\n var bytes = enc.GetBytes(replaced);\n using (var ms2 = new MemoryStream(bytes))\n {\n ms2.Position = 0;\n await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n else\n {\n ms.Position = 0;\n await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n else\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n }\n }\n\n public void Stop() => _listener.Stop();\n public override string ToString() => string.Join(\", \", Prefixes) + \" => \" + TargetUrl;\n public void Dispose() => ((IDisposable)_listener)?.Dispose();\n\n // out-of-the-box replace doesn't tell if something *was* replaced or not\n private static bool TryReplace(string input, string oldValue, string newValue, out string result)\n {\n if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))\n {\n result = input;\n return false;\n }\n\n var oldLen = oldValue.Length;\n var sb = new StringBuilder(input.Length);\n bool changed = false;\n var offset = 0;\n for (int i = 0; i < input.Length; i++)\n {\n var c = input[i];\n\n if (offset > 0)\n {\n if (c == oldValue[offset])\n {\n offset++;\n if (oldLen == offset)\n {\n changed = true;\n sb.Append(newValue);\n offset = 0;\n }\n continue;\n }\n\n for (int j = 0; j < offset; j++)\n {\n sb.Append(input[i - offset + j]);\n }\n\n sb.Append(c);\n offset = 0;\n }\n else\n {\n if (c == oldValue[0])\n {\n if (oldLen == 1)\n {\n changed = true;\n sb.Append(newValue);\n }\n else\n {\n offset = 1;\n }\n continue;\n }\n\n sb.Append(c);\n }\n }\n\n if (changed)\n {\n result = sb.ToString();\n return true;\n }\n\n result = input;\n return false;\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
226,785
<p>We have a netbeans project that has an xsd that we use to create a wsdl and we use the wsdl to create a webservice. Since we are using types in our xsd jaxb is used and one of our webservice methods looks like this: </p> <pre><code>public void someMethod( org.netbeans.xml.schema.line.Line x )... </code></pre> <p>So that leaves us a problem with subversion since the Line objects are generated by netbeans. So we want to do is either tell netbeans to place the files inside of the project? Or tell netbeans that we will generate the jaxb code and that they should use our classes when the webservice calls are processed? How can we accomplish one of these, what are some other alternatives?</p>
[ { "answer_id": 226795, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "HttpListener HttpWebRequest" }, { "answer_id": 806378, "author": "Vadym Stetsiak", "author_id": 6952, "author_profile": "https://Stackoverflow.com/users/6952", "pm_score": 4, "selected": false, "text": "Browser Proxy HTTP server\n Open TCP connection \n Send HTTP request -----------> \n Read HTTP header\n detect Host header\n Send request to HTTP ----------->\n Server\n <-----------\n Read response and send\n <----------- it back to the browser\nRender content\n" }, { "answer_id": 58039128, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 2, "selected": false, "text": "// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068\nusing (var server = new ProxyServer(\"http://localhost:53068\", \"http://localhost:5000/\", \"http://127.0.0.1:5000/\"))\n{\n server.Start();\n Console.WriteLine(\"Press ESC to stop server.\");\n while (true)\n {\n var key = Console.ReadKey(true);\n if (key.Key == ConsoleKey.Escape)\n break;\n }\n server.Stop();\n}\n\n....\n\npublic class ProxyServer : IDisposable\n{\n private readonly HttpListener _listener;\n private readonly int _targetPort;\n private readonly string _targetHost;\n private static readonly HttpClient _client = new HttpClient();\n\n public ProxyServer(string targetUrl, params string[] prefixes)\n : this(new Uri(targetUrl), prefixes)\n {\n }\n\n public ProxyServer(Uri targetUrl, params string[] prefixes)\n {\n if (targetUrl == null)\n throw new ArgumentNullException(nameof(targetUrl));\n\n if (prefixes == null)\n throw new ArgumentNullException(nameof(prefixes));\n\n if (prefixes.Length == 0)\n throw new ArgumentException(null, nameof(prefixes));\n\n RewriteTargetInText = true;\n RewriteHost = true;\n RewriteReferer = true;\n TargetUrl = targetUrl;\n _targetHost = targetUrl.Host;\n _targetPort = targetUrl.Port;\n Prefixes = prefixes;\n\n _listener = new HttpListener();\n foreach (var prefix in prefixes)\n {\n _listener.Prefixes.Add(prefix);\n }\n }\n\n public Uri TargetUrl { get; }\n public string[] Prefixes { get; }\n public bool RewriteTargetInText { get; set; }\n public bool RewriteHost { get; set; }\n public bool RewriteReferer { get; set; } // this can have performance impact...\n\n public void Start()\n {\n _listener.Start();\n _listener.BeginGetContext(ProcessRequest, null);\n }\n\n private async void ProcessRequest(IAsyncResult result)\n {\n if (!_listener.IsListening)\n return;\n\n var ctx = _listener.EndGetContext(result);\n _listener.BeginGetContext(ProcessRequest, null);\n await ProcessRequest(ctx).ConfigureAwait(false);\n }\n\n protected virtual async Task ProcessRequest(HttpListenerContext context)\n {\n if (context == null)\n throw new ArgumentNullException(nameof(context));\n\n var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);\n using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))\n {\n msg.Version = context.Request.ProtocolVersion;\n\n if (context.Request.HasEntityBody)\n {\n msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg\n }\n\n string host = null;\n foreach (string headerName in context.Request.Headers)\n {\n var headerValue = context.Request.Headers[headerName];\n if (headerName == \"Content-Length\" && headerValue == \"0\") // useless plus don't send if we have no entity body\n continue;\n\n bool contentHeader = false;\n switch (headerName)\n {\n // some headers go to content...\n case \"Allow\":\n case \"Content-Disposition\":\n case \"Content-Encoding\":\n case \"Content-Language\":\n case \"Content-Length\":\n case \"Content-Location\":\n case \"Content-MD5\":\n case \"Content-Range\":\n case \"Content-Type\":\n case \"Expires\":\n case \"Last-Modified\":\n contentHeader = true;\n break;\n\n case \"Referer\":\n if (RewriteReferer && Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle\n {\n var builder = new UriBuilder(referer);\n builder.Host = TargetUrl.Host;\n builder.Port = TargetUrl.Port;\n headerValue = builder.ToString();\n }\n break;\n\n case \"Host\":\n host = headerValue;\n if (RewriteHost)\n {\n headerValue = TargetUrl.Host + \":\" + TargetUrl.Port;\n }\n break;\n }\n\n if (contentHeader)\n {\n msg.Content.Headers.Add(headerName, headerValue);\n }\n else\n {\n msg.Headers.Add(headerName, headerValue);\n }\n }\n\n using (var response = await _client.SendAsync(msg).ConfigureAwait(false))\n {\n using (var os = context.Response.OutputStream)\n {\n context.Response.ProtocolVersion = response.Version;\n context.Response.StatusCode = (int)response.StatusCode;\n context.Response.StatusDescription = response.ReasonPhrase;\n\n foreach (var header in response.Headers)\n {\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n foreach (var header in response.Content.Headers)\n {\n if (header.Key == \"Content-Length\") // this will be set automatically at dispose time\n continue;\n\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n var ct = context.Response.ContentType;\n if (RewriteTargetInText && host != null && ct != null &&\n (ct.IndexOf(\"text/html\", StringComparison.OrdinalIgnoreCase) >= 0 ||\n ct.IndexOf(\"application/json\", StringComparison.OrdinalIgnoreCase) >= 0))\n {\n using (var ms = new MemoryStream())\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(ms).ConfigureAwait(false);\n var enc = context.Response.ContentEncoding ?? Encoding.UTF8;\n var html = enc.GetString(ms.ToArray());\n if (TryReplace(html, \"//\" + _targetHost + \":\" + _targetPort + \"/\", \"//\" + host + \"/\", out var replaced))\n {\n var bytes = enc.GetBytes(replaced);\n using (var ms2 = new MemoryStream(bytes))\n {\n ms2.Position = 0;\n await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n else\n {\n ms.Position = 0;\n await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n else\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n }\n }\n\n public void Stop() => _listener.Stop();\n public override string ToString() => string.Join(\", \", Prefixes) + \" => \" + TargetUrl;\n public void Dispose() => ((IDisposable)_listener)?.Dispose();\n\n // out-of-the-box replace doesn't tell if something *was* replaced or not\n private static bool TryReplace(string input, string oldValue, string newValue, out string result)\n {\n if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))\n {\n result = input;\n return false;\n }\n\n var oldLen = oldValue.Length;\n var sb = new StringBuilder(input.Length);\n bool changed = false;\n var offset = 0;\n for (int i = 0; i < input.Length; i++)\n {\n var c = input[i];\n\n if (offset > 0)\n {\n if (c == oldValue[offset])\n {\n offset++;\n if (oldLen == offset)\n {\n changed = true;\n sb.Append(newValue);\n offset = 0;\n }\n continue;\n }\n\n for (int j = 0; j < offset; j++)\n {\n sb.Append(input[i - offset + j]);\n }\n\n sb.Append(c);\n offset = 0;\n }\n else\n {\n if (c == oldValue[0])\n {\n if (oldLen == 1)\n {\n changed = true;\n sb.Append(newValue);\n }\n else\n {\n offset = 1;\n }\n continue;\n }\n\n sb.Append(c);\n }\n }\n\n if (changed)\n {\n result = sb.ToString();\n return true;\n }\n\n result = input;\n return false;\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
226,828
<p>After discussing with a newly arrived developer in my team, I realized that there are still, in C++, habits of using C constructs because they are supposed to be better (i.e. faster, leaner, prettier, pick your reason).</p> <p><strong>What are the examples worth sharing, showing a C constructs, compared to the similar C++ construct?</strong></p> <p>For each example, I need to read the reasons the C++ construct is as good as or even better the original C construct. The aim is to offer alternatives to some C constructs that are considered somewhat dangerous/unsafe in C++ code (C++0x valid only answers are accepted as long as clearly marked as C++0x only).</p> <p>I'll post below an answer (struct inline initialization) as an example.</p> <p><em>Note 1: Please, one answer per case. If you have multiple cases, please post multiple answers</em></p> <p><em>Note 2: <s>This is not a C question. Do not add the "C" tag to this question.</s></em> <em>This is not supposed to become a fight between C++ and C. Only the study of some constructs of the C subset of C++, and their alternative in other C++ "toolkits"</em></p> <p><em>Note 3: This is not a C-bashing question. I want reasons. Boasting, bashing, and unproven comparisons will be downmodded. Mentioning C++ features without a C equivalent could be considered out of topic: I want the put side by side a C feature against a C++ feature.</em></p>
[ { "answer_id": 226833, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "// C-like code in C++\nstruct CRect\n{\n int x ;\n int y ;\n} ;\n\nvoid doSomething()\n{\n CRect r0 ; // uninitialized\n CRect r1 = { 25, 40 } ; // vulnerable to some silent struct reordering,\n // or adding a parameter\n}\n // C++\nstruct CRect\n{\n CRect() : x(0), y(0) {} ;\n CRect(int X, int Y) : x(X), y(Y) {} ;\n int x ;\n int y ;\n} ;\n\nvoid doSomething()\n{\n CRect r0 ;\n CRect r1(25, 40) ;\n}\n" }, { "answer_id": 226890, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": -1, "selected": false, "text": "void*" }, { "answer_id": 227021, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 5, "selected": false, "text": "#define max(x,y) (x) > (y) ? (x) : (y)\n inline template<typename T>\nconst T& max(const T& x, const T& y)\n{\n return x > y ? x : y;\n}\n" }, { "answer_id": 227095, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 4, "selected": false, "text": "void AddUser(LPCSTR lpcstrName, int iAge, const char *lpcstrAddress);\nvoid AddUserByNameOnly(LPCSTR lpcstrName)\n {\n AddUser(lpcstrName, -1,NULL);\n }\n void User::Add(LPCSTR lpcstrName, int iAge=-1, const char *lpcstrAddress=NULL);\n" }, { "answer_id": 227142, "author": "Andrew Top", "author_id": 30036, "author_profile": "https://Stackoverflow.com/users/30036", "pm_score": 5, "selected": false, "text": "Resource r;\nr = Acquire(...);\n\n... Code that uses r ...\n\nRelease(r);\n Resource Release r r Resource r r.Acquire(...) r class ResourceRAII\n{\n Resource rawResource;\n\n public:\n ResourceRAII(...) {rawResource = Acquire(...);}\n ~ResourceRAII() {Release(rawResource);}\n\n // Functions for manipulating the resource\n};\n\n...\n\n{\n ResourceRAII r(...);\n\n ... Code that uses r ...\n}\n" }, { "answer_id": 227188, "author": "Jeff Linahan", "author_id": 2222, "author_profile": "https://Stackoverflow.com/users/2222", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n int num = 42;\n\n printf(\"%s%d%c\", \"Hello World\\n\", num, '\\n');\n\n return 0;\n}\n #include <iostream>\n\nint main()\n{\n int num = 42;\n\n std::cout << \"Hello World\\n\" << num << '\\n';\n}\n" }, { "answer_id": 227202, "author": "Cat Plus Plus", "author_id": 16102, "author_profile": "https://Stackoverflow.com/users/16102", "pm_score": 4, "selected": false, "text": "int **foo = new int*[n];\nfor (int x = 0; x < n; ++x) foo[x] = new int[m];\n// (...)\nfor (int x = 0; x < n; ++x) delete[] foo[x];\ndelete[] foo;\n std::vector< std::vector<int> > foo(n, std::vector<int>(m));\n// (...)\n" }, { "answer_id": 227220, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 4, "selected": false, "text": "#define MYBUFSIZE 256\n\n. . . \n\nchar somestring[MYBUFSIZE];\n const int MYBUFSIZE = 256;\n\nchar somestring[MYBUFSIZE];\n" }, { "answer_id": 227349, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "qsort sort sort sort qsort qsort sort int int pint_less_than(void const* pa, void const* pb) {\n return *static_cast<int const*>(pa) - *static_cast<int const*>(pb);\n}\n\nstruct greater_than {\n bool operator ()(int a, int b) {\n return a > b;\n }\n};\n\ntemplate <std::size_t Size>\nvoid print(int (&arr)[Size]) {\n std::copy(arr, arr + Size, std::ostream_iterator<int>(std::cout, \" \"));\n std::cout << std::endl;\n}\n\nint main() {\n std::size_t const size = 5;\n int values[] = { 4, 3, 6, 8, 2 };\n\n { // qsort\n int arr[size];\n std::copy(values, values + size, arr);\n std::qsort(arr, size, sizeof(int), &pint_less_than);\n print(arr);\n }\n\n { // sort\n int arr[size];\n std::copy(values, values + size, arr);\n std::sort(arr, arr + size);\n print(arr);\n }\n\n { // sort with custom comparer\n int arr[size];\n std::copy(values, values + size, arr);\n std::sort(arr, arr + size, greater_than());\n print(arr);\n }\n}\n" }, { "answer_id": 227408, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n char src[23];\nint dest[ARRAY_SIZE(src)];\n template <typename T, size_t size>\ninline size_t array_size(T (&p)[size])\n{\n // return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n #include <iostream>\n\n// C-like macro\n#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n\n// C++ replacement\ntemplate <typename T, size_t size>\ninline size_t array_size(T (&p)[size])\n{\n // return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n\nint main(int argc, char **argv)\n{\n char src[23];\n char * src2 = new char[23] ;\n int dest[ARRAY_SIZE(src)];\n int dest2[array_size(src)];\n\n std::cout << \"ARRAY_SIZE(src) : \" << ARRAY_SIZE(src) << std::endl ;\n std::cout << \"array_size(src) : \" << array_size(src) << std::endl ;\n std::cout << \"ARRAY_SIZE(src2) : \" << ARRAY_SIZE(src2) << std::endl ;\n // The next line won't compile\n //std::cout << \"array_size(src2) : \" << array_size(src2) << std::endl ;\n\n return 0;\n}\n ARRAY_SIZE(src) : 23\narray_size(src) : 23\nARRAY_SIZE(src2) : 4\n /main.cpp|539|error: no matching function for call to ‘array_size(char*&)’|\n inline template <typename T, size_t size>\nconstexpr size_t array_size(T (&p)[size])\n{\n //return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n template<typename T, size_t N> char (& array_size(T(&)[N]) )[N];\n int p[] = { 1, 2, 3, 4, 5, 6 };\nint u[sizeof array_size(p)]; // we get the size (6) at compile time.\n array_size" }, { "answer_id": 227409, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 2, "selected": false, "text": "(type) static_cast<type>()" }, { "answer_id": 234192, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 0, "selected": false, "text": "AddUserName(int userid, NameInfo nameinfo);\nAddUserAge(int userid, int iAge);\nAddUserAddress(int userid, AddressInfo addressinfo);\n User::AddInfo(NameInfo nameinfo);\nUser::AddInfo(int iAge);\nUser::AddInfo(AddressInfo addressInfo);\n" }, { "answer_id": 245394, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 2, "selected": false, "text": "int main(void)\n{\n for(int i = 0; i < 10; i++)\n ...\n\n int r = 0;\n return r;\n}\n" }, { "answer_id": 402185, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 2, "selected": false, "text": "void PrintToScreen(const char *pBuffer);\nvoid PrintToFile(const char *pBuffer);\nvoid PrintToSocket(const char *pBuffer);\nvoid PrintPrettyToScreen(const char *pBuffer);\n namespace Screen\n{\n void Print(const char *pBuffer);\n}\n\nnamespace File\n{\n void Print(const char *pBuffer);\n}\n\nnamespace Socket\n{\n void Print(const char *pBuffer);\n}\n\nnamespace PrettyScreen\n{\n void Print(const char *pBuffer);\n}\n" }, { "answer_id": 402222, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 0, "selected": false, "text": "int fibonacci() {\n static int a0 = 0, a1 =1; // problematic....\n int temp = a0;\n a0 = a1;\n a1 = temp + a0;\n return temp;\n}\n\nvoid Graph( (int)(*func)(void) );\nvoid Graph2( (int)(*func1)(void), (int)(*func2)(void) ); \n\nGraph(fibonacci);\nGraph2(fibonacci,fibonacci);\n fibonacci() Graph Graph2() Graph2() func1 func2 class Fib {\n public:\n Fib() : a0_(1), a1_(1) {}\n int operator();\n private:\n int a0_, a1_;\n};\nint Fib::operator() {\n int temp = a0_;\n a0_ = a1_;\n a1_ = temp + a0_;\n return temp;\n}\n\n\ntemplate <class FuncT>\nvoid Graph( FuncT &func );\n\ntemplate <class FuncT>\nvoid Graph2( FuncT &func1, FuncT &func2); \n\nFib a,b,c;\nGraph(a);\nGraph2(b,c);\n Graph() Graph2() Graph2() b c" }, { "answer_id": 411610, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "template<typename T, size_t N> char (& array_size(T(&)[N]) )[N];\n void pass(int *q) {\n int n1 = sizeof(q); // oops, size of the pointer!\n int n2 = sizeof array_size(q); // error! q is not an array!\n}\n\nint main() {\n int p[] = { 1, 2, 3, 4, 5, 6 };\n int u[sizeof array_size(p)]; // we get the size at compile time.\n\n pass(p);\n}\n" }, { "answer_id": 10464325, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 1, "selected": false, "text": "std::copy memcpy memcpy std::copy std::copy_backward memcpy memcpy std::copy std::copy std::copy std::list std::copy memcpy memcpy" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
226,831
<p>I'd like to make anchors to every post in my asp.net forum. Every forum's post is rendered using repeater control. How can I render <code>&lt;a name="anchor_name"&gt;&lt;/a&gt;</code> in asp.net?</p>
[ { "answer_id": 226838, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 4, "selected": true, "text": "<a name='<%# Eval(\"PostId\") %>' />\n" }, { "answer_id": 226841, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": -1, "selected": false, "text": "<a name=\"anchor_name\"></a>" }, { "answer_id": 226854, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 1, "selected": false, "text": "<a name=\"<%# Bind('PostId') %>\" runat=\"server\" />\n" }, { "answer_id": 226943, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 0, "selected": false, "text": "override string UniqueID { get { return ID; } }\n <MyPrefix:MyHyperLink ID=\"IDOfYourHyperLink\" ... />\n (e.Item.FindControl(\"IDOfYourHyperLink\") as MyHyperlink).ID = NowIKnowWhatToUseHere;\n" }, { "answer_id": 227061, "author": "rafek", "author_id": 3182, "author_profile": "https://Stackoverflow.com/users/3182", "pm_score": 0, "selected": false, "text": "<a name='<%# DataBinder.Eval(Container.DataItem, \"Id\") %>' />\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
226,834
<p>I'm working on a C++ prettyprinter and would like to show the results of the prettyprinter by comparing code before and after running it. Does anyone know where I can find some ugly C++ code to run through the prettypretty? Ideally the code would come from some open source software.</p>
[ { "answer_id": 227163, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 4, "selected": false, "text": " if (x < foo (y, z))\n haha = bar[4] + 5;\n else\n {\n while (z)\n {\n haha += foo (z, z);\n z--;\n }\n return ++x + bar ();\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
226,847
<p>I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =&lt; only. Here is the code I have:</p> <pre><code>var oImg = document.createElement("img"); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); </code></pre> <p>Is this the simplest but most robust (error free) way to do it?</p> <p>I cannot use a framework like jQuery. It needs to be in plain JavaScript.</p>
[ { "answer_id": 226856, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });\n$(document).insert(elem);\n" }, { "answer_id": 226875, "author": "Tad", "author_id": 30095, "author_profile": "https://Stackoverflow.com/users/30095", "pm_score": 6, "selected": false, "text": "var img = new Image(1,1); // width, height values are optional params \nimg.src = 'http://www.testtrackinglink.com';\n" }, { "answer_id": 226922, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 5, "selected": false, "text": "var img = document.createElement('img');\nimg.src = 'my_image.jpg';\ndocument.getElementById('container').appendChild(img);\n" }, { "answer_id": 226941, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": false, "text": "$('#container').append('<img src=\"/path/to/image.jpg\"\n width=\"16\" height=\"16\" alt=\"Test Image\" title=\"Test Image\" />');\n $('#container').append($('<img>', { \n src : \"/path/to/image.jpg\", \n width : 16, \n height : 16, \n alt : \"Test Image\", \n title : \"Test Image\"\n}));\n" }, { "answer_id": 227093, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 8, "selected": true, "text": "oImg.setAttribute('width', '1px');\n px oImg.width = '1';\n oImg.style.width = '1px';\n document.createElement() new Image() // IEWIN boolean previously sniffed through eg. conditional comments\n\nfunction img_create(src, alt, title) {\n var img = IEWIN ? new Image() : document.createElement('img');\n img.src = src;\n if ( alt != null ) img.alt = alt;\n if ( title != null ) img.title = title;\n return img;\n}\n document.body.appendChild <body> body.insertBefore(body.firstChild) <div>" }, { "answer_id": 229329, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 3, "selected": false, "text": "(new Image()).src = \"http:/track.me/image.gif\";\n" }, { "answer_id": 230096, "author": "Binny V A", "author_id": 15595, "author_profile": "https://Stackoverflow.com/users/15595", "pm_score": 3, "selected": false, "text": "document.getElementById(\"image-holder\").innerHTML = \"<img src='image.png' alt='The Image' />\";\n" }, { "answer_id": 7776653, "author": "Nitin Bansal", "author_id": 967062, "author_profile": "https://Stackoverflow.com/users/967062", "pm_score": 2, "selected": false, "text": "var newImage = new Image();\nnewImage.src = \"someImg.jpg\";\n\nif(document.images)\n{\n document.images.yourImageElementName.src = newImage.src;\n}\n" }, { "answer_id": 40192076, "author": "Vaibs", "author_id": 1253088, "author_profile": "https://Stackoverflow.com/users/1253088", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>create image demo</title>\n <script>\n\n\n function createImage() {\n var x = document.createElement(\"IMG\");\n x.setAttribute(\"src\", \"http://www.iseebug.com/wp-content/uploads/2016/09/c2.png\");\n x.setAttribute(\"height\", \"200\");\n x.setAttribute(\"width\", \"400\");\n x.setAttribute(\"alt\", \"suppp\");\n document.getElementById(\"res\").appendChild(x);\n }\n\n </script>\n</head>\n<body>\n<button onclick=\"createImage()\">ok</button>\n<div id=\"res\"></div>\n\n</body>\n</html>\n" }, { "answer_id": 50042804, "author": "Gvs Akhil", "author_id": 7737777, "author_profile": "https://Stackoverflow.com/users/7737777", "pm_score": 1, "selected": false, "text": "method1 :\n let pics=document.getElementById(\"pics-thumbs\");\n let divholder=document.createDocumentFragment();\n for(let i=1;i<73;i++)\n {\n let img=document.createElement(\"img\");\n img.class=\"img-responsive\";\n img.src=`images/fun${i}.jpg`;\n divholder.appendChild(img);\n }\n pics.appendChild(divholder);\n method2: \nlet pics = document.getElementById(\"pics-thumbs\"),\n imgArr = [];\nfor (let i = 1; i < 73; i++) {\n\n imgArr.push(`<img class=\"img-responsive\" src=\"images/fun${i}.jpg\">`);\n}\npics.innerHTML = imgArr.join('<br>')\n<div id=\"pics-thumbs\"></div>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3004/" ]
226,894
<p>When you use the PHP <a href="http://us2.php.net/manual/en/function.copy.php" rel="noreferrer">copy</a> function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?</p>
[ { "answer_id": 226906, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "// The PHP copy function blindly copies over existing files. We don't wish\n// this to happen, so we have to perform the copy a bit differently. The\n// only safe way to ensure we don't overwrite an existing file is to call\n// fopen in create-only mode (mode 'x'). If it succeeds, the file did not\n// exist before, and we've successfully created it, meaning we own the\n// file. After that, we can safely copy over our own file.\n\n$filename = 'sourcefile.txt'\n$copyname = 'sourcefile_copy.txt'\nif ($file = @fopen($copyname, 'x')) {\n // We've successfully created a file, so it's ours. We'll close\n // our handle.\n if (!@fclose($file)) {\n // There was some problem with our file handle.\n return false;\n }\n\n // Now we copy over the file we created.\n if (!@copy($filename, $copyname)) {\n // The copy failed, even though we own the file, so we'll clean\n // up by itrying to remove the file and report failure.\n unlink($copyname);\n return false;\n }\n\n return true;\n}\n" }, { "answer_id": 547711, "author": "Ben Blank", "author_id": 46387, "author_profile": "https://Stackoverflow.com/users/46387", "pm_score": 0, "selected": false, "text": "link() copy() function safe_copy($src, $dest) {\n if (link($src, $dest)) {\n // Link succeeded, remove old name\n unlink($filename);\n return true;\n } else {\n // Link failed; filesystem has not been altered\n return false;\n }\n}\n" }, { "answer_id": 22653312, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 1, "selected": false, "text": "function safeCopy($src, $dest) {\n if (is_file($dest) === true) {\n // if the destination file already exists, it will NOT be overwritten. \n return false;\n }\n\n if (copy($src, $dest) === false) {\n echo \"Failed to copy $src... Permissions correct?\\n\";\n return false;\n }\n\n return true; \n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8458/" ]
226,896
<p>I am currently trying to create an Exception handler built into my windows service that, on an unhandled exception, sends a message to another program. I have built the method and gotten the communication working, but it seems that every time my program throws the error, (I have a raise call in the code to force it.) windows catches it instead and the Handler isn't called. Can anyone explain what I am doing wrong?.</p> <p>Simplified Code to explain:</p> <pre><code>procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin WriteLn('Display: ' + Exception(ExceptObject).Message); //send Message Here end; </code></pre> <p>I call this code to run it:</p> <pre><code>WriteLn('Starting'); ExceptProc := @ExceptionHandler; unhandled(); </code></pre> <p>I would expect the output to be:</p> <blockquote> <p>Starting<br/> Display: Unhandled</p> </blockquote> <p>but all it does is display:</p> <blockquote> <p>Starting</p> </blockquote> <p>Then windows returns a command prompt after about 5 seconds.</p> <p>Why isn't the handler being properly called?</p> <p>P.S. I've been running these tests in a console app for testing.</p> <p>EDIT:</p> <p>Here's some more information:</p> <p>Apparently when you have an assigned ExceptProc, your program shouldn't throw the normal runtime 217 error. I'm guessing this is what windows is catching, From what I can see however, my program is throwing that runtime error, and I can't get an ErrorProc to catch it either.</p>
[ { "answer_id": 227079, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 0, "selected": false, "text": "begin\n WriteLn('Starting');\n try\n ExceptProc := @ExceptionHandler;\n Unhandled;\n finally Readln; end;\nend.\n" }, { "answer_id": 227285, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "SetErrorMode(SEM_NOGPFAULTERRORBOX);\n {$apptype console}\n\nuses Windows, SysUtils;\n\nprocedure unhandled();\nbegin\n raise Exception.Create('Unhandled');\nend;\n\nprocedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer);\nbegin\n Writeln('here');\n WriteLn('Display: ' + Exception(ExceptObject).Message);\n Flush(Output);\n Halt(1);\nend;\n\nprocedure Go;\nbegin\n unhandled;\nend;\n\nbegin\n ExceptProc := @ExceptionHandler;\n SetErrorMode(SEM_NOGPFAULTERRORBOX);\n Go;\nend.\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16059/" ]
226,899
<p>I've got a reasonably simple query (this time) that I need ALL the results back from (I'm storing them in an Excel spreadsheet). The query itself times out the server, so how do I go about running it without that happening?</p>
[ { "answer_id": 226957, "author": "Nick Van Brunt", "author_id": 30470, "author_profile": "https://Stackoverflow.com/users/30470", "pm_score": 1, "selected": false, "text": "<cfsetting \nenableCFoutputOnly = \"yes|no\" \nrequestTimeOut = \"value in seconds\"\nshowDebugOutput = \"yes|no\" >\n" }, { "answer_id": 226958, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 3, "selected": false, "text": "<cfsetting requestTimeout=\"3600\" />\n" }, { "answer_id": 234771, "author": "rip747", "author_id": 31278, "author_profile": "https://Stackoverflow.com/users/31278", "pm_score": 3, "selected": false, "text": "<!--- init --->\n<cffunction name=\"init\" access=\"public\" returntype=\"Any\" output=\"false\">\n <cfargument name=\"name\" type=\"string\" required=\"true\">\n <cfset var local = {}>\n\n <!--- name of file when downloading --->\n <cfset variables.name = arguments.name & \".xls\">\n <!--- name of temp file --->\n <cfset variables.filename = CreateUUID() & \".csv\">\n <!--- full path to temp file for downloading --->\n <cfset variables.fullfilename = expandpath(\"/_temp\") & \"\\\" & variables.filename>\n <!--- file write java object --->\n <cfset variables.filewriter = CreateObject(\"java\",\"java.io.FileWriter\").init(\n variables.fullfilename\n ,JavaCast(\"boolean\",\"true\")\n )>\n <!--- buffered writer java object --->\n <cfset variables.bufferedwriter = CreateObject(\"java\",\"java.io.BufferedWriter\").init(\n variables.filewriter\n )>\n <!--- row delimeter --->\n <cfset variables.row = chr(10)>\n <!--- col delimeter --->\n <cfset variables.col = chr(9)>\n <!--- header container --->\n <cfset variables.headers = []>\n <!--- data container --->\n <cfset variables.data = []>\n <cfset newrow()>\n <cfreturn this>\n</cffunction>\n\n\n<!--- addheader --->\n<cffunction name=\"addheader\" access=\"public\" returntype=\"void\" output=\"false\">\n <cfargument name=\"str\" type=\"string\" required=\"true\">\n <cfset arrayappend(variables.headers, arguments.str)>\n</cffunction>\n\n<!--- newrow --->\n<cffunction name=\"newrow\" access=\"public\" returntype=\"void\" output=\"false\">\n <cfset arrayappend(variables.data, arraynew(1))>\n <cfset variables.data_counter = arraylen(variables.data)>\n</cffunction>\n\n<!--- adddata --->\n<cffunction name=\"adddata\" access=\"public\" returntype=\"void\" output=\"false\">\n <cfargument name=\"str\" type=\"string\" required=\"true\">\n <cfset arrayappend(variables.data[variables.data_counter], arguments.str)>\n</cffunction>\n\n<!--- flush --->\n<cffunction name=\"flush\" access=\"public\" returntype=\"void\" output=\"false\">\n <cfset var local = {}>\n\n <!--- write headers --->\n <cfset local.counter = 0>\n <cfset local.headers_count = arraylen(variables.headers)>\n <cfloop array=\"#variables.headers#\" index=\"local.header\">\n <cfset local.counter++>\n <cfset variables.bufferedwriter.write(local.header & variables.col)>\n </cfloop>\n\n <cfif not arrayisempty(variables.headers)>\n <cfset variables.bufferedwriter.write(variables.row)>\n </cfif>\n\n <!--- write data --->\n <cfloop array=\"#variables.data#\" index=\"local.data\">\n <cfloop array=\"#local.data#\" index=\"local.cell\">\n <cfset variables.bufferedwriter.write(local.cell & variables.col)>\n </cfloop>\n <cfset variables.bufferedwriter.write(variables.row)>\n </cfloop>\n\n <cfset variables.bufferedwriter.close()>\n <cfsetting showdebugoutput=\"No\">\n <cfheader name=\"Content-Description\" value=\"File Transfer\">\n <cfheader name=\"Content-Disposition\" value=\"attachment;filename=#variables.name#\">\n <cfcontent type=\"application/vnd.ms-excel\" file=\"#variables.fullfilename#\" deletefile=\"true\" reset=\"true\">\n</cffunction>\n" }, { "answer_id": 330812, "author": "Samiksha", "author_id": 29515, "author_profile": "https://Stackoverflow.com/users/29515", "pm_score": 1, "selected": false, "text": "group by where having" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
226,905
<p>I cannot get the internet explorer web developer tool bar to work with a pop-up, it won't render at the bottom of the pop-up. Any suggestions? </p>
[ { "answer_id": 12267176, "author": "moloko", "author_id": 1646700, "author_profile": "https://Stackoverflow.com/users/1646700", "pm_score": 3, "selected": false, "text": "unpin" }, { "answer_id": 22496042, "author": "Leniel Maccaferri", "author_id": 114029, "author_profile": "https://Stackoverflow.com/users/114029", "pm_score": 0, "selected": false, "text": "IE 11 Developer Tools popup Inspect Element Refresh Console debugger" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700/" ]
226,910
<p>I find it curious that the most obvious way to create <code>Date</code> objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.</p> <p>How do you check that a date, given as a combination of day, month, and year, is a valid date?</p> <p>For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.</p>
[ { "answer_id": 226920, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 6, "selected": true, "text": "Calendar cal = Calendar.getInstance();\ncal.setLenient(false);\ncal.setTime(yourDate);\ntry {\n cal.getTime();\n}\ncatch (Exception e) {\n System.out.println(\"Invalid date\");\n}\n" }, { "answer_id": 227232, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 5, "selected": false, "text": "boolean isLegalDate(String s) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n sdf.setLenient(false);\n return sdf.parse(s, new ParsePosition(0)) != null;\n}\n" }, { "answer_id": 892204, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 6, "selected": false, "text": " Date parseDate(String maybeDate, String format, boolean lenient) {\n Date date = null;\n\n // test date string matches format structure using regex\n // - weed out illegal characters and enforce 4-digit year\n // - create the regex based on the local format string\n String reFormat = Pattern.compile(\"d+|M+\").matcher(Matcher.quoteReplacement(format)).replaceAll(\"\\\\\\\\d{1,2}\");\n reFormat = Pattern.compile(\"y+\").matcher(reFormat).replaceAll(\"\\\\\\\\d{4}\");\n if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {\n\n // date string matches format structure, \n // - now test it can be converted to a valid date\n SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();\n sdf.applyPattern(format);\n sdf.setLenient(lenient);\n try { date = sdf.parse(maybeDate); } catch (ParseException e) { }\n } \n return date;\n } \n\n // used like this:\n Date date = parseDate( \"21/5/2009\", \"d/M/yyyy\", false);\n Locale locale = Locale.getDefault();\nSimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );\nString format = sdf.toPattern();\n import org.joda.time.format.*;\nimport org.joda.time.DateTime;\n\norg.joda.time.DateTime parseDate(String maybeDate, String format) {\n org.joda.time.DateTime date = null;\n try {\n DateTimeFormatter fmt = DateTimeFormat.forPattern(format);\n date = fmt.parseDateTime(maybeDate);\n } catch (Exception e) { }\n return date;\n}\n" }, { "answer_id": 4528089, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 2, "selected": false, "text": "package cruft;\n\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class DateValidator\n{\n private static final DateFormat DEFAULT_FORMATTER;\n\n static\n {\n DEFAULT_FORMATTER = new SimpleDateFormat(\"dd-MM-yyyy\");\n DEFAULT_FORMATTER.setLenient(false);\n }\n\n public static void main(String[] args)\n {\n for (String dateString : args)\n {\n try\n {\n System.out.println(\"arg: \" + dateString + \" date: \" + convertDateString(dateString));\n }\n catch (ParseException e)\n {\n System.out.println(\"could not parse \" + dateString);\n }\n }\n }\n\n public static Date convertDateString(String dateString) throws ParseException\n {\n return DEFAULT_FORMATTER.parse(dateString);\n }\n}\n java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011\ncould not parse 32-11-2010\ncould not parse 31-02-2010\narg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011\n\nProcess finished with exit code 0\n" }, { "answer_id": 4528094, "author": "Aravind Yarram", "author_id": 127320, "author_profile": "https://Stackoverflow.com/users/127320", "pm_score": 6, "selected": false, "text": "final static String DATE_FORMAT = \"dd-MM-yyyy\";\n\npublic static boolean isDateValid(String date) \n{\n try {\n DateFormat df = new SimpleDateFormat(DATE_FORMAT);\n df.setLenient(false);\n df.parse(date);\n return true;\n } catch (ParseException e) {\n return false;\n }\n}\n" }, { "answer_id": 15382305, "author": "Imran", "author_id": 1412471, "author_profile": "https://Stackoverflow.com/users/1412471", "pm_score": 0, "selected": false, "text": " public final boolean validateDateFormat(final String date) {\n String[] formatStrings = {\"MM/dd/yyyy\"};\n boolean isInvalidFormat = false;\n Date dateObj;\n for (String formatString : formatStrings) {\n try {\n SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();\n sdf.applyPattern(formatString);\n sdf.setLenient(false);\n dateObj = sdf.parse(date);\n System.out.println(dateObj);\n if (date.equals(sdf.format(dateObj))) {\n isInvalidFormat = false;\n break;\n }\n } catch (ParseException e) {\n isInvalidFormat = true;\n }\n }\n return isInvalidFormat;\n }\n" }, { "answer_id": 17710658, "author": "Ziya", "author_id": 1325331, "author_profile": "https://Stackoverflow.com/users/1325331", "pm_score": 3, "selected": false, "text": "org.apache.commons.validator.GenericValidator GenericValidator.isDate(String value, String datePattern, boolean strict);" }, { "answer_id": 18666219, "author": "Dresden Sparrow", "author_id": 2084112, "author_profile": "https://Stackoverflow.com/users/2084112", "pm_score": 2, "selected": false, "text": "private static boolean isDateValid(String s) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n try {\n Date d = asDate(s);\n if (sdf.format(d).equals(s)) {\n return true;\n } else {\n return false;\n }\n } catch (ParseException e) {\n return false;\n }\n}\n" }, { "answer_id": 23438158, "author": "Matthias Braun", "author_id": 775954, "author_profile": "https://Stackoverflow.com/users/775954", "pm_score": 4, "selected": false, "text": "LocalDate public static boolean isDateValid(int year, int month, int day) {\n try {\n LocalDate.of(year, month, day);\n } catch (DateTimeException e) {\n return false;\n }\n return true;\n}\n" }, { "answer_id": 30528952, "author": "Sufian", "author_id": 1276636, "author_profile": "https://Stackoverflow.com/users/1276636", "pm_score": 3, "selected": false, "text": "dateString private boolean isDateCorrect(String dateString) {\n try {\n Date date = mDateFormatter.parse(dateString);\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n return matchesOurDatePattern(dateString); //added my method\n }\n catch (ParseException e) {\n return false;\n }\n}\n\n/**\n * This will check if the provided string matches our date format\n * @param dateString\n * @return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)\n */\nprivate boolean matchesDatePattern(String dateString) {\n return dateString.matches(\"^\\\\d+\\\\-\\\\d+\\\\-\\\\d+\");\n}\n" }, { "answer_id": 35197612, "author": "mawa", "author_id": 5882412, "author_profile": "https://Stackoverflow.com/users/5882412", "pm_score": 3, "selected": false, "text": "public boolean isDateValid(String dateString, String pattern)\n{ \n try\n {\n SimpleDateFormat sdf = new SimpleDateFormat(pattern);\n if (sdf.format(sdf.parse(dateString)).equals(dateString))\n return true;\n }\n catch (ParseException pe) {}\n\n return false;\n}\n" }, { "answer_id": 39276958, "author": "TennisVisuals", "author_id": 4483303, "author_profile": "https://Stackoverflow.com/users/4483303", "pm_score": 0, "selected": false, "text": "Date.prototype.yyyymmdd = function() {\n var yyyy = this.getFullYear().toString();\n var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based\n var dd = this.getDate().toString();\n return zeroPad([yyyy, mm, dd].join('-')); \n};\n\nfunction zeroPad(date_string) {\n var dt = date_string.split('-');\n return dt[0] + '-' + (dt[1][1]?dt[1]:\"0\"+dt[1][0]) + '-' + (dt[2][1]?dt[2]:\"0\"+dt[2][0]);\n}\n\nfunction isDateCorrect(in_string) {\n if (!matchesDatePattern) return false;\n in_string = zeroPad(in_string);\n try {\n var idate = new Date(in_string);\n var out_string = idate.yyyymmdd();\n return in_string == out_string;\n } catch(err) {\n return false;\n }\n\n function matchesDatePattern(date_string) {\n var dateFormat = /[0-9]+-[0-9]+-[0-9]+/;\n return dateFormat.test(date_string); \n }\n}\n isDateCorrect('2014-02-23')\ntrue\n" }, { "answer_id": 39649815, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 5, "selected": false, "text": "java.time.DateTimeFormatter LocalDate DateTimeParseException LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.\n \"31/02/2000\" , // Input string.\n DateTimeFormatter // Define a formatting pattern to match your input string.\n .ofPattern ( \"dd/MM/uuuu\" )\n .withResolverStyle ( ResolverStyle.STRICT ) // Specify leniency in tolerating questionable inputs.\n)\n birthDate.isAfter( LocalDate.now().minusYears( 100 ) )\n LocalDate DateTimeFormatter ResolverStyle LocalDate String input = \"31/02/2000\";\nDateTimeFormatter f = DateTimeFormatter.ofPattern ( \"dd/MM/uuuu\" );\ntry {\n LocalDate ld = LocalDate.parse ( input , f );\n System.out.println ( \"ld: \" + ld );\n} catch ( DateTimeParseException e ) {\n System.out.println ( \"ERROR: \" + e );\n}\n java.time.DateTimeFormatter ResolverStyle f = f.withResolverStyle ( ResolverStyle.LENIENT );\n ResolverStyle.LENIENT ResolverStyle.SMART ResolverStyle.STRICT ResolverStyle.LENIENT ResolverStyle.SMART ResolverStyle.STRICT java.util.Date Calendar SimpleDateFormat java.sql.* Interval YearWeek YearQuarter" }, { "answer_id": 44917419, "author": "ashishdhiman2007", "author_id": 2301721, "author_profile": "https://Stackoverflow.com/users/2301721", "pm_score": 0, "selected": false, "text": "// to return valid days of month, according to month and year\nint returnDaysofMonth(int month, int year) {\n int daysInMonth;\n boolean leapYear;\n leapYear = checkLeap(year);\n if (month == 4 || month == 6 || month == 9 || month == 11)\n daysInMonth = 30;\n else if (month == 2)\n daysInMonth = (leapYear) ? 29 : 28;\n else\n daysInMonth = 31;\n return daysInMonth;\n}\n\n// to check a year is leap or not\nprivate boolean checkLeap(int year) {\n Calendar cal = Calendar.getInstance();\n cal.set(Calendar.YEAR, year);\n return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;\n}\n" }, { "answer_id": 53091974, "author": "db07", "author_id": 9177302, "author_profile": "https://Stackoverflow.com/users/9177302", "pm_score": 0, "selected": false, "text": " public static boolean checkFormat(String dateTimeString) {\n return dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\") || dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:\\\\d{2}:\\\\d{2}\")\n || dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}\") || dateTimeString\n .matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}Z\") ||\n dateTimeString.matches(\"^\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:\\\\d{2}:\\\\d{2}Z\");\n}\n" }, { "answer_id": 56888385, "author": "Suheb Rafique", "author_id": 7785060, "author_profile": "https://Stackoverflow.com/users/7785060", "pm_score": 0, "selected": false, "text": " public static String detectDateFormat(String inputDate, String requiredFormat) {\n String tempDate = inputDate.replace(\"/\", \"\").replace(\"-\", \"\").replace(\" \", \"\");\n String dateFormat;\n\n if (tempDate.matches(\"([0-12]{2})([0-31]{2})([0-9]{4})\")) {\n dateFormat = \"MMddyyyy\";\n } else if (tempDate.matches(\"([0-31]{2})([0-12]{2})([0-9]{4})\")) {\n dateFormat = \"ddMMyyyy\";\n } else if (tempDate.matches(\"([0-9]{4})([0-12]{2})([0-31]{2})\")) {\n dateFormat = \"yyyyMMdd\";\n } else if (tempDate.matches(\"([0-9]{4})([0-31]{2})([0-12]{2})\")) {\n dateFormat = \"yyyyddMM\";\n } else if (tempDate.matches(\"([0-31]{2})([a-z]{3})([0-9]{4})\")) {\n dateFormat = \"ddMMMyyyy\";\n } else if (tempDate.matches(\"([a-z]{3})([0-31]{2})([0-9]{4})\")) {\n dateFormat = \"MMMddyyyy\";\n } else if (tempDate.matches(\"([0-9]{4})([a-z]{3})([0-31]{2})\")) {\n dateFormat = \"yyyyMMMdd\";\n } else if (tempDate.matches(\"([0-9]{4})([0-31]{2})([a-z]{3})\")) {\n dateFormat = \"yyyyddMMM\";\n } else {\n return \"Pattern Not Added\";\n//add your required regex\n }\n try {\n String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));\n\n return formattedDate;\n } catch (Exception e) {\n //\n return \"\";\n }\n\n }\n" }, { "answer_id": 56907180, "author": "Pravin Bansal", "author_id": 6095444, "author_profile": "https://Stackoverflow.com/users/6095444", "pm_score": 0, "selected": false, "text": "public boolean isThisDateValid(String dateToValidate, String dateFromat){\n\n if(dateToValidate == null){\n return false;\n }\n\n SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);\n sdf.setLenient(false);\n\n try {\n\n //if not valid, it will throw ParseException\n Date date = sdf.parse(dateToValidate);\n System.out.println(date);\n\n } catch (ParseException e) {\n\n e.printStackTrace();\n return false;\n }\n\n return true;\n}\n" }, { "answer_id": 57268013, "author": "vijay", "author_id": 7682476, "author_profile": "https://Stackoverflow.com/users/7682476", "pm_score": 2, "selected": false, "text": "import java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeParseException;\npublic boolean isValidFormat(String dateString, String pattern) {\n boolean valid = true;\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);\n try {\n formatter.parse(dateString);\n } catch (DateTimeParseException e) {\n valid = false;\n }\n return valid;\n}\n" }, { "answer_id": 58209655, "author": "skay", "author_id": 560410, "author_profile": "https://Stackoverflow.com/users/560410", "pm_score": 0, "selected": false, "text": " public boolean isValidFormat(String source, String pattern) {\n SimpleDateFormat sd = new SimpleDateFormat(pattern);\n sd.setLenient(false);\n try {\n Date date = sd.parse(source);\n return date != null && sd.format(date).equals(source);\n } catch (Exception e) {\n return false;\n }\n}\n" }, { "answer_id": 68069005, "author": "SANAT", "author_id": 2024527, "author_profile": "https://Stackoverflow.com/users/2024527", "pm_score": 0, "selected": false, "text": "org.apache.commons.validator.GenericValidator public static boolean isValidDate(String value, String datePattern, boolean strict) {\n\n if (value == null\n || datePattern == null\n || datePattern.length() <= 0) {\n\n return false;\n }\n\n SimpleDateFormat formatter = new SimpleDateFormat(datePattern, Locale.ENGLISH);\n formatter.setLenient(false);\n\n try {\n formatter.parse(value);\n } catch(ParseException e) {\n return false;\n }\n\n if (strict && (datePattern.length() != value.length())) {\n return false;\n }\n\n return true;\n}\n" }, { "answer_id": 72899575, "author": "ucMedia", "author_id": 7756492, "author_profile": "https://Stackoverflow.com/users/7756492", "pm_score": 0, "selected": false, "text": "// month value is 1-based. e.g., 1 for January.\npublic static boolean isDateValid(int year, int month, int day) {\n Calendar calendar = Calendar.getInstance();\n try {\n calendar.setLenient(false);\n calendar.set(year, month-1, day);\n calendar.getTime();\n return true;\n } catch (Exception e) {\n return false;\n }\n}\n" }, { "answer_id": 73434373, "author": "Nagendra Rao", "author_id": 19813614, "author_profile": "https://Stackoverflow.com/users/19813614", "pm_score": 0, "selected": false, "text": " if (strDate != null && !strDate.isEmpty() && !strDate.equalsIgnoreCase(\" \")) {\n {\n\n SimpleDateFormat date = new SimpleDateFormat(\"dd/MM/yyyy\");\n date.setLenient(false);\n\n try {\n Date javaDate = date.parse(strDate);\n System.out.println(strDate + \" Valid Date format\");\n }\n\n catch (ParseException e) {\n System.out.println(strDate + \" Invalid Date format\");\n return false;\n }\n return true;\n }\n\n } else {\n System.out.println(strDate + \"----> Date is Null/Empty\");\n return false;\n }\n\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26595/" ]
226,935
<p>I came across a code snippet like this:</p> <p><code>Timestamp expiryDate = Timestamp.valueOf(dateStr + " " + "23:59:59.000"); </code></p> <p>Here dateStr is a string entered by the user in a form, in the format yyyy-mm-dd. Now the behavior of Timestamp.valueOf is such that it converts non-existent dates into appropriate proper dates. Say 31st June 2008 into 01st July 2008. </p> <p>How can I check in Java if the dateStr string is in fact a valid date ? I know I can manually do the check, but what I would like to know is whether any method is already available to do the same.</p>
[ { "answer_id": 69889085, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "java.util SimpleDateFormat java.sql.Timestamp java.util.Date java.time DateTimeFormatter ResolverStyle ResolverStyle.STRICT ResolverStyle.SMART import java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.format.DateTimeParseException;\nimport java.time.format.ResolverStyle;\nimport java.time.format.SignStyle;\nimport java.time.temporal.ChronoField;\nimport java.util.Locale;\nimport java.util.stream.Stream;\n\npublic class Main {\n public static void main(String[] args) {\n DateTimeFormatter dtf = \n new DateTimeFormatterBuilder()\n .appendValue(ChronoField.YEAR, 1, 4, SignStyle.NORMAL)\n .appendLiteral('-')\n .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL)\n .appendLiteral('-')\n .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)\n .appendLiteral(' ')\n .appendValue(ChronoField.HOUR_OF_DAY, 1, 2, SignStyle.NORMAL)\n .appendLiteral(':')\n .appendValue(ChronoField.MINUTE_OF_HOUR, 1, 2, SignStyle.NORMAL)\n .appendLiteral(':')\n .appendValue(ChronoField.SECOND_OF_MINUTE, 1, 2, SignStyle.NORMAL)\n .optionalStart()\n .appendLiteral('.')\n .appendFraction(ChronoField.NANO_OF_SECOND, 0, 3, false)\n .optionalEnd()\n .toFormatter(Locale.ENGLISH)\n .withResolverStyle(ResolverStyle.STRICT);\n \n // Test\n Stream.of(\n \"2008-06-31 23:59:59.000\",\n \"2008-06-30 23:59:59.000\",\n \"2008-6-30 23:59:59.000\",\n \"2008-6-8 23:59:59.000\",\n \"2008-6-8 2:59:59.000\",\n \"2008-6-8 23:5:59.000\",\n \"2008-6-8 23:59:9.000\",\n \"2008-06-30 23:59:59\"\n \n ).forEach (s -> {\n try {\n LocalDateTime ldt = LocalDateTime.parse(s, dtf);\n System.out.println(ldt);\n }catch(DateTimeParseException e) {\n System.out.printf(\"%s is an invalid date-time string.%n\", s);\n // ...\n }\n }); \n }\n}\n 2008-06-31 23:59:59.000 is an invalid date-time string.\n2008-06-30T23:59:59\n2008-06-30T23:59:59\n2008-06-08T23:59:59\n2008-06-08T02:59:59\n2008-06-08T23:05:59\n2008-06-08T23:59:09\n2008-06-30T23:59:59\n java.time java.sql.Timestamp LocalDateTime java.sql.Timestamp Timestamp#valueOf LocalDateTime now = LocalDateTime.now();\nTimestamp ts = Timestamp.valueOf(now);\n java.time" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
226,939
<p>I've been working with code synthesis xsd to generate an xml tree to ensure constinency of the xml output to the original xsd.</p> <p>After initial testing, everything looked ok but when I tried entering invalid values (correct type, but outside the defined range), the values were allowed.</p> <p>Although the xml is well formed and conforms to the types set in the xsd, it is not a valid xml wrt the schema.</p> <p>Has anybody else used this tool and/or come up across this problem?</p>
[ { "answer_id": 69889085, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "java.util SimpleDateFormat java.sql.Timestamp java.util.Date java.time DateTimeFormatter ResolverStyle ResolverStyle.STRICT ResolverStyle.SMART import java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.DateTimeFormatterBuilder;\nimport java.time.format.DateTimeParseException;\nimport java.time.format.ResolverStyle;\nimport java.time.format.SignStyle;\nimport java.time.temporal.ChronoField;\nimport java.util.Locale;\nimport java.util.stream.Stream;\n\npublic class Main {\n public static void main(String[] args) {\n DateTimeFormatter dtf = \n new DateTimeFormatterBuilder()\n .appendValue(ChronoField.YEAR, 1, 4, SignStyle.NORMAL)\n .appendLiteral('-')\n .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL)\n .appendLiteral('-')\n .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)\n .appendLiteral(' ')\n .appendValue(ChronoField.HOUR_OF_DAY, 1, 2, SignStyle.NORMAL)\n .appendLiteral(':')\n .appendValue(ChronoField.MINUTE_OF_HOUR, 1, 2, SignStyle.NORMAL)\n .appendLiteral(':')\n .appendValue(ChronoField.SECOND_OF_MINUTE, 1, 2, SignStyle.NORMAL)\n .optionalStart()\n .appendLiteral('.')\n .appendFraction(ChronoField.NANO_OF_SECOND, 0, 3, false)\n .optionalEnd()\n .toFormatter(Locale.ENGLISH)\n .withResolverStyle(ResolverStyle.STRICT);\n \n // Test\n Stream.of(\n \"2008-06-31 23:59:59.000\",\n \"2008-06-30 23:59:59.000\",\n \"2008-6-30 23:59:59.000\",\n \"2008-6-8 23:59:59.000\",\n \"2008-6-8 2:59:59.000\",\n \"2008-6-8 23:5:59.000\",\n \"2008-6-8 23:59:9.000\",\n \"2008-06-30 23:59:59\"\n \n ).forEach (s -> {\n try {\n LocalDateTime ldt = LocalDateTime.parse(s, dtf);\n System.out.println(ldt);\n }catch(DateTimeParseException e) {\n System.out.printf(\"%s is an invalid date-time string.%n\", s);\n // ...\n }\n }); \n }\n}\n 2008-06-31 23:59:59.000 is an invalid date-time string.\n2008-06-30T23:59:59\n2008-06-30T23:59:59\n2008-06-08T23:59:59\n2008-06-08T02:59:59\n2008-06-08T23:05:59\n2008-06-08T23:59:09\n2008-06-30T23:59:59\n java.time java.sql.Timestamp LocalDateTime java.sql.Timestamp Timestamp#valueOf LocalDateTime now = LocalDateTime.now();\nTimestamp ts = Timestamp.valueOf(now);\n java.time" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23553/" ]
226,953
<p>If I have hundreds/thousands of client computers WCP'ing to my server, should I respond with a '200 OK' type message stating that I received the data and stored it in the db successfully?</p> <p>Is this already built-into WCF?</p>
[ { "answer_id": 228116, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 4, "selected": false, "text": "InstanceContext [ServiceContract]\ninterface IMyServiceContract\n{\n [OperationContract] \n void DoSomeThing(InputMessage Message);\n}\n [ServiceContract]\ninterface IMyServiceContract\n{\n [OperationContract(IsOneWay = true)] \n void DoSomeThing(InputMessage Message);\n}\n [ServiceContract(CallbackContract = typeof(IMyContractCallback))]\ninterface IMyContract\n{\n [OperationContract(IsOneWay=true)] \n void DoSomeThing(InputMessage Message);\n}\n\npublic interface IMyContractCallback\n{\n [OperationContract(IsOneWay = true)]\n void ServiceResponse(string result); \n}\n public class CallbackHandler : IMyContractCallback \n{\n #region IEchoContractCallback Members\n\n public void ServiceResponse(string result)\n {\n //Do something with the response\n }\n\n #endregion\n}\n\n// And in the client when you set up the service call:\n\nInstanceContext instanceContext = new InstanceContext(new CallbackHandler());\nMyContractClient client = new MyContractClient(instanceContext);\n\nInputMessage msg = new InputMessage();\n\nclient.DoSomething(msg); \n class MyContractImplementation : IMyContract\n{\n public void DoSomeThing(MyMessage Message)\n {\n\n string responseMessage;\n\n try\n {\n //Write to the database\n responseMessage = \"The database call was good!\";\n }\n catch (Exception ex)\n {\n responseMessage = ex.Message;\n }\n\n Callback.ServiceResponse(responseMessage);\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
226,970
<blockquote> <p>This question has been preserved for historical reasons, but it is not considered on-topic, so don't use it as an excuse to post something similar.</p> <p>More info at <a href="https://stackoverflow.com/faq">https://stackoverflow.com/faq</a>.</p> </blockquote> <hr> <p>For me to read code and learn, not to play...</p> <p>...of course ;-)</p>
[ { "answer_id": 227660, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 4, "selected": false, "text": ". . . . . . . . . .\n. . . . S . . . . .\n. . * . . . . * . .\n. . . . . . . . . *\n. * . . . * . . . .\n. . . . . . . . . .\n. . . E . . . . . .\n. . . . . * . . . .\n. . . . . . . . . . \n. . . * . . . . . .\n" }, { "answer_id": 2129654, "author": "xadoc", "author_id": 179225, "author_profile": "https://Stackoverflow.com/users/179225", "pm_score": 2, "selected": false, "text": " To compile and install you need:\n\n Qt >= 4.4\n FreePascal >= 2.2.0\n SDL >= 1.2.5\n SDL_net >= 1.2.5\n SDL_mixer >= 1.2\n SDL_image >= 1.2\n SDL_ttf >= 2.0\n CMake >= 2.6.0\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28722/" ]
226,976
<p>I have a git repository with multiple branches. </p> <p>How can I know which branches are already merged into the master branch?</p>
[ { "answer_id": 226993, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "git merge-base git branch -d" }, { "answer_id": 227026, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 12, "selected": true, "text": "git branch --merged master git branch --merged git branch --no-merged -a -r" }, { "answer_id": 19538778, "author": "xxjjnn", "author_id": 849697, "author_profile": "https://Stackoverflow.com/users/849697", "pm_score": 4, "selected": false, "text": "git branch -r | xargs -t -n 1 git branch -r --contains\n tig origin/feature/someones-decaying-feature\n" }, { "answer_id": 19538972, "author": "iberbeu", "author_id": 2114871, "author_profile": "https://Stackoverflow.com/users/2114871", "pm_score": 5, "selected": false, "text": "gitk --all" }, { "answer_id": 23929250, "author": "angularsen", "author_id": 134761, "author_profile": "https://Stackoverflow.com/users/134761", "pm_score": 3, "selected": false, "text": "554 Andreas:MyRepo(develop)$ git flow start tmp\nSwitched to a new branch 'feature/tmp'\n\nSummary of actions:\n- A new branch 'feature/tmp' was created, based on 'develop'\n- You are now on branch 'feature/tmp'\n\nNow, start committing on your feature. When done, use:\n\n git flow feature finish tmp\n\n555 Andreas:MyRepo(feature/tmp)$ git flow finish\nSwitched to branch 'develop'\nYour branch is up-to-date with 'if/develop'.\nAlready up-to-date.\n\n[post-flow-feature-finish] Delete remote branch? (Y/n)\nDeleting remote branch: origin/feature/tmp.\n\nDeleted branch feature/tmp (was 02a3356).\n\nSummary of actions:\n- The feature branch 'feature/tmp' was merged into 'develop'\n- Feature branch 'feature/tmp' has been locally deleted\n- You are now on branch 'develop'\n\n556 Andreas:ScDesktop (develop)$\n NAME=$1\nORIGIN=$2\nBRANCH=$3\n\n# Delete remote branch\n# Allows us to read user input below, assigns stdin to keyboard\nexec < /dev/tty\n\nwhile true; do\n read -p \"[post-flow-feature-finish] Delete remote branch? (Y/n) \" yn\n if [ \"$yn\" = \"\" ]; then\n yn='Y' \n fi\n case $yn in\n [Yy] ) \n echo -e \"\\e[31mDeleting remote branch: $2/$3.\\e[0m\" || exit \"$?\"\n git push $2 :$3; \n break;;\n [Nn] ) \n echo -e \"\\e[32mKeeping remote branch.\\e[0m\" || exit \"$?\"\n break;;\n * ) echo \"Please answer y or n for yes or no.\";;\n esac\ndone\n\n# Stop reading user input (close STDIN)\nexec <&-\nexit 0\n gru \ngls origin/feature/foo\nglf \"my message\"\n alias gru='git remote update -p'\nalias glf=findCommitByMessage\n\nfindCommitByMessage() {\n git log -i --grep=\"$1\"\n}\n" }, { "answer_id": 40011122, "author": "Hari", "author_id": 6146917, "author_profile": "https://Stackoverflow.com/users/6146917", "pm_score": 5, "selected": false, "text": "git merge-base <commit> <commit> git merge-base <commit-hash-step1> <commit-hash-step2>" }, { "answer_id": 49434212, "author": "Carl G", "author_id": 39396, "author_profile": "https://Stackoverflow.com/users/39396", "pm_score": 5, "selected": false, "text": "git-is-merged develop feature/new-feature git-is-merged () {\n merge_destination_branch=$1\n merge_source_branch=$2\n\n merge_base=$(git merge-base $merge_destination_branch $merge_source_branch)\n merge_source_current_commit=$(git rev-parse $merge_source_branch)\n if [[ $merge_base = $merge_source_current_commit ]]\n then\n echo $merge_source_branch is merged into $merge_destination_branch\n return 0\n else\n echo $merge_source_branch is not merged into $merge_destination_branch\n return 1\n fi\n}\n" }, { "answer_id": 53325693, "author": "radke", "author_id": 622016, "author_profile": "https://Stackoverflow.com/users/622016", "pm_score": 3, "selected": false, "text": "$ git fetch && git branch -r --merged | grep -q origin/master && echo Incorporates origin/master || echo Out of date from origin/master\n [alias]\n current = !git branch -r --merged | grep -q $1 && echo Incorporates $1 || echo Out of date from $1 && :\n $ git current origin/master\n" }, { "answer_id": 57146858, "author": "avivamg", "author_id": 4692049, "author_profile": "https://Stackoverflow.com/users/4692049", "pm_score": 5, "selected": false, "text": "git branch <flag[-r/-a/none]> --merged master git branch <flag[-r/-a/none]> --merged master | wc -l -a -r <emptyFlag> git branch -r --merged master" }, { "answer_id": 64879695, "author": "customcommander", "author_id": 1244884, "author_profile": "https://Stackoverflow.com/users/1244884", "pm_score": 4, "selected": false, "text": "origin/integration origin/integration integration git pull git fetch origin/integration git for-each-ref --merged=origin/integration --format=\"%(refname:short)\" refs/heads/\n# ^ ^ ^\n# A B C\nbranch1\nbranch2\nbranch3\nbranch4\n origin/integration heads origin/integration git for-each-ref --no-merged=origin/integration --format=\"%(committerdate:short) %(refname:short)\" --sort=committerdate refs/heads\n# ^ ^ ^ ^\n# A B C D\n2020-01-14 branch10\n2020-01-16 branch11\n2020-01-17 branch12\n2020-01-30 branch13\n origin/integration heads" }, { "answer_id": 70389345, "author": "Harish Ambady", "author_id": 1258949, "author_profile": "https://Stackoverflow.com/users/1258949", "pm_score": 3, "selected": false, "text": "git merge-base --is-ancestor <source branch name> master && echo \"merged\" || echo \"not merged\"\n" }, { "answer_id": 74049970, "author": "cjohnson318", "author_id": 923797, "author_profile": "https://Stackoverflow.com/users/923797", "pm_score": 0, "selected": false, "text": "git branch git branch --merged main diff <(git branch) <(git branch --merged main)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
226,977
<p>I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a <em>good</em> thing.</p> <p>Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?</p>
[ { "answer_id": 227023, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "ArrayList<String> myList = new ArrayList<String>();\n List<String> myList = new ArrayList<String>();\n myList" }, { "answer_id": 227036, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 6, "selected": false, "text": "public class ABC\n{\n public void doDiskAccess() {...}\n}\n ABC abc = new ABC();\n\nabc. doDiskAccess();\n public class XYZ\n{\n public void doNetworkAccess() {...}\n}\n if(config.isNetwork()) new XYZ().doNetworkAccess();\nelse new ABC().doDiskAccess();\n public interface Runnable\n{\n public void run();\n}\n\npublic class ABC implements Runnable\n{\n public void run() {...}\n}\n\npublic class XYZ implements Runnable\n{\n public void run() {...}\n}\n Runnable obj = config.isNetwork() ? new XYZ() : new ABC();\n\nobj.run();\n" }, { "answer_id": 227046, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "class FormA \n{\n FormB fb = new FormB( this );\n\n ...\n fb.Show();\n}\n\nclass FormB \n{\n FormA parent;\n\n public FormB( FormA parent )\n {\n this.parent = parent;\n } \n}\n" }, { "answer_id": 227051, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": 3, "selected": false, "text": " [ServiceDependency]\n public ICustomizableGridService CustomizableGridService\n {\n protected get { return _customizableGridService; }\n set { _customizableGridService = value; }\n }\n" }, { "answer_id": 227334, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 8, "selected": false, "text": "CartContents Order Order public class CartEntry\n{\n public float Price;\n public int Quantity;\n}\n\npublic class CartContents\n{\n public CartEntry[] items;\n}\n\npublic class Order\n{\n private CartContents cart;\n private float salesTax;\n\n public Order(CartContents cart, float salesTax)\n {\n this.cart = cart;\n this.salesTax = salesTax;\n }\n\n public float OrderTotal()\n {\n float cartTotal = 0;\n for (int i = 0; i < cart.items.Length; i++)\n {\n cartTotal += cart.items[i].Price * cart.items[i].Quantity;\n }\n cartTotal += cartTotal*salesTax;\n return cartTotal;\n }\n}\n OrderTotal CartContents CartEntry List<CartEntry> Order public class CartEntry\n{\n public float Price;\n public int Quantity;\n\n public float GetLineItemTotal()\n {\n return Price * Quantity;\n }\n}\n\npublic class CartContents\n{\n public CartEntry[] items;\n\n public float GetCartItemsTotal()\n {\n float cartTotal = 0;\n foreach (CartEntry item in items)\n {\n cartTotal += item.GetLineItemTotal();\n }\n return cartTotal;\n }\n}\n\npublic class Order\n{\n private CartContents cart;\n private float salesTax;\n\n public Order(CartContents cart, float salesTax)\n {\n this.cart = cart;\n this.salesTax = salesTax;\n }\n\n public float OrderTotal()\n {\n return cart.GetCartItemsTotal() * (1.0f + salesTax);\n }\n}\n" }, { "answer_id": 227957, "author": "Owen", "author_id": 425, "author_profile": "https://Stackoverflow.com/users/425", "pm_score": 5, "selected": false, "text": "public ICatcher\n{\n public void Catch();\n}\n public CatcherA : ICatcher\n{\n public void Catch()\n {\n console.writeline(\"You Caught it\");\n }\n\n}\npublic CatcherB : ICatcher\n{\n public void Catch()\n {\n console.writeline(\"Your brother Caught it\");\n }\n\n}\n CatcherA CatcherB Catch public CatchService\n{\n private CatcherA catcher = new CatcherA();\n\n public void CatchService()\n {\n catcher.Catch();\n }\n\n}\n CatchService CatcherA CatcherA public CatchService\n{\n private ICatcher catcher;\n\n public void CatchService(ICatcher catcher)\n {\n this.catcher = catcher;\n catcher.Catch();\n }\n}\n CatchService CatchService catchService = new CatchService(new CatcherA());\n CatchService catchService = new CatchService(new CatcherB());\n Catch CatcherA CatcherB" }, { "answer_id": 228747, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "this.some_object = new SomeObject();\n void InjectSomeObject(ISomeObject so) { // note we require an interface, not concrete implementation\n this.some_object = so;\n}\n" }, { "answer_id": 27795160, "author": "Abhishek Aggarwal", "author_id": 1074100, "author_profile": "https://Stackoverflow.com/users/1074100", "pm_score": 2, "selected": false, "text": "new package interface_package.loose_coupling;\n\npublic class A {\n\nvoid display(InterfaceClass obji)\n{\n obji.display();\n System.out.println(obji.getVar());\n}\n}\n package interface_package.loose_coupling;\n\npublic class B implements InterfaceClass{\n\nprivate String var=\"variable Interface\";\n\npublic String getVar() {\n return var;\n}\n\npublic void setVar(String var) {\n this.var = var;\n}\n\n@Override\npublic void display() {\n // TODO Auto-generated method stub\n System.out.println(\"Display Method Called\");\n}\n}\n package interface_package.loose_coupling;\n\npublic interface InterfaceClass {\n\nvoid display();\nString getVar();\n}\n package interface_package.loose_coupling;\n\npublic class MainClass {\n\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n\n A obja=new A();\n B objb=new B();\n obja.display(objb); //Calling display of A class with object of B class \n \n}\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30454/" ]
226,978
<p>What is the best way to sync up two lists each of which may contain items not in the other? As shown the lists are not sorted - although if necessary sorting them first would not be an issue.</p> <pre><code>List 1 = a,b,c,e List 2 = b,e,c,d </code></pre> <p>Using the lists above, I'm looking for a solution that will write out to a spreadsheet in two columns:</p> <pre><code>a b b c c d e e </code></pre>
[ { "answer_id": 227292, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Const adVarChar = 200 'the SQL datatype is varchar\n\n'Create arrays fron the lists\nasL1 = Split(\"a,b,c,\", \",\")\nasL2 = Split(\"b,e,c,d\", \",\")\n\n'Create a disconnected recordset\nSet rs = CreateObject(\"ADODB.RECORDSET\")\nrs.Fields.append \"Srt\", adVarChar, 25\nrs.Fields.append \"L1\", adVarChar, 25\nrs.Fields.append \"L2\", adVarChar, 25\n\nrs.CursorType = adOpenStatic\nrs.Open\n\n'Add list 1 to the recordset\nFor i = 0 To UBound(asL1)\n rs.AddNew Array(\"Srt\", \"L1\"), Array(asL1(i), asL1(i))\n rs.Update\nNext\n\n'Add list 2\nFor i = 0 To UBound(asL2)\n rs.MoveFirst\n rs.Find \"L1='\" & asL2(i) & \"'\"\n\n If rs.EOF Then\n rs.AddNew Array(\"Srt\", \"L2\"), Array(asL2(i), asL2(i))\n Else\n rs.Fields(\"L2\") = asL2(i)\n End If\n\n rs.Update\nNext\n\nrs.Sort = \"Srt\"\n\n'Add the data to the active sheet\nSet wks = Application.ActiveWorkbook.ActiveSheet\n\nrs.MoveFirst\n\nintRow = 1\nDo\n For intField = 1 To rs.Fields.Count - 1\n wks.Cells(intRow, intField + 1) = rs.Fields(intField).Value\n Next intField\n\n rs.MoveNext\n intRow = intRow + 1\nLoop Until rs.EOF = True\n" }, { "answer_id": 227464, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "Option Explicit\n\nPublic Sub OutputLists()\n\nDim list1, list2\nDim dict1 As Dictionary, dict2 As Dictionary\nDim ky\nDim cel As Range\n\n Set dict1 = DictionaryFromArray(Array(\"a\", \"b\", \"c\", \"e\"))\n Set dict2 = DictionaryFromArray(Array(\"b\", \"e\", \"c\", \"d\"))\n\n Set cel = ActiveSheet.Range(\"A1\")\n\n For Each ky In dict1.Keys\n PutRow cel, ky, True, dict2.Exists(ky)\n If dict2.Exists(ky) Then\n dict2.Remove ky\n End If\n Set cel = cel.Offset(1, 0)\n Next\n\n For Each ky In dict2\n PutRow cel, ky, False, True\n Set cel = cel.Offset(1, 0)\n Next\n\nEnd Sub\n\nPrivate Sub PutRow(cel As Range, val As Variant, in1 As Boolean, in2 As Boolean)\n\nDim arr(1 To 2)\n\n If in1 Then arr(1) = val\n If in2 Then arr(2) = val\n cel.Resize(1, 2) = arr\n\nEnd Sub\n\nPrivate Function DictionaryFromArray(arr) As Dictionary\n\nDim val\n\n Set DictionaryFromArray = New Dictionary\n For Each val In arr\n DictionaryFromArray.Add val, Nothing\n Next\n\nEnd Function\n" }, { "answer_id": 227932, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "Dim C As New Collection,i As Long, j As Long\nReDim LL(UBound(L1) + UBound(L2), 2) As String 'output array\n\nFor i = 1 To UBound(L1)\n On Error Resume Next 'try adding to collection\n C.Add C.Count + 1, L1(i) 'store sequence number,ie 1,2,3,4,...\n On Error GoTo 0\n j = C(L1(i)) 'look up sequence number\n LL(j, 1) = L1(i)\nNext i\n\nFor i = 1 To UBound(L2) 'same for L2\n On Error Resume Next\n C.Add C.Count + 1, L2(i)\n On Error GoTo 0\n j = C(L2(i))\n LL(j, 2) = L2(i)\nNext i\n\n'Result is in LL, number of rows is C.Count\nRange(\"Results\").Resize(UBound(LL, 1), 2) = LL\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30473/" ]
226,980
<p>I have a Google Map that suddenly stopped working for no apparent reason (I hadn't touched the code for months, but the wrapper code from our CMS may have changed without Corporate telling me).</p> <p><a href="http://www.democratandchronicle.com/section/builder" rel="nofollow noreferrer">http://www.democratandchronicle.com/section/builder</a></p> <p>(sorry about the nasty HTML outside the map, most of that comes from our corporate parent...)</p> <p>I've narrowed it down to this part of my <code>drawMarker</code> function:</p> <pre><code>GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html, { maxWidth: 500 }); }); </code></pre> <p>Of note:</p> <ul> <li><code>alert(html);</code> displays the correct HTML for the infowindow.</li> <li>The HTML in the html variable is indeed valid.</li> <li>The click event is firing (confirmed by <code>alert('test');</code> within it)</li> <li>Another map I host on the same site <a href="http://www.democratandchronicle.com/garagesales" rel="nofollow noreferrer">works fine</a>, despite similar code.</li> <li>No JavaScript errors in Firebug or IE that I can see.</li> </ul> <p>I've been bashing my head against this for a while. What am I missing?</p>
[ { "answer_id": 227397, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "GEvent.addListener(marker, 'click', function() {\nmarker.openInfoWindowHtml(html+'', { maxWidth: 500 });\n});\n" }, { "answer_id": 228719, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "http://maps.google.com/maps?file=api&v=2.xd&key=XXXXX" }, { "answer_id": 444853, "author": "Keith Fitzgerald", "author_id": 49611, "author_profile": "https://Stackoverflow.com/users/49611", "pm_score": 1, "selected": false, "text": "GEvent.addListener(marker, 'click', function() {\n this.openInfoWindowHtml(html, { maxWidth: 500 });\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902010/" ]
226,981
<p>I have an <code>IList&lt;T&gt;</code> that I need to sort, and I would rather not copy the list if possible. I've noticed that <code>ArrayList</code> has an <code>Adapter</code> static method that wraps the passed list without copying it, but this takes an <code>IList</code> and I have an <code>IList&lt;T&gt;</code>. Is it safe to cast from a <code>System.Collections.Generic.IList&lt;T&gt;</code> to a <code>System.Collections.IList</code> and just use the <code>Adapter</code> method?</p> <p>Note that this is .Net 2.0, so LINQ is not an option.</p>
[ { "answer_id": 226992, "author": "Mike C.", "author_id": 3799, "author_profile": "https://Stackoverflow.com/users/3799", "pm_score": 5, "selected": true, "text": "public class LanguageDto : IComparable {\n private String name;\n public string Name { get { return name; } set { name = value; } }\n\n public LanguageDto(string name) {\n this.name = name;\n }\n\n #region IComparable Members\n public int CompareTo(object obj) {\n if (obj is LanguageDto) {\n LanguageDto language = (LanguageDto)obj;\n return this.name.CompareTo(language.name);\n }\n throw new ArgumentException(string.Format(\"Cannot compare a LanguageDto to an {0}\", obj.GetType().ToString()));\n }\n #endregion\n}\n ArrayList.Adapter((IList)languages).Sort();\n" }, { "answer_id": 227013, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "object[] array = new object[count];\nthis.CopyTo(index, array, 0, count);\nArray.Sort(array, 0, count, comparer);\nfor (int i = 0; i < count; i++)\n{\n this._list[i + index] = array[i];\n}\n IList<object> unsorted = ...\nList<object> sorted = new List<object>(unsorted);\nsorted.Sort(); \nfor (int i = 0; i < unsorted.Countt; i++)\n{\n unsorted[i] = sorted[i];\n}\n" }, { "answer_id": 227065, "author": "Gord", "author_id": 12560, "author_profile": "https://Stackoverflow.com/users/12560", "pm_score": 0, "selected": false, "text": "var sortedProducts =\n from p in products\n orderby p.ProductName\n select p;\n\nObjectDumper.Write(sortedProducts);\n string[] digits = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" };\n\nvar sortedDigits =\n from d in digits \n orderby d.Length, d\n select d;\n" }, { "answer_id": 227443, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 1, "selected": false, "text": "interface ISortableList<T> : IList<T>\n{\n void Sort();\n void Sort(IComparer<T> comparer);\n}\n\nclass SortableList<T> : List<T>, ISortableList<T> { }\n\n/* usage */\nvoid Example(ISortedList<T> list)\n{\n list.Sort();\n list.Sort(new MyCustomerComparer());\n}\n void Example(IList<T> list)\n{\n list = new List<T>(list).Sort();\n}\n" }, { "answer_id": 5311258, "author": "Rohit", "author_id": 660495, "author_profile": "https://Stackoverflow.com/users/660495", "pm_score": -1, "selected": false, "text": "IList<object> unsorted = ...\nIList<object> sortedList = unsorted.Orderby(x => x.Tostring()).Tolist();\n" }, { "answer_id": 32208526, "author": "Nullius", "author_id": 1302710, "author_profile": "https://Stackoverflow.com/users/1302710", "pm_score": 0, "selected": false, "text": "public class DynamicComparer<T> : IComparer<T>\n{\n\n private Func<T, int> calculateFunc;\n private int calculateMultiplier;\n\n private Func<T, T, int> compareFunc;\n public DynamicComparer(Func<T, int> calculateFunc, bool reverse = false)\n {\n if (calculateFunc == null)\n {\n throw new Exception(\"Delegate function 'calculateFunc' cannot be null.\");\n }\n\n this.calculateFunc = calculateFunc;\n this.calculateMultiplier = reverse ? -1 : 1;\n this.compareFunc = null;\n }\n\n public DynamicComparer(Func<T, T, int> compareFunc)\n {\n if (calculateFunc == null)\n {\n throw new Exception(\"Delegate function 'compareFunc' cannot be null.\");\n }\n\n this.calculateFunc = null;\n this.compareFunc = compareFunc;\n }\n\n public int Compare(T x, T y)\n {\n if (calculateFunc != null)\n {\n return (calculateFunc(x) - calculateFunc(y)) * this.calculateMultiplier;\n }\n if (compareFunc != null)\n {\n return compareFunc(x, y);\n }\n\n throw new Exception(\"Compare not possible because neither a Compare or a Calculate function was specified.\");\n }\n}\n public delegate TResult Func<T, TResult>(T t);\npublic delegate TResult Func<T, U, TResult>(T t, U u);\n myList.Sort(new DynamicComparer<MyClass>(x => x.MyIntProperty) // Ascending\nmyList.Sort(new DynamicComparer<MyClass>(x => x.MyIntProperty, true) // Descending\n [TestClass()]\npublic class DynamicComparerTU\n{\n [TestMethod()]\n public void SortIntList()\n {\n // Arrange\n dynamic myIntArray = new int[] {\n 4,\n 1,\n 9,\n 0,\n 4,\n 7\n };\n dynamic myIntList = new List<int>(myIntArray);\n\n // Act\n int temp = 0;\n for (int write = 0; write <= myIntArray.Length - 1; write++)\n {\n for (int sort = 0; sort <= myIntArray.Length - 2; sort++)\n {\n if (myIntArray(sort) > myIntArray(sort + 1))\n {\n temp = myIntArray(sort + 1);\n myIntArray(sort + 1) = myIntArray(sort);\n myIntArray(sort) = temp;\n }\n }\n }\n\n myIntList.Sort(new DynamicComparer<int>(x => x));\n\n // Assert\n Assert.IsNotNull(myIntList);\n Assert.AreEqual(myIntArray.Length, myIntList.Count);\n for (int i = 0; i <= myIntArray.Length - 1; i++)\n {\n Assert.AreEqual(myIntArray(i), myIntList(i));\n }\n }\n\n [TestMethod()]\n public void SortStringListByLength()\n {\n // Arrange\n dynamic myStringArray = new string[] {\n \"abcd\",\n \"ab\",\n \"abcde\",\n \"a\",\n \"abc\"\n };\n dynamic myStringList = new List<string>(myStringArray);\n\n // Act\n myStringList.Sort(new DynamicComparer<string>(x => x.Length));\n\n // Assert\n Assert.IsNotNull(myStringList);\n Assert.AreEqual(5, myStringList.Count);\n Assert.AreEqual(\"a\", myStringList(0));\n Assert.AreEqual(\"ab\", myStringList(1));\n Assert.AreEqual(\"abc\", myStringList(2));\n Assert.AreEqual(\"abcd\", myStringList(3));\n Assert.AreEqual(\"abcde\", myStringList(4));\n }\n\n [TestMethod()]\n public void SortStringListByLengthDescending()\n {\n // Arrange\n dynamic myStringArray = new string[] {\n \"abcd\",\n \"ab\",\n \"abcde\",\n \"a\",\n \"abc\"\n };\n dynamic myStringList = new List<string>(myStringArray);\n\n // Act\n myStringList.Sort(new DynamicComparer<string>(x => x.Length, true));\n\n // Assert\n Assert.IsNotNull(myStringList);\n Assert.AreEqual(5, myStringList.Count);\n Assert.AreEqual(\"abcde\", myStringList(0));\n Assert.AreEqual(\"abcd\", myStringList(1));\n Assert.AreEqual(\"abc\", myStringList(2));\n Assert.AreEqual(\"ab\", myStringList(3));\n Assert.AreEqual(\"a\", myStringList(4));\n }\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9323/" ]
226,986
<p>I've used several apps now that launch the itunes store directly from the app. I'm even using some on my 2.1 iPod 2G.</p> <p>I know there's a bug in 2.1 that prevents appstore links from working in safari, but somehow people are launching the appstore directly, not even through safari.</p> <p>How do you do this? Is it an undocumented openURL feature?</p>
[ { "answer_id": 227343, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 3, "selected": false, "text": "UIApplication openURL" }, { "answer_id": 1374791, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 4, "selected": false, "text": "- (IBAction)gotoReviews:(id)sender\n{\n NSString *str = @\"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa\";\n str = [NSString stringWithFormat:@\"%@/wa/viewContentsUserReviews?\", str]; \n str = [NSString stringWithFormat:@\"%@type=Purple+Software&id=\", str];\n\n // Here is the app id from itunesconnect\n str = [NSString stringWithFormat:@\"%@289382458\", str]; \n\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];\n}\n" }, { "answer_id": 4122425, "author": "user160917", "author_id": 160917, "author_profile": "https://Stackoverflow.com/users/160917", "pm_score": 5, "selected": false, "text": "[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@\"itms://itunes.com/apps/appname\"]];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@\"itms://itunes.com/apps/developername\"]];\n" }, { "answer_id": 16054940, "author": "NielsKoole", "author_id": 1630528, "author_profile": "https://Stackoverflow.com/users/1630528", "pm_score": 3, "selected": false, "text": "NSString *appId = @\"app id\";\nNSString *endPoint = [NSString stringWithFormat:@\"phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@&mt=8\", appId];\nNSString *link = [NSString stringWithFormat:@\"itms-apps://%@\", endPoint];\n\n[[UIApplication sharedApplication] openURL:[NSURL URLWithString:link]];\n" }, { "answer_id": 21066454, "author": "Charlie Seligman", "author_id": 646818, "author_profile": "https://Stackoverflow.com/users/646818", "pm_score": 0, "selected": false, "text": "- (void)showOurAppsInAppStore\n{ \n NSString *searchUrl = nil;\n // iPad\n if ([DeviceController isDeviceAnIpad]) {\n searchUrl = @\"itms-apps://itunes.apple.com/us/artist/seligman-ventures-ltd/id326161338\";\n }\n // iPhone / iPod Touch\n else {\n // iOS 7+\n if ([DeviceController isDeviceOperatingSystemAtleast:@\"7.0\"]) {\n searchUrl = @\"itms-apps://itunes.apple.com/artist/seligman-ventures-ltd/id326161338\";\n }\n // iOS 6\n else if ([DeviceController isDeviceOperatingSystemAtleast:@\"6.0\"]) {\n searchUrl = @\"itms-apps://ax.itunes.apple.com/artist/seligman-ventures-ltd/id326161338\";\n }\n // Pre iOS 6\n else {\n NSString *companyName = @\"Seligman Ventures\";\n searchUrl = [NSString stringWithFormat:@\"http://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?WOURLEncoding=ISO8859_1&lang=1&output=lm&country=US&term=%@&media=software\", [companyName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n }\n }\n\n [[UIApplication sharedApplication] openURL: [NSURL URLWithString:searchUrl]];\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8597/" ]
227,005
<p>If I have two UIColors, what's the best way to draw an even gradient between them over an arbitrarily-sized area?</p> <p>I am guessing you would create a UIView subclass and use the CG drawing methods in the drawRect method. I just don't know which ones, or if there are any pitfalls to watch out for, like performance. Has anyone done this?</p>
[ { "answer_id": 15302226, "author": "Anton Chikin", "author_id": 435680, "author_profile": "https://Stackoverflow.com/users/435680", "pm_score": 6, "selected": false, "text": "#import <QuartzCore/QuartzCore.h> \n- (void) setGradient {\n CAGradientLayer *gradient = [CAGradientLayer layer];\n gradient.frame = self.view.bounds;\n gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];\n [self.view.layer insertSublayer:gradient atIndex:0]; \n}\n" }, { "answer_id": 24437621, "author": "Jbryson", "author_id": 877032, "author_profile": "https://Stackoverflow.com/users/877032", "pm_score": 0, "selected": false, "text": "UILabel UITextView UITextField drawRect UILabel UITextView UITextField" }, { "answer_id": 27236831, "author": "tybro0103", "author_id": 202875, "author_profile": "https://Stackoverflow.com/users/202875", "pm_score": 0, "selected": false, "text": "layerClass class GradientView: UIView {\n\n var colorA : UIColor = UIColor.greenColor() {\n didSet { updateGradient() }\n }\n var colorB : UIColor = UIColor.blueColor() {\n didSet { updateGradient() }\n }\n\n override class func layerClass() -> AnyClass {\n return CAGradientLayer.self\n }\n\n required init(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n updateGradient()\n }\n\n func updateGradient() {\n if let gLayer = layer as? CAGradientLayer {\n gLayer.colors = [colorA.CGColor, colorB.CGColor]\n }\n }\n\n}\n" }, { "answer_id": 28135666, "author": "Reza_Rg", "author_id": 1567034, "author_profile": "https://Stackoverflow.com/users/1567034", "pm_score": 2, "selected": false, "text": " var view : UIView = UIView(frame: CGRectMake(0, 0, 320, 100))\n var g : CAGradientLayer = CAGradientLayer()\n g.frame = gradientView.bounds\n g.colors = [\"000000\".UIColor.CGColor , \"111111\".UIColor.CGColor]\n view.layer.insertSublayer(g, atIndex: 0)\n UIColor() hex color rgb color" }, { "answer_id": 32965625, "author": "Amit Shelgaonkar", "author_id": 4865339, "author_profile": "https://Stackoverflow.com/users/4865339", "pm_score": 0, "selected": false, "text": "-(void)applyGradientEffecttoView:(UIView *)aView\n {\n // Create the colors\n\n UIColor *darkOp = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0];\n UIColor *lightOp =[UIColor colorWithRed:255.0f green:255.0f blue:255.0f alpha:0.0];\n\n // Create the gradient\n CAGradientLayer *gradient = [CAGradientLayer layer];\n\n // Set colors\n gradient.colors = [NSArray arrayWithObjects:\n (id)lightOp.CGColor,\n (id)darkOp.CGColor,\n nil];\n gradient.locations = [NSArray arrayWithObjects:\n [NSNumber numberWithFloat:0.0f],\n [NSNumber numberWithFloat:0.5],\n nil];\n\n // Set bounds\n gradient.frame = aView.bounds;\n\n // Add the gradient to the view\n\n [aView.layer insertSublayer:gradient atIndex:0];\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544/" ]
227,007
<p>In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?</p> <p>In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.</p> <p><code>SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';</code></p>
[ { "answer_id": 227044, "author": "thoroughly", "author_id": 8943, "author_profile": "https://Stackoverflow.com/users/8943", "pm_score": 3, "selected": false, "text": "public static Date stripTimePortion(Date timestamp) {\n long msInDay = 1000 * 60 * 60 * 24; // Number of milliseconds in a day\n long msPortion = timestamp.getTime() % msInDay;\n return new Date(timestamp.getTime() - msPortion);\n}\n" }, { "answer_id": 227049, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 7, "selected": true, "text": "Date date = new Date(); // timestamp now\nCalendar cal = Calendar.getInstance(); // get calendar instance\ncal.setTime(date); // set cal to date\ncal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight\ncal.set(Calendar.MINUTE, 0); // set minute in hour\ncal.set(Calendar.SECOND, 0); // set second in minute\ncal.set(Calendar.MILLISECOND, 0); // set millis in second\nDate zeroedDate = cal.getTime(); // actually computes the new Date\n" }, { "answer_id": 227186, "author": "Domchi", "author_id": 29192, "author_profile": "https://Stackoverflow.com/users/29192", "pm_score": 0, "selected": false, "text": "java.util.Date originalDate = new java.util.Date();\njava.sql.Date wantedDate = new java.sql.Date(originalDate.getTime());\n" }, { "answer_id": 227595, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 4, "selected": false, "text": "DateUtils.truncate" }, { "answer_id": 13462986, "author": "Torben Kohlmeier", "author_id": 1836528, "author_profile": "https://Stackoverflow.com/users/1836528", "pm_score": 2, "selected": false, "text": "GregorianCalendar now = new GregorianCalendar();\nGregorianCalendar calendar = new GregorianCalendar(\n now.get(GregorianCalendar.YEAR), now.get(GregorianCalendar.MONTH), \n now.get(GregorianCalendar.DAY_OF_MONTH));\n" }, { "answer_id": 22518375, "author": "Ziya", "author_id": 1325331, "author_profile": "https://Stackoverflow.com/users/1325331", "pm_score": 2, "selected": false, "text": "import org.apache.commons.lang.time.DateUtils;\n\nDate myDate = new Date();\nSystem.out.println(myDate); \nSystem.out.println(DateUtils.truncate(myDate, Calendar.DATE));\n" }, { "answer_id": 31340625, "author": "Richard Gomes", "author_id": 62131, "author_profile": "https://Stackoverflow.com/users/62131", "pm_score": 0, "selected": false, "text": "currentDate currentTime informedDate informedTime schedulable /**\n * This class splits the current date/time (now!) and an informed date/time into their components:\n * <lu>\n * <li>schedulable: if the informed date/time is in the present (now!) or in future.</li>\n * <li>informedDate: the date (only) part of the informed date/time</li>\n * <li>informedTime: the time (only) part of the informed date/time</li>\n * <li>currentDate: the date (only) part of the current date/time (now!)</li>\n * <li>currentTime: the time (only) part of the current date/time (now!)</li>\n * </lu>\n */\npublic class ScheduleDateTime {\n public final boolean schedulable;\n public final long millis;\n public final java.util.Date informedDate;\n public final java.util.Date informedTime;\n public final java.util.Date currentDate;\n public final java.util.Date currentTime;\n\n public ScheduleDateTime(long millis) {\n final long now = System.currentTimeMillis();\n this.schedulable = (millis > -1L) && (millis >= now);\n\n final TimeZoneUtils tz = new TimeZoneUtils();\n\n final java.util.Date dmillis = new java.util.Date( (millis > -1L) ? millis : now );\n final java.time.ZonedDateTime zdtmillis = java.time.ZonedDateTime.ofInstant(dmillis.toInstant(), java.time.ZoneId.systemDefault());\n final java.util.Date zdmillis = java.util.Date.from(tz.tzdate(zdtmillis));\n final java.util.Date ztmillis = new java.util.Date(tz.tztime(zdtmillis));\n\n final java.util.Date dnow = new java.util.Date(now);\n final java.time.ZonedDateTime zdtnow = java.time.ZonedDateTime.ofInstant(dnow.toInstant(), java.time.ZoneId.systemDefault());\n final java.util.Date zdnow = java.util.Date.from(tz.tzdate(zdtnow));\n final java.util.Date ztnow = new java.util.Date(tz.tztime(zdtnow));\n\n this.millis = millis;\n this.informedDate = zdmillis;\n this.informedTime = ztmillis;\n this.currentDate = zdnow;\n this.currentTime = ztnow;\n }\n}\n\n\n\npublic class TimeZoneUtils {\n\n public java.time.Instant tzdate() {\n final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();\n return tzdate(zdtime);\n }\n public java.time.Instant tzdate(java.time.ZonedDateTime zdtime) {\n final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);\n final java.time.Instant instant = zddate.toInstant();\n return instant;\n }\n\n public long tztime() {\n final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();\n return tztime(zdtime);\n }\n public long tztime(java.time.ZonedDateTime zdtime) {\n final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);\n final long millis = zddate.until(zdtime, java.time.temporal.ChronoUnit.MILLIS);\n return millis;\n }\n}\n" }, { "answer_id": 41723114, "author": "MAbraham1", "author_id": 212950, "author_profile": "https://Stackoverflow.com/users/212950", "pm_score": 0, "selected": false, "text": "import java.util.Calendar;\nimport java.util.Date;\npublic class Util {\n/**\n * Returns an imprecise date/timestamp. \n * @param date\n * @return the timestamp with zeroized seconds/milliseconds\n */\npublic static Date getImpreciseDate(Date date) {\n Calendar cal = Calendar.getInstance(); // get calendar instance\n cal.setTime(date);// set cal to date\n cal.set(Calendar.SECOND, 0); // zeroize seconds \n cal.set(Calendar.MILLISECOND, 0); // zeroize milliseconds\n return cal.getTime();\n}\n\npublic static void main(String[] args){\n Date now = new Date();\n now.setTime(System.currentTimeMillis()); // set time to now\n System.out.println(\"Precise date: \" + Util.getImpreciseDate(now));\n System.out.println(\"Imprecise date: \" + Util.getImpreciseDate(now));\n}\n}\n" }, { "answer_id": 57574338, "author": "Sabir Khan", "author_id": 3850730, "author_profile": "https://Stackoverflow.com/users/3850730", "pm_score": 0, "selected": false, "text": "Calendar java.time.ZonedDateTime java.sql.Timestamp ZonedDateTime Timestamp Timestamp.valueOf(ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).toLocalDateTime())\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
227,022
<p>I would like to check my JavaScript files without going to <a href="http://www.jslint.com/" rel="noreferrer">JSLint</a> web site.<br> Is there a desktop version of this tool for Windows?</p>
[ { "answer_id": 2466261, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 2, "selected": false, "text": " (function(){if(!JSLINT(WScript.StdIn.ReadAll(),.....\n (function(){\n var filename = \"stdin\";\n var content= \"\";\n if (WScript.Arguments.length > 0){\n filename = WScript.Arguments(0);\n var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n //var file = fso.GetFile(filename);\n var fs = fso.OpenTextFile(filename, 1);\n content = fs.ReadAll();\n fs.Close();\n fso = null;\n fs = null;\n } else {\n content = WScript.StdIn.ReadAll();\n }\n if(!JSLINT(content,{passfail:false})){\n WScript.StdErr.WriteLine(\"JSLINT\");\n for (var i=0; i<JSLINT.errors.length; i++) {\n // sample error msg:\n // sprintf.js(53,42) JSLINT: Use the array literal notation [].\n var e=JSLINT.errors[i];\n if (e !== null){\n var line = (typeof e.line == \"undefined\")?'0':e.line;\n WScript.StdErr.WriteLine(filename + '(' +line+','+e.character+') JSLINT: '+e.reason);\n WScript.StdErr.WriteLine(' ' + (e.evidence||'').replace(/^\\s*(\\S*(\\s+\\S+)*)\\s*$/,\"$1\"));\n }\n }}}());\n cscript.exe jslint.js MyJavascriptModule.js \n JSLINT\nMyJavascriptModule.js(7,17) JSLINT: 'xml' is already defined.\n var xml = new ActiveXObject(\"Microsoft.XMLHTTP\");\nMyJavascriptModule.js(10,5) JSLINT: 'xml' used out of scope.\n xml.open(\"GET\", url, true);\nMyJavascriptModule.js(11,9) JSLINT: 'xml' used out of scope.\n if (xml.overrideMimeType) {\nMyJavascriptModule.js(12,9) JSLINT: 'xml' used out of scope.\n xml.overrideMimeType('text/plain; charset=x-user-defined');\nMyJavascriptModule.js(14,9) JSLINT: 'xml' used out of scope.\n xml.setRequestHeader('Accept-Charset', 'x-user-defined');\nMyJavascriptModule.js(17,5) JSLINT: 'xml' used out of scope.\n xml.onreadystatechange = function() {\nMyJavascriptModule.js(28,5) JSLINT: 'xml' used out of scope.\n xml.send('');\nMyJavascriptModule.js(34,16) JSLINT: Expected '{' and instead saw 'url'.\n if (proxy) url = proxy + '?url=' + encodeURIComponent(url);\nMyJavascriptModule.js(51,16) JSLINT: Expected '{' and instead saw 'url'.\n if (proxy) url = proxy + '?url=' + encodeURIComponent(url);\n" }, { "answer_id": 7710960, "author": "Nathan MacInnes", "author_id": 489885, "author_profile": "https://Stackoverflow.com/users/489885", "pm_score": 2, "selected": false, "text": "var options = {\n browser : true,\n plusplus : true,\n unparam : true,\n maxlen : 120,\n indent : 4 // etc\n};\nif (JSLINT(myCode, options)) {\n document.write('Passed!');\n} else {\n document.write('Failed! :(');\n}\ndocument.write('<ul>');\nfor (i = 0; i < JSLINT.errors.length; i++) {\n document.write('<li><b>' + JSLINT.errors[i].line + ':</b> ' + JSLINT.errors[i].reason + '</li>');\n}\ndocument.write('</ul>');\n" }, { "answer_id": 18792902, "author": "feklee", "author_id": 282729, "author_profile": "https://Stackoverflow.com/users/282729", "pm_score": 0, "selected": false, "text": "C:\\jslint-reporter C:\\jslint-reporter>node wrapper.js --upgrade\n C:\\Temp>node C:\\jslint-reporter\\wrapper.js missing_semicolon.js\nmissing_semicolon.js:1:10:Expected ';' and instead saw 'console'.\nmissing_semicolon.js:2:1:'console' was used before it was defined.\n C:\\>npm -g install jslint\n C:\\Temp>jslint missing_semicolon.js\n\nmissing_semicolon.js\n #1 Expected ';' and instead saw 'console'.\n var x = 5 // Line 1, Pos 10\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
227,037
<p>I have two tables Institutions and Results and I want to see if there are any results for institutions that way I can exclude the ones that don't have results.</p> <p>Can I get better performance using a JOIN or using EXISTS?</p> <p>Thank you,<br> -Nimesh</p>
[ { "answer_id": 227067, "author": "BrynJ", "author_id": 29538, "author_profile": "https://Stackoverflow.com/users/29538", "pm_score": 0, "selected": false, "text": "SELECT t1.* FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.id = t2.id WHERE t2.id IS NULL\n" }, { "answer_id": 227073, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": false, "text": "select Institutions.institution_name \nfrom Institutions\ninner join Results on (Institutions.institution_id = Results.institution_id)\n if exists(select 1 from Results where institution_id = 2)\n print \"institution_id 2 has results\"\nelse\n print \"institution_id 2 does not have results\"\n" }, { "answer_id": 227237, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "select *\nfrom\n table_one t1\nwhere exists (\n select *\n from table_two t2\n where t2.id_field = t1.id_field\n )\norder by t1.id_field desc\n\n\nselect t1.*\nfrom \n table_one t1\n ,table_two t2\nwhere t1.id_field = t2.id_field\norder by t1.id_field desc \n" }, { "answer_id": 227322, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 1, "selected": false, "text": "SELECT *\n FROM Institutions\n WHERE InstitutionID NOT IN (\n SELECT DISTINCT InstitutionID\n FROM Results\n )\n" }, { "answer_id": 227363, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 2, "selected": false, "text": "SELECT\n MyTable.MyTableID\nFROM\n dbo.MyTable T1\nLEFT OUTER JOIN dbo.MyOtherTable T2 ON\n T2.MyTableID = T1.MyTableID\nWHERE\n T2.MyOtherTableID IS NULL\n SELECT\n MyTable.MyTableID\nFROM\n dbo.MyTable T1\nWHERE NOT EXISTS (SELECT * FROM MyOtherTable T2 WHERE T2.MyTableID = T1.MyTableID)\n" }, { "answer_id": 227737, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 1, "selected": false, "text": "INSTITUTION EXISTS() joins, IN(), and EXISTS()" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
227,064
<p>I am wondering what server control people generally use for surrounding and separating blocks of related controls and content in a Web Forms scenario. Often times I need to surround a block of HTML and related Server controls with a 'panel' that I can show or hide based upon some UI logic in the code behind. I am usually faced with either using a Panel, however this doesn't work if I need to surround multiple TR's in a table for example because the Panel renders as a div which is invalid inside a Table tag. In this situation I usually just set each TR to runat server and show/hide each of them individually, but there must be a better way. I have seen the PlaceHolder control used for this scenario, but wanted to know if anyone does this or has any other suggestions.</p>
[ { "answer_id": 227082, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<table>\n <tr>\n ....\n </tr>\n\n <% if( ShowSecretRow ) { %>\n\n <tr>\n <td>shhh!</td>\n </tr>\n\n <% } %>\n</table>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218/" ]
227,066
<p>I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why.</p> <p>For example, the second CaselessIs method calls the first:</p> <pre><code>public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable&lt;string&gt; compareTo) { foreach(string comparison in compareTo) { if (s.CaselessIs(comparison)) { return true; } } return false; } </code></pre> <p>Would it be more appropriate to not do this? The downside would be that it violates DRY.</p> <pre><code>public static bool CaselessIs(this string s, string compareTo) { return string.Compare(s, compareTo, true) == 0; } public static bool CaselessIs(this string s, IEnumerable&lt;string&gt; compareTo) { foreach(string comparison in compareTo) { if (string.Compare(s, comparison, true) == 0) { return true; } } return false; } </code></pre>
[ { "answer_id": 227106, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 4, "selected": true, "text": "extended.ExtensionMethod(foo);\n StaticType.ExtensionMethod(extended, foo);\n" }, { "answer_id": 227107, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "public static bool CaselessIs(this string s, IEnumerable<string> compareTo)\n{\n foreach(string comparison in compareTo)\n {\n if (Extensions.CaselessIs(s, comparison))\n {\n return true;\n }\n }\n\n return false;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
227,078
<p>I'd love to create a "back" left-arrow-bezel button in a <code>UIToolbar</code>.</p> <p>As far as I can tell, the only way to get one of these is to leave <code>UINavigationController</code> at default settings and it uses one for the left bar item. But there's no way I can find to create one as a <code>UIBarButtonItem</code>, so I can't make one in a standard <code>UIToolbar</code>, even though they're very similar to <code>UINavigationBar</code>s.</p> <p>I could manually create it with button images, but I can't find the source images anywhere. They have alpha-channel edges, so screenshotting and cutting won't get very versatile results.</p> <p>Any ideas beyond screenshotting for every size and color scheme I intend to use?</p> <p><strong>Update:</strong> PLEASE STOP dodging the question and suggesting that I shouldn't be asking this and should be using <code>UINavigationBar</code>. My app is Instapaper Pro. It shows only a bottom toolbar (to save space and maximize readable content area), and I wish to put a left-arrow-shaped Back button in the bottom.</p> <p>Telling me that I shouldn't need to do this <strong>is not an answer</strong> and certainly doesn't deserve a bounty.</p>
[ { "answer_id": 227135, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 0, "selected": false, "text": "[UIImage stretchableImageWithLeftCapWidth:topCapHeight:]" }, { "answer_id": 574863, "author": "PyjamaSam", "author_id": 55453, "author_profile": "https://Stackoverflow.com/users/55453", "pm_score": 8, "selected": true, "text": "// Creates a back button instead of default behaviour (displaying title of previous screen)\nUIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"back_arrow.png\"]\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(backAction)];\n\ntipsDetailViewController.navigationItem.leftBarButtonItem = backButton;\n[backButton release];\n" }, { "answer_id": 580341, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "UINavigationController removeFromSuperview retain removeFromSuperview release" }, { "answer_id": 1766704, "author": "Andrew Arrow", "author_id": 148736, "author_profile": "https://Stackoverflow.com/users/148736", "pm_score": 2, "selected": false, "text": " UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @\"Title\" style:UIBarButtonItemStylePlain \n target:self action:@selector(foo)];\n\n UIColor* darkBlue = RGBCOLOR(109, 132, 162);\n\n TTShapeStyle* style = [TTShapeStyle styleWithShape:[TTRoundedLeftArrowShape shapeWithRadius:4.5] next:\n [TTShadowStyle styleWithColor:RGBCOLOR(255,255,255) blur:1 offset:CGSizeMake(0, 1) next:\n [TTReflectiveFillStyle styleWithColor:darkBlue next:\n [TTBevelBorderStyle styleWithHighlight:[darkBlue shadow]\n shadow:[darkBlue multiplyHue:1 saturation:0.5 value:0.5]\n width:1 lightSource:270 next:\n [TTInsetStyle styleWithInset:UIEdgeInsetsMake(0, -1, 0, -1) next:\n [TTBevelBorderStyle styleWithHighlight:nil shadow:RGBACOLOR(0,0,0,0.15)\n width:1 lightSource:270 next:nil]]]]]];\n\n TTView* view = [[[TTView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)] autorelease];\n view.backgroundColor = [UIColor clearColor];\n view.style = style;\n backButton.customView = view;\n\n\n self.navigationItem.leftBarButtonItem = backButton;\n" }, { "answer_id": 3406308, "author": "Cameron Lowell Palmer", "author_id": 410867, "author_profile": "https://Stackoverflow.com/users/410867", "pm_score": 6, "selected": false, "text": "NSString *backArrowString = @\"\\U000025C0\\U0000FE0E\"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR\n\nUIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:nil action:nil];\nself.navigationItem.leftButtonItem = backBarButtonItem;\n" }, { "answer_id": 3426793, "author": "AndrewS", "author_id": 173964, "author_profile": "https://Stackoverflow.com/users/173964", "pm_score": 5, "selected": false, "text": "initWithCustomView BarButtonItem toolbar // create button\nUIButton* backButton = [UIButton buttonWithType:101]; // left-pointing shape!\n[backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];\n[backButton setTitle:@\"Back\" forState:UIControlStateNormal];\n\n// create button item -- possible because UIButton subclasses UIView!\nUIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];\n\n// add to toolbar, or to a navbar (you should only have one of these!)\n[toolbar setItems:[NSArray arrayWithObject:backItem]];\nnavItem.leftBarButtonItem = backItem;\n" }, { "answer_id": 3639703, "author": "marikaner", "author_id": 433926, "author_profile": "https://Stackoverflow.com/users/433926", "pm_score": 2, "selected": false, "text": "// initialize button and button view\nUIButton *backButton = [UIButton buttonWithType:101];\nUIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backButton.frame.size.width, backButton.frame.size.height)];\n\n[backButton addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside];\n[backButton setTitle:@\"Back\" forState:UIControlStateNormal];\n[backButtonView addSubview:backButton];\n\n// set buttonview as custom view for bar button item\nUIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];\nself.navigationItem.leftBarButtonItem = backButtonItem;\n\n// push item to navigationbar items\n[self.navigationController.navigationBar setItems:[NSArray arrayWithObject:backButtonItem]];\n" }, { "answer_id": 3985773, "author": "maralbjo", "author_id": 156395, "author_profile": "https://Stackoverflow.com/users/156395", "pm_score": 2, "selected": false, "text": "// Creates a back button instead of default behaviour (displaying title of previous screen)\n UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"back_arrow.png\"]\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(backAction)];\n\n tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;\n [backButton release];\n" }, { "answer_id": 4854786, "author": "quantumpotato", "author_id": 172232, "author_profile": "https://Stackoverflow.com/users/172232", "pm_score": 3, "selected": false, "text": " self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;\n" }, { "answer_id": 10748447, "author": "Steve", "author_id": 1043343, "author_profile": "https://Stackoverflow.com/users/1043343", "pm_score": 2, "selected": false, "text": "// Generate the background images\nUIImage *stretchableBackButton = [[UIImage imageNamed:@\"UINavigationBarDefaultBack.png\"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];\nUIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@\"UINavigationBarDefaultBackPressed.png\"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];\n// Setup the UIButton\nUIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];\n[backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];\n[backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];\nNSString *buttonTitle = NSLocalizedString(@\"Back\", @\"Back\");\n[backButton setTitle:buttonTitle forState:UIControlStateNormal];\n[backButton setTitle:buttonTitle forState:UIControlStateSelected];\nbackButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position\nNSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);\n[backButton setFrame:CGRectMake(0, 0, width, 29)];\nbackButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];\n[backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];\n// Now add the button as a custom UIBarButtonItem\nUIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];\nself.navigationItem.leftBarButtonItem = backButtonItem;\n" }, { "answer_id": 12072890, "author": "Mj.B", "author_id": 1556934, "author_profile": "https://Stackoverflow.com/users/1556934", "pm_score": -1, "selected": false, "text": "UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@\"Back\"\n style:UIBarButtonItemStyleBordered\n target:self\n action:@selector(yourSelectorGoesHere:)];\nself.navigationItem.backBarButtonItem = backButton;\n" }, { "answer_id": 18874211, "author": "Alexey", "author_id": 744015, "author_profile": "https://Stackoverflow.com/users/744015", "pm_score": 5, "selected": false, "text": "UINavigationBarBackIndicatorDefault imageView.tint = [UIColor redColor];\nimageView.image = [[UIImage imageNamed:@\"UINavigationBarBackIndicatorDefault\"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];\n -(void)viewWillAppear:(BOOL)animated{\n UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"UINavigationBarBackIndicatorDefault\"]];\n [imageView setTintColor:[UIColor redColor]];\n UILabel *label=[[UILabel alloc] init];\n [label setTextColor:[UIColor redColor]];\n [label setText:@\"Blog\"];\n [label sizeToFit];\n\n int space=6;\n label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);\n UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];\n\n view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);\n [view addSubview:imageView];\n [view addSubview:label];\n\n UIButton *button=[[UIButton alloc] initWithFrame:view.frame];\n [button addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];\n [view addSubview:button];\n\n [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{\n label.alpha = 0.0;\n CGRect orig=label.frame;\n label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);\n label.alpha = 1.0;\n label.frame=orig;\n } completion:nil];\n\n UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];\n}\n\n- (void) handleBack:(id)sender{\n}\n UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBack:)];\n[view addGestureRecognizer:tap];\n[view setUserInteractionEnabled:YES];\n" }, { "answer_id": 25557645, "author": "Gabriel Jensen", "author_id": 416618, "author_profile": "https://Stackoverflow.com/users/416618", "pm_score": 1, "selected": false, "text": "UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 70, 20)];\n\n// Add the disclosure\nCGRect frm;\nUITableViewCell *disclosure = [[UITableViewCell alloc] init];\ndisclosure.transform = CGAffineTransformScale(CGAffineTransformIdentity, -1, 1);\nfrm = self.btnBack.bounds;\ndisclosure.frame = CGRectMake(frm.origin.x, frm.origin.y, frm.size.width-25, frm.size.height);\ndisclosure.accessoryType = UITableViewCellAccessoryDisclosureIndicator;\ndisclosure.userInteractionEnabled = NO;\n[self.btnBack addSubview:disclosure];\n\n// Add the label\nUILabel *lbl = [[UILabel alloc] init];\nfrm = CGRectOffset(self.btnBack.bounds, 15, 0);\nlbl.frame = frm;\nlbl.textAlignment = NSTextAlignmentCenter;\nlbl.text = @\"BACK\";\n[self addSubview:lbl];\n" }, { "answer_id": 34803540, "author": "machoota", "author_id": 1822154, "author_profile": "https://Stackoverflow.com/users/1822154", "pm_score": 3, "selected": false, "text": "- (void)drawRect:(CGRect)rect {\n float width = rect.size.width;\n float height = rect.size.height;\n CGContextRef context = UIGraphicsGetCurrentContext();\n\n CGContextBeginPath(context);\n CGContextMoveToPoint(context, width * 5.0/6.0, height * 0.0/10.0);\n CGContextAddLineToPoint(context, width * 0.0/6.0, height * 5.0/10.0);\n CGContextAddLineToPoint(context, width * 5.0/6.0, height * 10.0/10.0);\n CGContextAddLineToPoint(context, width * 6.0/6.0, height * 9.0/10.0);\n CGContextAddLineToPoint(context, width * 2.0/6.0, height * 5.0/10.0);\n CGContextAddLineToPoint(context, width * 6.0/6.0, height * 1.0/10.0);\n CGContextClosePath(context);\n\n CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);\n CGContextFillPath(context);\n}\n" }, { "answer_id": 41550133, "author": "Bart van Kuik", "author_id": 1085556, "author_profile": "https://Stackoverflow.com/users/1085556", "pm_score": 0, "selected": false, "text": "let prevButtonItem = UIBarButtonItem(title: \"\\u{25C0}\", style: .plain, target: self, action: #selector(prevButtonTapped))\nlet nextButtonItem = UIBarButtonItem(title: \"\\u{25B6}\", style: .plain, target: self, action: #selector(nextButtonTapped))\nself.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]\n" }, { "answer_id": 42454113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "// create button\n var backButton = UIButton(type: 101)\n\n // left-pointing shape!\n backButton.addTarget(self, action: #selector(self.backAction), for: .touchUpInside)\n backButton.setTitle(\"Back\", for: .normal)\n\n // create button item -- possible because UIButton subclasses UIView!\n var backItem = UIBarButtonItem(customView: backButton)\n\n // add to toolbar, or to a navbar (you should only have one of these!)\n toolbar.items = [backItem]\n navItem.leftBarButtonItem = backItem\n" }, { "answer_id": 61438985, "author": "rbaldwin", "author_id": 8197946, "author_profile": "https://Stackoverflow.com/users/8197946", "pm_score": 1, "selected": false, "text": "import UIKit\n\nclass CustomBackButton: UIBarButtonItem {\n\n convenience init(target: Any, selector: Selector) {\n\n // Create UIButton\n let button = UIButton(frame: .zero)\n\n // Customise Title\n button.setTitle(\"Back\", for: .normal)\n button.setTitleColor(.systemBlue, for: .normal)\n button.titleLabel?.font = UIFont.systemFont(ofSize: 17)\n\n // Customise Image\n let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)\n let image = UIImage(systemName: \"chevron.left\", withConfiguration: config)\n button.setImage(image, for: .normal)\n\n // Add Target\n button.addTarget(target, action: selector, for: .touchUpInside)\n\n // Customise Spacing to match system Back button\n button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)\n button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)\n\n self.init(customView: button)\n }\n}\n UIToolbarItem UINavigationItem override func viewDidLoad() {\n super.viewDidLoad()\n\n // UIToolbar Item\n let barBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))\n let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)\n navigationController?.setToolbarHidden(false, animated: false)\n toolbarItems = [barBackButton, flexSpace]\n\n // Navigation Item\n let navBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))\n navigationItem.leftBarButtonItem = navBackButton\n}\n\n@objc func backButtonTapped() {\n print(\"Back tapped\")\n}\n CustomBackButton // Put the image of the right side of the button\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30480/" ]
227,081
<p>I have ListView with Grouping Items. Grouping uses custom GroupStyle (Expander). I would like to have check box which will Expand and collapse all groups when. It works fine untill I click manually on the group header and expand or collapse that group. After clicking that particular group stops to respond on check box selection. Looks like binding is broken after user manually clicks on the group.</p> <p>Please advise what I am doing wrong.</p> <p>Thanks a lot.</p> <p>Sincerely, Vlad.</p> <pre><code>&lt;Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'&gt; &lt;Window.Resources&gt; &lt;XmlDataProvider x:Key="MyData" XPath="/Info"&gt; &lt;x:XData&gt; &lt;Info xmlns=""&gt; &lt;Item Name="Item 1" Category="Cat1" /&gt; &lt;Item Name="Item 2" Category="Cat1" /&gt; &lt;Item Name="Item 3" Category="Cat2" /&gt; &lt;Item Name="Item 4" Category="Cat2" /&gt; &lt;Item Name="Item 5" Category="Cat2" /&gt; &lt;Item Name="Item 6" Category="Cat3" /&gt; &lt;/Info&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}"&gt; &lt;CollectionViewSource.GroupDescriptions&gt; &lt;PropertyGroupDescription PropertyName="@Category" /&gt; &lt;/CollectionViewSource.GroupDescriptions&gt; &lt;/CollectionViewSource&gt; &lt;ControlTemplate x:Key="ListTemplate" TargetType="ListView"&gt; &lt;ListView BorderThickness="0" ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}' DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"&gt; &lt;ListView.GroupStyle&gt; &lt;GroupStyle&gt; &lt;GroupStyle.ContainerStyle&gt; &lt;Style TargetType="{x:Type GroupItem}"&gt; &lt;Setter Property="Margin" Value="0,0,0,5" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type GroupItem}"&gt; &lt;Expander IsExpanded="{Binding IsChecked, ElementName=chkExpandAll, Mode=OneWay}"&gt; &lt;Expander.Header&gt; &lt;DockPanel&gt; &lt;TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100" /&gt; &lt;TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}" /&gt; &lt;/DockPanel&gt; &lt;/Expander.Header&gt; &lt;Expander.Content&gt; &lt;ItemsPresenter /&gt; &lt;/Expander.Content&gt; &lt;/Expander&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/GroupStyle.ContainerStyle&gt; &lt;/GroupStyle&gt; &lt;/ListView.GroupStyle&gt; &lt;/ListView&gt; &lt;/ControlTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel&gt; &lt;CheckBox Name="chkExpandAll" IsChecked="True" Content="Expand All" /&gt; &lt;ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath="@Name" BorderThickness="1" Template="{StaticResource ListTemplate}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre>
[ { "answer_id": 230107, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": true, "text": "<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'\n xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>\n <Window.Resources>\n <XmlDataProvider x:Key=\"MyData\" XPath=\"/Info\">\n <x:XData>\n <Info xmlns=\"\">\n <Item Name=\"Item 1\" Category=\"Cat1\" />\n <Item Name=\"Item 2\" Category=\"Cat1\" />\n <Item Name=\"Item 3\" Category=\"Cat2\" />\n <Item Name=\"Item 4\" Category=\"Cat2\" />\n <Item Name=\"Item 5\" Category=\"Cat2\" />\n <Item Name=\"Item 6\" Category=\"Cat3\" />\n </Info>\n </x:XData>\n </XmlDataProvider>\n\n <CollectionViewSource x:Key='src' Source=\"{Binding Source={StaticResource MyData}, XPath=Item}\">\n <CollectionViewSource.GroupDescriptions>\n <PropertyGroupDescription PropertyName=\"@Category\" />\n </CollectionViewSource.GroupDescriptions>\n </CollectionViewSource>\n\n <ControlTemplate x:Key=\"ListTemplate\" TargetType=\"ListView\">\n <ListView BorderThickness=\"0\"\n ItemsSource='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}'\n DisplayMemberPath=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}\">\n <ListView.GroupStyle>\n <GroupStyle>\n <GroupStyle.ContainerStyle>\n <Style TargetType=\"{x:Type GroupItem}\">\n <Setter Property=\"Margin\" Value=\"0,0,0,5\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type GroupItem}\">\n <StackPanel>\n <Expander Name=\"exp\" IsExpanded=\"{Binding IsChecked, ElementName=chkExpandAll, Mode=TwoWay, UpdateSourceTrigger=Explicit}\">\n <Expander.Header>\n <DockPanel>\n <TextBlock FontWeight=\"Bold\" Text=\"{Binding Path=Name}\" Margin=\"5,0,0,0\" Width=\"100\" />\n <TextBlock FontWeight=\"Bold\" Text=\"{Binding Path=ItemCount}\" />\n </DockPanel>\n </Expander.Header>\n <Expander.Content>\n <ItemsPresenter />\n </Expander.Content>\n </Expander>\n </StackPanel>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </GroupStyle.ContainerStyle>\n </GroupStyle>\n </ListView.GroupStyle>\n </ListView>\n </ControlTemplate>\n </Window.Resources>\n\n <StackPanel>\n <CheckBox Name=\"chkExpandAll\" Content=\"Expand All\" />\n <ListView ItemsSource='{Binding Source={StaticResource src}}' DisplayMemberPath=\"@Name\" BorderThickness=\"1\" Template=\"{StaticResource ListTemplate}\" />\n </StackPanel>\n\n</Window>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30038/" ]
227,083
<p>I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net? I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.</p>
[ { "answer_id": 227123, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 5, "selected": true, "text": "myInt = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);\n" }, { "answer_id": 227166, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": "Dim i as Integer \n\ni = (((bits(0) Or (bits(1) << 8)) Or (bits(2) << &H10)) Or (bits(3) << &H18))\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
227,101
<p>I have somewhat of a staging server on the public internet running copies of the production code for a few websites. I'd really not like it if the staging sites get indexed. </p> <p>Is there a way I can modify my httpd.conf on the staging server to block search engine crawlers? </p> <p>Changing the robots.txt wouldn't really work since I use scripts to copy the same code base to both servers. Also, I would rather not change the virtual host conf files either as there is a bunch of sites and I don't want to have to remember to copy over a certain setting if I make a new site.</p>
[ { "answer_id": 1278647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<IfModule mod_rewrite.c>\n RewriteEngine on\n\n # Dissuade web spiders from crawling the staging site\n RewriteCond %{HTTP_HOST} ^staging\\.example\\.com$\n RewriteRule ^robots.txt$ robots-staging.txt [L]\n</IfModule>\n <IfModule mod_rewrite.c>\n RewriteEngine on\n\n # Redirect web spiders to a robots.txt file elsewhere (possibly unreliable)\n RewriteRule ^robots.txt$ http://www.example.com/robots-staging.txt [R]\n</IfModule>\n" }, { "answer_id": 7364999, "author": "jsdalton", "author_id": 99289, "author_profile": "https://Stackoverflow.com/users/99289", "pm_score": 6, "selected": true, "text": "User-agent: *\nDisallow: /\n /var/www/html/robots.txt # Exclude all robots\n<Location \"/robots.txt\">\n SetHandler None\n</Location>\nAlias /robots.txt /path/to/robots.txt\n SetHandler" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24988/" ]
227,121
<p>Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.</p> <pre><code>foreach(UserControl uc in plhMediaBuys.Controls) { uc.PulblicPropertyIWantAccessTo; } </code></pre>
[ { "answer_id": 227127, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 3, "selected": false, "text": "foreach(UserControl uc in plhMediaBuys.Controls)\n{\n if (uc is MySpecificType)\n {\n return (uc as MySpecificType).PulblicPropertyIWantAccessTo;\n }\n}\n" }, { "answer_id": 227133, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 4, "selected": true, "text": "foreach(UserControl uc in plhMediaBuys.Controls) {\n MyControl c = uc as MyControl;\n if (c != null) {\n c.PublicPropertyIWantAccessTo;\n }\n}\n" }, { "answer_id": 227139, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "foreach(UserControl uc in plhMediaBuys.Controls)\n{\n ParticularUCType myControl = uc as ParticularUCType;\n if (myControl != null)\n {\n // do stuff with myControl.PulblicPropertyIWantAccessTo;\n }\n}\n if( uc is ParticularUCType ) // one cast to test if it is the type\n{\n ParticularUCType myControl = (ParticularUCType)uc; // second cast\n ParticularUCType myControl = uc as ParticularUCType; // same deal this way\n // do stuff with myControl.PulblicPropertyIWantAccessTo;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18785/" ]
227,129
<p>I am trying to dynamically load the contents of a div tag with a .cfm page that contains a cfchart in png format. When the user clicks on a link, I am using the load function to put the .cfm page into the div.</p> <pre><code>$("#bank").bind("click", function(){ $("#chartx").load("bank.cfm"); }); </code></pre> <p>I can get this to come up perfectly in Firefox, but not in IE6. It gives no error messages.</p>
[ { "answer_id": 227178, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": 0, "selected": false, "text": "$(\"#bank\").bind(\"click\", function(){\n $.get(\"bank.cfm\", function(data){\n $(\"#chartx\").html(data);\n });\n});\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30485/" ]
227,132
<p>Is it possible to use the asp templating engine (With the partial code-behind class, dynamic &lt;% ... %> blocks and such) to generate non HTML? I want to have a clean and maintainable way to generate code dynamically. (Specifically, I want to generate LaTeX code populated with values from a database.) </p> <p>Currently my LaTeX templates are resource strings with placeholders that I string.replace with the database values. This solution rapidly became very difficult to maintain and clean. I'd really like to use the dynamic blocks from aspx markup, but I'm not sure a) whether aspx will throw a fit when the output isn't HTML, or b) how to actually render the result into a .tex file.</p> <p>The generating code itself is located in a C# .dll. We're using .NET 3.5</p> <p>Is this possible? Thanks in advance. </p>
[ { "answer_id": 227203, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 4, "selected": true, "text": "public override bool Execute()\n{\n bool success = false;\n\n //read in the template:\n string template = File.ReadAllText(this.TemplatePath);\n\n //replace tags with property and item group values:\n ProjectHelper helper = new ProjectHelper(this);\n template = helper.ResolveProjectItems(template);\n\n //copy the template to a temp file:\n this._tempFilePath = Path.GetTempFileName();\n File.WriteAllText(this._tempFilePath, template);\n\n //shell out to the exe:\n ProcessHelper.Run(this, TextTransform.ToolPath, TextTransform.ExeName, string.Format(TextTransform.ArgumentFormat, this.OutputPath, this._tempFilePath));\n success = true;\n\n return success;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26626/" ]
227,140
<p>I have need to write an application which uses a speech recognition engine -- either the built in vista one, or a third party one -- that can display a word or phrase, and recognise when the user reads it (or an approximation of it). I also need to be able to switch quickly between languages, without changing the language of the operating system.</p> <p>The users will be using the system for very short periods. The application needs to work without the requirement of first training the recognition engine to the users' voices.</p> <p>It would also be fantastic if this could work on Windows XP or lesser versions of Windows Vista.</p> <p>Optionally, the system needs to be able to read information on the screen back to the user, in the user's selected language. I can work around this specification using pre-recorded voice-overs, but the preferred method would be to use a text-to-speech engine.</p> <p>Can anyone recommend something for me?</p>
[ { "answer_id": 227217, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 6, "selected": false, "text": "public partial class Form1 : Form\n{\n SpeechRecognizer rec = new SpeechRecognizer();\n\n public Form1()\n {\n InitializeComponent();\n rec.SpeechRecognized += rec_SpeechRecognized;\n }\n\n void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)\n {\n lblLetter.Text = e.Result.Text;\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n var c = new Choices();\n for (var i = 0; i <= 100; i++)\n c.Add(i.ToString());\n var gb = new GrammarBuilder(c);\n var g = new Grammar(gb);\n rec.LoadGrammar(g);\n rec.Enabled = true;\n }\n" }, { "answer_id": 316444, "author": "Rob Segal", "author_id": 7285, "author_profile": "https://Stackoverflow.com/users/7285", "pm_score": 3, "selected": false, "text": "public partial class Form1 : Form\n{\n SpeechRecognizer rec = new SpeechRecognizer();\n\n public Form1()\n {\n InitializeComponent();\n rec.SpeechRecognized += rec_SpeechRecognized;\n }\n\n void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)\n {\n lblLetter.Text = e.Result.Text;\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n var c = new Choices();\n\n // Doens't work must use English words to add to Choices and\n // populate grammar.\n //\n //for (var i = 0; i <= 100; i++)\n // c.Add(i.ToString());\n\n c.Add(\"one\");\n c.Add(\"two\");\n c.Add(\"three\");\n c.Add(\"four\");\n // etc...\n\n var gb = new GrammarBuilder(c);\n var g = new Grammar(gb);\n rec.LoadGrammar(g);\n rec.Enabled = true;\n }\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6389/" ]
227,143
<p>What is <a href="http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#getName%28%29" rel="noreferrer"><code>java.awt.Component.getName()</code></a> used for? It always seems to be <code>null</code> in the applications I build with NetBeans. I'm thinking of storing some help text per component in it -- I don't want to use the tooltip, I have another panel where I'll show the help text.</p>
[ { "answer_id": 1143865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "component.getName() component.setName(name) Listener public void someMethodOfsomeListener(SomeEvent e){\n if (e.getComponent().getName().equals(component.getName())\n //do stuff...\n}\n null" }, { "answer_id": 1469278, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " Frame[] frames = JFrame.getFrames();\n\n for (int i = 0; i < frames.length; ++i) {\n\n //get the frame\n Frame frame = frames[i];\n\n if (frame.getName().equals(frameName)) {\n\n //make the frame visible\n frame.setVisible(true);\n\n //focus the frame\n frame.requestFocus();\n\n //found\n return;\n\n }\n\n }\n" }, { "answer_id": 42957015, "author": "Tural", "author_id": 7752430, "author_profile": "https://Stackoverflow.com/users/7752430", "pm_score": -1, "selected": false, "text": "public static void main(String[] args) {\n ActionListener actionListener = new ActionListener() {\n public void actionPerformed(ActionEvent actionEvent) {\n String name = actionEvent.getSource().toString();\n UserReaction(ObjectName.getComponentVariableName(name), \"null\");\n }\n };\n Button calculate_btn = new Button(\"Calculate\");\n calculate_btn.setName(\"Calculate\");\n calculate_btn.addActionListener(actionListener);\n}\n\nprivate static void UserReaction(String objectName) {\n if (objectName.equals(\"Calculate\")) {\n //do something; \n }\n}static public String getComponentVariableName(String name) {\n String res = (name.substring(name.indexOf(\"[\") + 1));\n res = res.split(\",\")[0];\n return res;\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9648/" ]
227,148
<p>I am a support engineer and our company's product allows XSLT transforms to customize outputs.</p> <p>I made a xsl transform for this purpose. It works well for source files of typical size (several 100k), but occasionally a really huge (10M) source file will come by. In such case, the output is not generated even if I let it grind several days.</p> <p>The SW engineering team tested it and discovered that for the transform and large source file in question is indeed very slow (>days), if our product is compiled to use the transform engine in .Net 1.1, but if they compile it with .Net 2.0, it is plenty fast (about 1-2 minutes).</p> <p>The long term solution obviously is, wait for the next release.</p> <p>For the short term I am wondering the following: 1) Is XSLT flexible enough that there are more efficient and less efficient ways to acheive the same result? For example, is it possible that the way I structured the xsl, the transform engine has to iterate from the beginning of the source file many many times, taking longer and longer as the next result piece gets farther and farther from the beginning? (Schlemiel the Painter), or 2) Is it more dependent on how the transform engine interprets the xsl?</p> <p>If 2 is the case, I don't want to waste a lot of time trying to improve the xsl (I am not a big xsl genius, it was hard enough for me to achieve what little I did...).</p> <p>Thanks!</p>
[ { "answer_id": 227454, "author": "trebormf", "author_id": 30454, "author_profile": "https://Stackoverflow.com/users/30454", "pm_score": 2, "selected": false, "text": "<xsl:template match=\"foo\">\n <!--OUTPUT-->\n <xsl:apply-templates / >\n <!--OUTPUT-->\n</xsl:template>\n\n <xsl:template match=\"bar\">\n <!--OUTPUT-->\n <xsl:apply-templates / >\n <!--OUTPUT-->\n</xsl:template>\n <xsl:for-each> <xsl:template match=\"*\">\n <xsl:copy> <!--Copy node -->\n <xsl:copy-of select=\"@*\"/> <!--Copy node attributes -->\n <xsl:apply-templates /> <!--Process children -->\n </xsl:copy>\n</xsl:template>\n" }, { "answer_id": 279497, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 3, "selected": true, "text": "<xsl:if test=\"@TheFirstCol>preceding-sibling::*[1]/@TheFirstCol\"\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output method=\"text\"/>\n\n <xsl:key name=\"kC1Value\" match=\"@c1\" use=\".\"/>\n\n <xsl:template match=\"/\">\n <xsl:for-each select=\"*/x[generate-id(@c1) = generate-id(key('kC1Value',@c1)[1])]\">\n\n <xsl:value-of select=\"concat('&#xA;',@c1)\"/>\n\n <xsl:for-each select=\"key('kC1Value',@c1)\">\n <xsl:value-of select=\"'&#xA;'\"/>\n <xsl:for-each select=\"../@*[not(name()='c1')]\">\n <xsl:value-of select=\"concat(' ', .)\"/>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n generate-id() <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output method=\"text\"/>\n\n <xsl:key name=\"kC1Value\" match=\"@c1\" use=\".\"/>\n\n <xsl:template match=\"/\">\n <xsl:for-each select=\"*/x[count(@c1 | key('kC1Value',@c1)[1]) = 1]\">\n\n <xsl:value-of select=\"concat('&#xA;',@c1)\"/>\n\n <xsl:for-each select=\"key('kC1Value',@c1)\">\n <xsl:value-of select=\"'&#xA;'\"/>\n <xsl:for-each select=\"../@*[not(name()='c1')]\">\n <xsl:value-of select=\"concat(' ', .)\"/>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n <t>\n <x c1=\"1\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"1\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"1\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"1\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"2\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"2\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"2\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"2\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"3\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"4\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"4\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"4\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"4\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"5\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"6\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"7\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"7\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"7\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"7\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"8\" c2=\"0\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"8\" c2=\"0\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n <x c1=\"8\" c2=\"2\" c3=\"0\" c4=\"0\" c5=\"0\"/>\n <x c1=\"8\" c2=\"1\" c3=\"1\" c4=\"0\" c5=\"0\"/>\n</t>\n 1\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n2\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n3\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n4\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n5\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n6\n 2 0 0 0\n 1 1 0 0\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n7\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n8\n 0 0 0 0\n 0 1 0 0\n 2 0 0 0\n 1 1 0 0\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24233/" ]
227,174
<p>I have been searching high and low for a way to get my silverlight application talking to the COM port on my local computer. Has anybody out there been able to get Silverlight to successfully connect to the COM port of you local computer? If so can you point me to the documentation.</p>
[ { "answer_id": 20622198, "author": "zax", "author_id": 1742458, "author_profile": "https://Stackoverflow.com/users/1742458", "pm_score": 0, "selected": false, "text": "If AutomationFactory.IsAvailable Then\n SilPort = AutomationFactory.CreateObject(\"SilverPort.Ports\")\n Dim AllPorts() As String\n AllPorts = SilPort.GetPortNames()\n ...\nEnd If\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17/" ]
227,187
<p>I have a console application that require to use some code that need administrator level. I have read that I need to add a Manifest file myprogram.exe.manifest that look like that :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; &lt;assembly xmlns=&quot;urn:schemas-microsoft-com:asm.v1&quot; manifestVersion=&quot;1.0&quot;&gt; &lt;trustInfo xmlns=&quot;urn:schemas-microsoft-com:asm.v3&quot;&gt; &lt;security&gt; &lt;requestedPrivileges&gt; &lt;requestedExecutionLevel level=&quot;requireAdministrator&quot;&gt; &lt;/requestedPrivileges&gt; &lt;/security&gt; &lt;/trustInfo&gt; &lt;/assembly&gt; </code></pre> <p>But it still doesn't raise the UAC (in the console or in debugging in VS). How can I solve this issue?</p> <h2>Update</h2> <p>I am able to make it work if I run the solution in Administrator or when I run the /bin/*.exe in Administrator. I am still wondering if it's possible to have something that will pop when the application start instead of explicitly right click&gt;Run as Administrator?</p>
[ { "answer_id": 259146, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 4, "selected": true, "text": "mt.exe -manifest \"$(ProjectDir)$(TargetName).exe.manifest\" -updateresource:\"$(TargetDir)$(TargetName).exe;#1\"\n" }, { "answer_id": 2679654, "author": "Joe Daley", "author_id": 31563, "author_profile": "https://Stackoverflow.com/users/31563", "pm_score": 5, "selected": false, "text": "static int Main(string[] args)\n{\n if (!HasAdministratorPrivileges())\n {\n Console.Error.WriteLine(\"Access Denied. Administrator permissions are \" +\n \"needed to use the selected options. Use an administrator command \" +\n \"prompt to complete these tasks.\");\n return 740; // ERROR_ELEVATION_REQUIRED\n }\n\n ...\n return 0;\n}\n\nprivate static bool HasAdministratorPrivileges()\n{\n WindowsIdentity id = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(id);\n return principal.IsInRole(WindowsBuiltInRole.Administrator);\n}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
227,208
<p>I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this?</p> <p>I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins. </p> <p>The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.</p>
[ { "answer_id": 227754, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 4, "selected": false, "text": "XMLSerializer var svg = document.getElementById('svg_root'); // or whatever you call it\nvar serializer = new XMLSerializer();\nvar str = serializer.serializeToString(svg);\n" }, { "answer_id": 237990, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "innerHTML <canvas> toDataURL() <img> drawImage() <img src=\"data:application/svg+xml,…\"> data:" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30238/" ]
227,210
<p>I've spent most of the day making what are basically some housekeeping changes to the codebase of one of our projects (replacing all <code>System.out.println()</code> calls with log4j).</p> <p>I'm kind of curious how many lines of code I've updated with this set of changes.</p> <p>Is there anyway with <code>cvs diff</code> or another command to get an accurate count of how many lines have changed?</p> <p>I've tried</p> <pre><code>cvs diff -b -B -R </code></pre> <p>to get all of the changes in the working directory (and recursively the subdirectories), but for each file changed it also prints out file/version information, which makes just counting the lines of output useless.</p> <p>Any ideas?</p>
[ { "answer_id": 227296, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "find . | egrep -v -e '(CVS|<other patterns you don't want>)' | \\\n xargs egrep -e 'System\\.out\\.println[(][)]' | wc -l\n" }, { "answer_id": 227316, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 3, "selected": true, "text": "cvs diff -b -B -R | egrep '^<|>' | wc -l\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
227,215
<p>What's the best performing way to convert a DataRowCollection instance to a DataRow[]?</p>
[ { "answer_id": 227269, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": "DataRowCollection.CopyTo(DataRow[] array, Int32 offset)" }, { "answer_id": 227273, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 7, "selected": false, "text": "DataRow[] rows = dt.Select();\n" }, { "answer_id": 10282474, "author": "Nordin", "author_id": 29669, "author_profile": "https://Stackoverflow.com/users/29669", "pm_score": 4, "selected": false, "text": "DataRow[] rows = dt.Rows.Cast<DataRow>().ToArray()\n" }, { "answer_id": 25531600, "author": "Deilan", "author_id": 3095779, "author_profile": "https://Stackoverflow.com/users/3095779", "pm_score": 3, "selected": false, "text": "public static class DataRowCollectionExtensions\n{\n public static IEnumerable<DataRow> AsEnumerable(this DataRowCollection source)\n {\n return source.Cast<DataRow>();\n }\n}\n DataRow[] dataRows = dataRowCollection.AsEnumerable().ToArray();\n DataTable AsEnumerable DataRow[] dataRows = dataTable.AsEnumerable().ToArray();\n DataTable Select DataRow[] dataRows = dataTable.Select();\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
227,236
<p>I need to convert a Word document into HTML file(s) in Java. The function will take input an word document and the output will be html file(s) based on the number of pages the word document has i.e. if the word document has 3 pages then there will be 3 html files generated having the required page break.</p> <p>I searched for open source/non-commercial APIs which can convert doc to html but for no result. Anybody who have done this type of job before please help.</p> <p>Thanks</p>
[ { "answer_id": 515548, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import officetools.OfficeFile; // package available at www.dancrintea.ro/doc-to-pdf/\n...\nFileInputStream fis = new FileInputStream(new File(\"test.doc\"));\nFileOutputStream fos = new FileOutputStream(new File(\"test.html\"));\nOfficeFile f = new OfficeFile(fis,\"localhost\",\"8100\", true);\nf.convert(fos,\"html\");\n" }, { "answer_id": 30839320, "author": "Yusuf D.Kutni Z Felemban", "author_id": 5008715, "author_profile": "https://Stackoverflow.com/users/5008715", "pm_score": 1, "selected": false, "text": " // 1) Load DOCX into XWPFDocument\n InputStream doc = new FileInputStream(new File(\"c:/document.docx\"));\n XWPFDocument document = new XWPFDocument(doc);\n\n // 2) Prepare XHTML options (here we set the IURIResolver to load images from a \"word/media\" folder)\n XHTMLOptions options = XHTMLOptions.create(); //.URIResolver(new FileURIResolver(new File(\"word/media\")));;\n\n // 3) Extract image\n String root = \"target\";\n File imageFolder = new File( root + \"/images/\" + doc );\n options.setExtractor( new FileImageExtractor( imageFolder ) );\n // 4) URI resolver\n options.URIResolver( new FileURIResolver( imageFolder ) );\n\n\n OutputStream out = new FileOutputStream(new File(\"c:/document.html\"));\n XHTMLConverter.getInstance().convert(document, out, options);\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13187/" ]
227,249
<p>As a followup to my <a href="https://stackoverflow.com/questions/227143/java-what-is-javaawtcomponentgetname-and-setname-used-for">question about the java.awt.Component.getName() property</a>, I'm wondering if there is a way of squirreling an arbitrary object somewhere in a Component, similar to the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx" rel="nofollow noreferrer">tag property in .NET</a>? This would be really handy for any code that does work to a component but doesn't necessarily know what that component is.</p> <p>For example, say I'm trying to implement an application-wide help system that knows to look at any component currently pointed to by the mouse, reach into that component and pull out it's help text and display it in it's own pane on the screen (no, I don't want to use a tooltip). My answer currently is to use the Name (getName()/setName()) to store the help text, and this will work, but the Name has to be a string. If I wanted to get fancier and store anything other than a string, I think I'd be stuck.</p>
[ { "answer_id": 229718, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "JComponent putClientProperty getClientProperty" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9648/" ]
227,279
<p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p> <p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p> <p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p> <p>Thanks.</p>
[ { "answer_id": 228959, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "xmpppy bot.py" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12419/" ]
227,287
<p>I know how to find a method in java using a fixed string,</p> <pre><code>someClass.getMethod("foobar", argTypes); </code></pre> <p>but is there a way to use a regular expression rather than a fixed string to find a method on a given class? </p> <p>An example of the usage might be if I wanted to find a method that was called either "foobar" or "fooBar". Using a regular expression like "foo[Bb]ar" would match either of these method names.</p>
[ { "answer_id": 227300, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "try\n{\n final Pattern aMethodNamePattern = Pattern.compile(\"foo[Bb]ar\");\n final List<Method> someMethods = aClass.getDeclaredMethods();\n final List<Method> someCompliantMethods = new ArrayList<Method>();\n for(final Method aMethod: someMethods)\n {\n final String aMethodName = aMethod.getName();\n final Matcher aMethodNameMatcher = aMethodNamePattern.getMatcher(aMethodName);\n if(aMethodNameMatcher.matches() == true)\n {\n someCompliantMethods.add(aMethod);\n }\n}\ncatch(...) // catch all exceptions like SecurityException, IllegalAccessException, ...\n" }, { "answer_id": 227333, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "Pattern p = Pattern.compile(\"foo[Bb]ar\");\nfor(Method m : someClass.getMethods()) {\n if(p.matcher(m.getName()).matches()) {\n return m; \n }\n}\n" }, { "answer_id": 227344, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "Method[] getMethods( String regexp, Class clazz, Object ... argTypes ){\n List<Method> toReturn = new ArrayList<Method>();\n for( Method m : clazz.getDeclaredMethods() ){ \n if( m.getName().matches( regExp ) ) { // validate argTypes aswell here...\n toReturn.add( m );\n }\n }\n return toReturn.toArray(); \n}\n" }, { "answer_id": 227367, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 1, "selected": false, "text": " ArrayList<Method> matches = new ArrayList<Method>();\n for(Method meth : String.class.getMethods()) {\n if (meth.getName().matches(\"lengt.\")){\n matches.add(meth);\n }\n }\n" }, { "answer_id": 35428600, "author": "krzysiek.ste", "author_id": 2750931, "author_profile": "https://Stackoverflow.com/users/2750931", "pm_score": 0, "selected": false, "text": "Set<Method> getters = ReflectionUtils.getAllMethods(SomeClass.class, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix(\"get\"));\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
227,288
<p><a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow noreferrer">YUI Compressor</a> does not accept wildcard parameters, so I cannot run it like this: </p> <pre><code>C:&gt;java -jar yuicompressor.jar *.js </code></pre> <p>But I have over 500 files and would rather not have to create a batch file like this:</p> <pre><code>C:&gt;java -jar yuicompressor.jar file1.js -o deploy\file1.js C:&gt;java -jar yuicompressor.jar file2.js -o deploy\file2.js ... C:&gt;java -jar yuicompressor.jar file500.js -o deploy\file500.js </code></pre> <p>And of course my file names are <em>not</em> in such uniform way.</p> <p>Is there way to automate this without writing any code? :)</p>
[ { "answer_id": 227336, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "for %%a in (*.js) do @java -jar yuicompressor.jar \"%%a\" -o \"deploy\\%%a\"\n" }, { "answer_id": 227354, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 1, "selected": false, "text": "FOR %f IN (*.js) DO java -jar yuicompressor.jar %f -o deploy\\%f\n" }, { "answer_id": 227371, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 2, "selected": false, "text": "%-min.js: %.js\n ${java} -jar ${compressor} $< -o ${<:.js=-min.js}\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
227,303
<p>How can I find or generate thousands of company names for testing and demo purposes? (Address, phone number, and related information would be nice too.)</p> <p>I've got a system I'm building which includes business contact information. Pretty common no doubt. </p> <p>My test/demo database currently has randomly generated individual's names loaded (thanks to a handy IRS spreadsheet I found). This has worked great for internal testing and review purposes, but it looks really odd when shown to prospective customers.</p> <p>I've tried various online public information sources (e.g. EDGAR, and county based property records searches), but these all require me to manually stitch together the results in blocks of 50 names or so at a time. I could do this, but was really hoping for a search service or data store out there that had this type of information readily searchable and retrievable in very large batches.</p>
[ { "answer_id": 29707553, "author": "Scott H", "author_id": 1789708, "author_profile": "https://Stackoverflow.com/users/1789708", "pm_score": 1, "selected": false, "text": "In [1]: from pyfaker import Fake\n\nIn [2]: fake = Fake(lang_code='en')\n\nIn [3]: fake.Address.street_address()\nOut[3]: u'72449 Ward Shore'\n\nIn [4]: fake.Address.street_address()\nOut[4]: u'7954 Waelchi Mall'\n\nIn [5]: fake.Company.bs()\nOut[5]: u'whiteboard visionary markets'\n\nIn [6]: fake.Company.bs()\nOut[6]: u'exploit innovative paradigms'\n\nIn [7]: fake.Name.name()\nOut[7]: u'Aaliyah Bauch'\n\nIn [8]: fake.Name.name()\nOut[8]: u\"Chad O'Keefe\"\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/227303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3489/" ]