qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
202,289
|
<p>I am building an application where most of the HTML is built using javascript. The DOM structure is built using some JSON data structures that are sent from the server, and then the client-side code builds a UI for that data. </p>
<p>My current approach is to walk the JSON data structures, and call script.aculo.us's Builder.node method to build the DOM structure, and then append it to some element that is actually in the HTML sent from the server. Along the way, I am registering event listeners to the various elements that need them. This allows for a good amount of flexibility, and allows for a very dynamic interface.</p>
<p>However, I feel that it is not very sustainable, since the view logic (ie, the DOM structure) is so tightly coupled to the code that walks the data, and the event handlers, and the data that is kept in memory to maintain the state, and is able to communicate those changes back to the server.</p>
<p>Are there any template-like solutions that will allow me to divorce the DOM structure from the code that drives the app? Currently, my only library dependencies are prototype.js and script.aculo.us, so I would like to avoid introducing any large libraries, but any suggestions are welcome.</p>
<p>Thanks!</p>
<p>EDIT: For some reason, <a href="https://stackoverflow.com/questions/128949/what-good-template-language-is-supported-in-javascript">What good template language is supported in Javascript?</a> didn't show up in the little search results when I was typing this question. It does, however, show up in the "Related" sidebar here.</p>
<p>I will read through some of the suggestions there, and if I find a solution, I will close this question. Otherwise, I will clarify this question with reasons why those solutions won't work for me.</p>
|
[
{
"answer_id": 202365,
"author": "Michael",
"author_id": 27966,
"author_profile": "https://Stackoverflow.com/users/27966",
"pm_score": 2,
"selected": false,
"text": "$(document.body).append($('<div id=\"sub-menu-holder\" style=\"position:absolute;top:0;left:0;border:0px none;\"></div>'));\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] |
202,299
|
<p>What would be the best way to write log statements to a file or database in an iPhone application?</p>
<p>Ideally, NSLog() output could be redirected to a file using freopen(), but I've seen several reports that it doesn't work. Does anyone have this going already or have any ideas how this might best be done?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 203561,
"author": "Martin Gordon",
"author_id": 2481,
"author_profile": "https://Stackoverflow.com/users/2481",
"pm_score": 5,
"selected": false,
"text": "NSData *dataToWrite = [[NSString stringWithString:@\"String to write\"] dataUsingEncoding:NSUTF8StringEncoding];\n\nNSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];\nNSString *path = [docsDirectory stringByAppendingPathComponent:@\"fileName.txt\"];\n\n// Write the file\n[dataToWrite writeToFile:path atomically:YES];\n\n// Read the file\nNSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path]; \n\n// Check if file exists\nNSFileManager *fileManager = [NSFileManager defaultManager];\n[fileManager fileExistsAtPath:path]; // Returns a BOOL \n\n// Remove the file\n[fileManager removeItemAtPath:path error:NULL];\n\n// Cleanup\n[stringFromFile release];\n[fileManager release];\n"
},
{
"answer_id": 479556,
"author": "nst",
"author_id": 55137,
"author_profile": "https://Stackoverflow.com/users/55137",
"pm_score": 4,
"selected": false,
"text": "- (void)applicationDidFinishLaunching:(UIApplication *)application {\n#if TARGET_IPHONE_SIMULATOR == 0\n freopen([@\"/tmp/my_logs.txt\" fileSystemRepresentation], \"w\", stderr);\n#endif\n}\n"
},
{
"answer_id": 2103091,
"author": "Ben Clayton",
"author_id": 228109,
"author_profile": "https://Stackoverflow.com/users/228109",
"pm_score": 4,
"selected": false,
"text": "#if TARGET_IPHONE_SIMULATOR == 0\n NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\n NSString *documentsDirectory = [paths objectAtIndex:0];\n NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@\"console.log\"];\n freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],\"a+\",stderr);\n#endif\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] |
202,302
|
<p>How can you round <em>any</em> number (not just integers > 0) to N significant digits?</p>
<p>For example, if I want to round to three significant digits, I'm looking for a formula that could take:</p>
<p>1,239,451 and return 1,240,000</p>
<p>12.1257 and return 12.1</p>
<p>.0681 and return .0681</p>
<p>5 and return 5</p>
<p>Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.</p>
|
[
{
"answer_id": 202336,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "double roundit(double num, double N)\n{\n double d = log10(num);\n double power;\n if (num > 0)\n {\n d = ceil(d);\n power = -(d-N);\n }\n else\n {\n d = floor(d); \n power = -(d-N);\n }\n\n return (int)(num * pow(10.0, power) + 0.5) * pow(10.0, -power);\n}\n log 1239451 = 6.09\nlog 12.1257 = 1.08\nlog 0.0681 = -1.16\n d (d-N) double roundedrest = num * pow(10, -(d-N));\n\npow(1239451, -4) = 123.9451\npow(12.1257, 1) = 121.257\npow(0.0681, 4) = 681\n roundedrest = (int)(roundedrest + 0.5);\n roundednum = pow(roundedrest, -(power))\n System.out.println(new BigDecimal(n));\n Pyro's: 12.0999999999999996447286321199499070644378662109375\nMine: 12.10000000000000142108547152020037174224853515625\nPrinting 12.1 directly: 12.0999999999999996447286321199499070644378662109375\n"
},
{
"answer_id": 202476,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 4,
"selected": false,
"text": "function sigFigs(n, sig) {\n var mult = Math.pow(10, sig - Math.floor(Math.log(n) / Math.LN10) - 1);\n return Math.round(n * mult) / mult;\n}\n\nalert(sigFigs(1234567, 3)); // Gives 1230000\nalert(sigFigs(0.06805, 3)); // Gives 0.0681\nalert(sigFigs(5, 3)); // Gives 5\n"
},
{
"answer_id": 730518,
"author": "Justin Wignall",
"author_id": 42774,
"author_profile": "https://Stackoverflow.com/users/42774",
"pm_score": 4,
"selected": false,
"text": "Number(n).toPrecision(sig)\n alert(Number(12345).toPrecision(3)\n Number(8.14301).toPrecision(4) == 8.143\n roundit(8.14301,4) == 8.144\n"
},
{
"answer_id": 1581007,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 8,
"selected": true,
"text": "power n - d public static double roundToSignificantFigures(double num, int n) {\n if(num == 0) {\n return 0;\n }\n\n final double d = Math.ceil(Math.log10(num < 0 ? -num: num));\n final int power = n - (int) d;\n\n final double magnitude = Math.pow(10, power);\n final long shifted = Math.round(num*magnitude);\n return shifted/magnitude;\n}\n"
},
{
"answer_id": 2975934,
"author": "Jason Swank",
"author_id": 358645,
"author_profile": "https://Stackoverflow.com/users/358645",
"pm_score": 2,
"selected": false,
"text": "function sigFigs(n, sig) {\n if ( n === 0 )\n return 0\n var mult = Math.pow(10,\n sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1);\n return Math.round(n * mult) / mult;\n }\n"
},
{
"answer_id": 3089387,
"author": "Valeri Shibaev",
"author_id": 372677,
"author_profile": "https://Stackoverflow.com/users/372677",
"pm_score": 1,
"selected": false,
"text": "/**\n * Set Significant Digits.\n * @param value value\n * @param digits digits\n * @return\n */\npublic static BigDecimal setSignificantDigits(BigDecimal value, int digits) {\n //# Start with the leftmost non-zero digit (e.g. the \"1\" in 1200, or the \"2\" in 0.0256).\n //# Keep n digits. Replace the rest with zeros.\n //# Round up by one if appropriate.\n int p = value.precision();\n int s = value.scale();\n if (p < digits) {\n value = value.setScale(s + digits - p); //, RoundingMode.HALF_UP\n }\n value = value.movePointRight(s).movePointLeft(p - digits).setScale(0, RoundingMode.HALF_UP)\n .movePointRight(p - digits).movePointLeft(s);\n s = (s > (p - digits)) ? (s - (p - digits)) : 0;\n return value.setScale(s);\n}\n"
},
{
"answer_id": 4221300,
"author": "Thomas Becker",
"author_id": 512951,
"author_profile": "https://Stackoverflow.com/users/512951",
"pm_score": 3,
"selected": false,
"text": "roundToSignificantFigures Double.MIN_VALUE roundToSignificantFigures(1.234E-310, 3);\n power magnitude Infinity magnitude num * magnitude magintude \n public static double roundToNumberOfSignificantDigits(double num, int n) {\n\n final double maxPowerOfTen = Math.floor(Math.log10(Double.MAX_VALUE));\n\n if(num == 0) {\n return 0;\n }\n\n final double d = Math.ceil(Math.log10(num < 0 ? -num: num));\n final int power = n - (int) d;\n\n double firstMagnitudeFactor = 1.0;\n double secondMagnitudeFactor = 1.0;\n if (power > maxPowerOfTen) {\n firstMagnitudeFactor = Math.pow(10.0, maxPowerOfTen);\n secondMagnitudeFactor = Math.pow(10.0, (double) power - maxPowerOfTen);\n } else {\n firstMagnitudeFactor = Math.pow(10.0, (double) power);\n }\n\n double toBeRounded = num * firstMagnitudeFactor;\n toBeRounded *= secondMagnitudeFactor;\n\n final long shifted = Math.round(toBeRounded);\n double rounded = ((double) shifted) / firstMagnitudeFactor;\n rounded /= secondMagnitudeFactor;\n return rounded;\n}\n"
},
{
"answer_id": 6428541,
"author": "Michael Zlatkovsky - Microsoft",
"author_id": 678505,
"author_profile": "https://Stackoverflow.com/users/678505",
"pm_score": 1,
"selected": false,
"text": "Public Shared Function roundToSignificantDigits(ByVal num As Double, ByVal n As Integer) As Double\n If (num = 0) Then\n Return 0\n End If\n\n Dim d As Double = Math.Ceiling(Math.Log10(If(num < 0, -num, num)))\n Dim power As Integer = n - CInt(d)\n Dim magnitude As Double = Math.Pow(10, power)\n Dim shifted As Double = Math.Round(num * magnitude)\n Return shifted / magnitude\nEnd Function\n"
},
{
"answer_id": 16631847,
"author": "Harikrishnan",
"author_id": 2279606,
"author_profile": "https://Stackoverflow.com/users/2279606",
"pm_score": -1,
"selected": false,
"text": "public static double roundToSignificantDigits(double num, int n) {\n return Double.parseDouble(new java.util.Formatter().format(\"%.\" + (n - 1) + \"e\", num).toString());\n}\n"
},
{
"answer_id": 16874602,
"author": "SomeGuy",
"author_id": 2443570,
"author_profile": "https://Stackoverflow.com/users/2443570",
"pm_score": 0,
"selected": false,
"text": "Function SF(n As Double, SigFigs As Integer)\n Dim l As Integer = n.ToString.Length\n n = n / 10 ^ (l - SigFigs)\n n = Math.Round(n)\n n = n * 10 ^ (l - SigFigs)\n Return n\nEnd Function\n"
},
{
"answer_id": 19506883,
"author": "JackDev",
"author_id": 1381093,
"author_profile": "https://Stackoverflow.com/users/1381093",
"pm_score": 2,
"selected": false,
"text": "public String toSignificantFiguresString(BigDecimal bd, int significantFigures){\n return String.format(\"%.\"+significantFigures+\"G\", bd);\n}\n public BigDecimal toSignificantFigures(BigDecimal bd, int significantFigures){\n String s = String.format(\"%.\"+significantFigures+\"G\", bd);\n BigDecimal result = new BigDecimal(s);\n return result;\n}\n BigDecimal bd = toSignificantFigures(BigDecimal.valueOf(0.0681), 2);\n"
},
{
"answer_id": 30041389,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 2,
"selected": false,
"text": "Number( my_number.toPrecision(3) );\n Number \"8.143e+5\" \"814300\""
},
{
"answer_id": 43051623,
"author": "Duncan Calvert",
"author_id": 1070333,
"author_profile": "https://Stackoverflow.com/users/1070333",
"pm_score": 0,
"selected": false,
"text": "return new BigDecimal(value, new MathContext(significantFigures, RoundingMode.HALF_UP)).doubleValue();"
},
{
"answer_id": 48482674,
"author": "Michael Hampton",
"author_id": 1068283,
"author_profile": "https://Stackoverflow.com/users/1068283",
"pm_score": 0,
"selected": false,
"text": "math.Round() // TODO: replace in go1.10 with math.Round()\nfunc round(x float64) float64 {\n return float64(int64(x + 0.5))\n}\n\n// SignificantDigits rounds a float64 to digits significant digits.\n// Translated from Java at https://stackoverflow.com/a/1581007/1068283\nfunc SignificantDigits(x float64, digits int) float64 {\n if x == 0 {\n return 0\n }\n\n power := digits - int(math.Ceil(math.Log10(math.Abs(x))))\n magnitude := math.Pow(10, float64(power))\n shifted := round(x * magnitude)\n return shifted / magnitude\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442/"
] |
202,305
|
<p>I've created a PHP DOM xml piece and saved it to a string like this:</p>
<pre><code><?php
// create a new XML document
$doc = new DomDocument('1.0');
...
...
...
$xmldata = $doc->saveXML();
?>
</code></pre>
<p>Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.</p>
<p>Something like a save this file link or a download prompt would be good. How do I do it?</p>
|
[
{
"answer_id": 204074,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 4,
"selected": true,
"text": "<html>\n<head>\n<title>XML Download Example</title>\n</head>\n\n<body>\n\n<a href=\"download.php\">Download XML example</a>\n\n</body>\n</html>\n <?php\n// Populate XML document\n $doc = new DomDocument();\n // ... various modifications to the document are made\n\n// Output headers\n header('Content-type: \"text/xml\"; charset=\"utf8\"');\n header('Content-disposition: attachment; filename=\"example.xml\"');\n\n// Output content\n echo $doc->saveXML();\n?>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27943/"
] |
202,306
|
<p>How can I AutoIncrement the assembly (build) number in Visual Studio?</p>
<h3>Duplicate:</h3>
<p><a href="https://stackoverflow.com/questions/650/">/questions/650/automatically-update-version-number</a></p>
|
[
{
"answer_id": 202315,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "[assembly: AssemblyVersion(\"1.0.*\")]\n"
},
{
"answer_id": 202327,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 0,
"selected": false,
"text": "[assembly: AssemblyVersion(\"1.0.*.*\")]\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,322
|
<p>I have a J2EE based web application, in which on clicking a button I need to create a word file from Java. I want to be able to sent the printing command to this file, so that the file is being printed without the user having to open the document and do it manually.</p>
<p>Could anyone please tell me if this is possible and if so how to proceed?</p>
|
[
{
"answer_id": 202341,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 1,
"selected": false,
"text": "<script>\nfunction load() {\nwindow.print();\nwindow.close();\n}\n</script>\n <body onLoad=\"load()\" ...>\n"
},
{
"answer_id": 6627350,
"author": "Leo",
"author_id": 835595,
"author_profile": "https://Stackoverflow.com/users/835595",
"pm_score": 1,
"selected": false,
"text": "$sRTFfilename = \"C:\\t\\t.rtf\" ;Change this path to one of your own \nShellExecute('\"' & $sRTFfilename & '\"', \"\", @ScriptDir, \"print\", @SW_HIDE)\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23414/"
] |
202,323
|
<p>Is there a URL for StackOverflow that I can use on the VS startpage in place of the never updated MS page? The URL that VS uses can be set on the Tools->Options::Startup dialog.</p>
<p>I've tried <a href="https://stackoverflow.com/feeds">https://stackoverflow.com/feeds</a> VS complaints with the following error:</p>
<blockquote>
<p>The current news channel might not be
a valid RSS feed, or your internet
connection might be unavailable. To
change the news channel, on the Tools
menu, click Options, then expand
Environment and click Startup.</p>
</blockquote>
|
[
{
"answer_id": 204982,
"author": "Scott Dillman",
"author_id": 10111,
"author_profile": "https://Stackoverflow.com/users/10111",
"pm_score": 2,
"selected": false,
"text": "<link xmlns=\"http://www.w3.org/2005/Atom\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\" rel=\"replies\" type=\"application/atom+xml\" href=\"http://stackoverflow.com/feeds/question/204696/answers\" thr:count=\"5\" />\n <!-- copy extensions -->\n<x:template match='*'>\n <x:comment>Unknown element <x:value-of select=\"local-name(.)\"/></x:comment>\n<!-- \n <x:copy>\n <x:copy-of select='node()|@*'/>\n </x:copy>\n-->\n</x:template>\n <?php\n\n$url=$_GET['url'];\n\n$ch = curl_init($url);\ncurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n$content = curl_exec($ch);\ncurl_close($ch);\n\n$chan = new DOMDocument(); \n$chan->loadXML($content); \n$sheet = new DOMDocument(); \n$sheet->load('atom2rss.xsl'); \n$processor = new XSLTProcessor();\n$processor->registerPHPFunctions();\n$processor->importStylesheet($sheet);\n$result = $processor->transformToXML($chan); \n\necho $result;\n\n?>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18978/"
] |
202,328
|
<p>What are some ways that I can query the local machine's specifications (a range of things from CPU specs, OS version, graphics card specs and drivers, etc.) through a programmatic interface? We're writing a simple app in C# to test compatibility of our main app and want to have it dump out some system metrics, but I can't seem to find where to even start, what interfaces to use, libraries, anything.</p>
<p>I've tried all kinds of searches, but can only find programs, and GUI ones at that, which require a user to interact with, or have to install.</p>
<p>Alternatively, a small, command-line program would work just as well, as long as we'd be permitted to distribute it with the test app.</p>
<p>I have found one program that gets some of the specs I'd want, <a href="http://technet.microsoft.com/en-us/sysinternals/bb897550.aspx" rel="nofollow noreferrer">PsInfo</a>. However, it seems to require each user to agree to some license when it is first run, even though it's a command line app. Plus, it only deals with OS/CPU info, and I will need more than that.</p>
<p>Also: forgot to mention explicitly, but this indeed is only going to be necessary for Windows machines. You folks are quick!</p>
<p>Edit: This WMI does look like what I need, thanks! Quite a can of worms though, so I've got to dive in. It mentions that for some things the user has to have administrator privileges; this probably won't be a big problem, but it might limit it a little.</p>
|
[
{
"answer_id": 202370,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "/proc"
},
{
"answer_id": 205628,
"author": "Doug Kavendek",
"author_id": 9330,
"author_profile": "https://Stackoverflow.com/users/9330",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Management;\nusing System.IO;\n\nnamespace SyTest\n{\n class Program\n {\n static StreamWriter specStream;\n\n static void Main(string[] args)\n {\n FileStream specFile =\n new FileStream(\"machine-specs.txt\",FileMode.Create,FileAccess.Write);\n specStream = new StreamWriter(specFile);\n\n LogClass(\"Win32_DesktopMonitor\");\n LogClass(\"Win32_VideoController\");\n LogClass(\"Win32_Processor\");\n // etc\n\n specStream.Close();\n specFile.Close();\n }\n\n static void LogClass(string strTable)\n {\n if (strTable.Length <= 0) return;\n specStream.Write(\"--- \" + strTable + \" ---\\r\\n\\r\\n\");\n WqlObjectQuery wqlQuery =\n new WqlObjectQuery(\"SELECT * FROM \" + strTable);\n ManagementObjectSearcher searcher =\n new ManagementObjectSearcher(wqlQuery);\n try\n {\n if (searcher.Get().Count <= 0)\n {\n specStream.Write(\"Class has no instances\\r\\n\\r\\n\");\n }\n foreach (ManagementObject obj in searcher.Get())\n {\n specStream.Write(\"* \" + obj.ToString() + \"\\r\\n\");\n\n if (obj.Properties.Count <= 0)\n {\n specStream.Write(\"Class instance has no properties\\r\\n\");\n continue;\n }\n\n foreach (System.Management.PropertyData prop in obj.Properties)\n {\n LogAttr(obj, prop.Name);\n }\n\n specStream.Write(\"\\r\\n\");\n }\n }\n catch { specStream.Write(\"Class does not exist\\r\\n\\r\\n\"); }\n }\n static void LogAttr(ManagementObject obj, string str)\n {\n if (str.Length <= 0) return;\n string strValue = \"\";\n try\n {\n strValue = obj[str].ToString();\n try\n {\n string[] pstrTmp = ((string[])obj[str]);\n if (pstrTmp.Length > 0) strValue = String.Join(\", \", pstrTmp);\n }\n catch { } // Problem casting, fall back on original assignment\n }\n catch { strValue = \"[UNDEFINED]\"; }\n specStream.Write(str + \": \" + strValue + \"\\r\\n\");\n }\n }\n}\n"
},
{
"answer_id": 22769332,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 0,
"selected": false,
"text": "MissingLinq.Linq2Management"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9330/"
] |
202,340
|
<p>Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.</p>
<p>Often times I should really be rolling my own class instead of just using std::pair. It's pretty easy to see when things start breaking down - when the code becomes littered with make_pair, first, and second, its very hard to remember what is what - an <code>std::pair<int, int></code> conveys less meaning than a type <code>Position</code>.</p>
<p>What have you found are the best ways to wrap the functionality of std::pair in a type that conveys real meaning?</p>
<p>Here are some things I have considered:</p>
<pre><code>typedef std::pair<int, int> Position;
</code></pre>
<p>This at least gives the type a meaningful name when passing it around, but the type isn't enforced, its still really just a pair, and most of the same problems still exist. This is however very simple to write.</p>
<pre><code>struct Position : public std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() : Base() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
};
</code></pre>
<p>This is better, since we can access the variables via a reasonably descriptive name. The problem here is that you can still access first and second, so its easy for the abstraction to leak. Also, accessing simple variables via functions makes the syntax annoying.</p>
<p>The obvious next step is to make the inheritance private:</p>
<pre><code>struct Position : private std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
bool operator<(const Position &x) const { return Base(*this) < Base(x); }
// other forwarding operators as needed...
};
</code></pre>
<p>So now at least we have gotten rid of the access to first and second, but now a new problem pops up. When we want to store the type in an std::set, we now don't have access to the operator< overload since we don't have access to first and second. This means we have to define a forwarding function for each operator overload we want. For me this is usually ==, !=, and <, but there could be others that I'd want. Yes I know I probably shouldn't overload operator< just to stick it in an associative container, but it makes everything so darn simple... And defining these operators for each new type is a pain, and we STILL have to access via functions. We can fix that:</p>
<pre><code>struct Position
{
Position() {}
Position(const Position &x) : row(x.row), col(x.col) {}
Position(int row, int col) : row(row), col(col) {}
int row, col;
};
bool operator<(const Position &a, const Position &b)
{
return a.row < b.row || (!(b.row < a.row) && a.col < b.col);
}
// more overloads as needed
</code></pre>
<p>So now we have simple variable access, but now defining overloaded operators is even more of a pain, because instead of just forwarding them to the pair's implementation, we actually have to re-implement them each time...</p>
<p>Are there any solutions I have overlooked that make this easy without the drawbacks? If there aren't which would you tend to prefer?</p>
|
[
{
"answer_id": 202363,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "pair bool operator< ( const Position &a, const Position &b ) \n{\n return\n std::make_pair( a.row, a.col ) < std::make_pair( b.row, b.col );\n}\n"
},
{
"answer_id": 202483,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "DEFINE_PAIR_TYPE(Position, int, int, row, col);"
},
{
"answer_id": 206762,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "struct MyStruct\n{\n std::string var1;\n std::string var2;\n bool var3;\n\n struct less : std::binary_function<struct MyStruct, struct MyStruct, bool>\n {\n bool operator() (const struct MyStruct& s1, const struct MyStruct& s2) const\n { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; }\n };\n};\ntypedef std::set<struct MyStruct, MyStruct::less> MySet;\n bool operator==(const MyStruct& rhs) const \n { return var1 == rhs.var1 && var2 == rhs.var2 && var3 == rhs.var3; };\nbool operator<(const MyStruct& a2) const \n { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; };\n"
},
{
"answer_id": 242742,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 0,
"selected": false,
"text": "typedef"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
202,368
|
<p>I'm writing an ASP.NET application. I have a textbox on a webform, and I want to force whatever the user types to upper case. I'd like to do this on the front end. You should also note that there is a validation control on this textbox, so I want to make sure the solution doesn't interfere with the ASP.NET validation.</p>
<p><strong>Clarification:</strong>
It appears that the CSS text transform makes the user input appear in uppercase. However, under the hood, it's still lower case as the validation control fails. You see, my validation control checks to see if a valid state code is entered, however the regular expression I'm using only works with uppercase characters.</p>
|
[
{
"answer_id": 202386,
"author": "billb",
"author_id": 26805,
"author_profile": "https://Stackoverflow.com/users/26805",
"pm_score": 5,
"selected": false,
"text": ".uppercase\n{\n text-transform: uppercase;\n}\n\n<asp:TextBox ID=\"TextBox1\" runat=\"server\" Text=\"\" CssClass=\"uppercase\"></asp:TextBox>;\n"
},
{
"answer_id": 202389,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "function makeUpperCase(this)\n{\n this.value = this.value.toUpperCase();\n}\n"
},
{
"answer_id": 202398,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": " style='text-transform:uppercase'\n"
},
{
"answer_id": 202410,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 1,
"selected": false,
"text": "style=\"text-transform: uppercase\";\"\n"
},
{
"answer_id": 202537,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<asp:TextBox ID=\"txtInput\" runat=\"server\"></asp:TextBox>\n<script type=\"text/javascript\">\n function setFormat() {\n var inp = document.getElementById('ctl00_MainContent_txtInput');\n var x = inp.value;\n inp.value = x.toUpperCase();\n }\n\n var inp = document.getElementById('ctl00_MainContent_txtInput');\n inp.onblur = function(evt) {\n setFormat();\n };\n</script>\n"
},
{
"answer_id": 202545,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 6,
"selected": false,
"text": "style='text-transform:uppercase' \n Textbox.Value.ToUpper();\n"
},
{
"answer_id": 203659,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "window.onload = function () {\n var input = document.getElementById(\"test\");\n\n input.onkeypress = function () {\n // So that things work both on Firefox and Internet Explorer.\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a lowercase character?\n if (/[a-z]/.test(char)) {\n // Append its uppercase version\n input.value += char.toUpperCase();\n\n // Cancel the original event\n evt.cancelBubble = true;\n return false;\n }\n }\n};\n"
},
{
"answer_id": 1339834,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<!-- Script by hscripts.com -->\n<script language=javascript>\n function upper(ustr)\n {\n var str=ustr.value;\n ustr.value=str.toUpperCase();\n }\n\n function lower(ustr)\n {\n var str=ustr.value;\n ustr.value=str.toLowerCase();\n }\n</script>\n\n<form>\n Type Lower-case Letters<textarea name=\"address\" onkeyup=\"upper(this)\"></textarea>\n</form>\n\n<form>\n Type Upper-case Letters<textarea name=\"address\" onkeyup=\"lower(this)\"></textarea>\n</form>\n"
},
{
"answer_id": 1345185,
"author": "Cyril Gupta",
"author_id": 33052,
"author_profile": "https://Stackoverflow.com/users/33052",
"pm_score": 2,
"selected": false,
"text": "<script src=\"Scripts/jquery-1.3.2.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#txt\").keydown(function(e) {\n if (e.keyCode >= 65 & e.keyCode <= 90) {\n val1 = $(\"#txt\").val();\n $(\"#txt\").val(val1 + String.fromCharCode(e.keyCode));\n return false;\n }\n });\n });\n</script>\n /script"
},
{
"answer_id": 2042635,
"author": "Vinay Yadav",
"author_id": 248138,
"author_profile": "https://Stackoverflow.com/users/248138",
"pm_score": 3,
"selected": false,
"text": "**I would do like:\n<asp:TextBox ID=\"txtName\" onkeyup=\"this.value=this.value.toUpperCase()\" runat=\"server\"></asp:TextBox>**\n"
},
{
"answer_id": 2815198,
"author": "NetMage",
"author_id": 2557128,
"author_profile": "https://Stackoverflow.com/users/2557128",
"pm_score": 0,
"selected": false,
"text": "function ToUpper() {\n // So that things work both on FF and IE\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a lowercase character?\n if (/[a-z]/.test(char)) {\n // convert to uppercase version\n if (evt.which) {\n evt.which = char.toUpperCase().charCodeAt(0);\n }\n else {\n evt.keyCode = char.toUpperCase().charCodeAt(0);\n }\n }\n\n return true;\n }\n <asp:TextBox ID=\"txtAddManager\" onKeyPress=\"ToUpper()\" runat=\"server\" \n Width=\"84px\" Font-Names=\"Courier New\"></asp:TextBox>\n"
},
{
"answer_id": 4474650,
"author": "Vasan Ramani",
"author_id": 546518,
"author_profile": "https://Stackoverflow.com/users/546518",
"pm_score": 2,
"selected": false,
"text": "<-- form name=\"frmTest\" -->\n<-- input type=\"text\" size=100 class=\"ucasetext\" name=\"textBoxUCase\" id=\"textBoxUCase\" -->\n<-- /form -->\n\nwindow.onload = function() {\n var input = document.frmTest.textBoxUCase;\n input.onkeyup = function() {\n input.value = input.value.toUpperCase();\n }\n};\n"
},
{
"answer_id": 7250093,
"author": "Robert Green MBA",
"author_id": 663853,
"author_profile": "https://Stackoverflow.com/users/663853",
"pm_score": 3,
"selected": false,
"text": "$('#FirstName').bind('keyup', function () {\n\n // Get the current value of the contents within the text box\n var val = $('#FirstName').val().toUpperCase();\n\n // Reset the current value to the Upper Case Value\n $('#FirstName').val(val);\n\n});\n"
},
{
"answer_id": 15717742,
"author": "Chetan Sanghani",
"author_id": 1936231,
"author_profile": "https://Stackoverflow.com/users/1936231",
"pm_score": 0,
"selected": false,
"text": " <telerik:RadTextBox ID=\"txtCityName\" runat=\"server\" MaxLength=\"50\" Width=\"200px\"\n Style=\"text-transform: uppercase;\">\n"
},
{
"answer_id": 24300082,
"author": "Vijay Kumbhoje",
"author_id": 3583859,
"author_profile": "https://Stackoverflow.com/users/3583859",
"pm_score": 2,
"selected": false,
"text": "<asp:TextBox ID=\"txtLocatorName\" runat=\"server\"\n style=\"text-transform:uppercase\" CssClass=\"textbox\" \n TabIndex=\"1\">\n</asp:TextBox>\n string UCstring = txtName.Text.ToUpper();\n"
},
{
"answer_id": 25896426,
"author": "greg",
"author_id": 1829881,
"author_profile": "https://Stackoverflow.com/users/1829881",
"pm_score": 0,
"selected": false,
"text": " $().ready(docReady);\n\n function docReady() {\n\n $(\"#myTextbox\").focusout(uCaseMe);\n }\n\n function uCaseMe() {\n\n var val = $(this).val().toUpperCase();\n\n // Reset the current value to the Upper Case Value\n $(this).val(val);\n }\n"
},
{
"answer_id": 37958370,
"author": "Codeone",
"author_id": 5519409,
"author_profile": "https://Stackoverflow.com/users/5519409",
"pm_score": 2,
"selected": false,
"text": "\nCSS property specifies how to capitalize an element's text. It can be used to make text appear in all-uppercase or all-lowercase Style=\"text-transform: uppercase;\" CssClass=\"upper\""
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21155/"
] |
202,378
|
<p>I am trying to make this feature available, maybe in an apache .htaccess file.</p>
|
[
{
"answer_id": 448435,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "AddHandler php4 .php\nAction php4 /cgi-bin/php4\n AddHandler php5 .php\nAction php5 /cgi-bin/php5\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,379
|
<p>I have a source base that, depending on defined flags at build time, creates two different apps. I can build both of these apps using a Makefile by specifying two different targets, one that compiles with a flag and one that compiles without, and having an aggregate target that builds both.</p>
<p>How do I do the equivalent thing from Visual C# Express on Windows?</p>
|
[
{
"answer_id": 202774,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 0,
"selected": false,
"text": "Build->Batch Build"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6010/"
] |
202,405
|
<p>At work, I use Cygwin a lot because it offers me a small oasis in the vast desert of Windows. I inevitably end up running some non-Cygwin programs through the bash shell, such as build scripts (batch files created in-house) and the Subversion CLI binaries (I have the Windows ones installed). 99% of the time, I don't have any problems using this setup. The other 1%, however, causes a strange issue:</p>
<p>With both the build scripts and SVN, most of the time the enter key is interpreted correctly. For instance, I'll kick off the database creation script and it will prompt me for the server name. I type in "localhost" and hit enter. Everything's fine. Then it gets to the end, if there are errors, and prints things out using <code>more</code>. No key that I press is recognized by <code>more</code>. I have to Ctrl-C out of it.</p>
<p>Similarly, if I do a Subversion update, normally everything is fine. In the case where the interactive conflict resolution happens, however, I'll usually type in "tf" for "theirs-full" and hit enter, but nothing happens. I have to Ctrl-C out of it and re-run the update with force merge or use TortoiseSVN in Windows to do it.</p>
<p>Any idea why Cygwin seems to randomly not be passing the enter key through to the programs? I considered that it may have something to do with Unix vs Windows style line endings, so I've tried typing those characters manually, but that doesn't seem to make a difference. Thanks.</p>
<p><strong>Edit</strong>: I just had this happen to me again and I realized something. It was SVN prompting me for a password. I typed in the password, which it echoed to the screen (bad) and hit enter... nothing. Hit enter a few more times, the cursor moves, but nothing happens. I hit Ctrl-C and it dumps me back to bash, which then says "bash: [my password]: command not found" followed by a number of new prompts equal to the number of times I hit the enter key. So what happened is the input never made it to SVN, but somehow got read by bash after SVN exited. I thought that may help someone figure out what is going on.</p>
|
[
{
"answer_id": 11046177,
"author": "Vic",
"author_id": 97439,
"author_profile": "https://Stackoverflow.com/users/97439",
"pm_score": 2,
"selected": false,
"text": "$ conin svn list https://{repo}\nPassword for 'user': ******\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
] |
202,406
|
<p>In my user model, I have an attribute called "nickname" and validates as such:</p>
<blockquote>
<p>validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true</p>
</blockquote>
<p>However, it is currently letting this string pass as valid:</p>
<p>a?c</p>
<p>I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.</p>
|
[
{
"answer_id": 202411,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "/^[a-zA-Z0-9]+$/\n"
},
{
"answer_id": 202412,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "^[a-zA-Z0-9]*$\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19527/"
] |
202,430
|
<p>Does anyone have any information about getting the current versions of ASP.NET MVC (Preview 5) working on Mono 2.0? There was info on the old versions (Preview 2, maybe Preview 3), but I've seen no details about making Preview 5 actually work.</p>
<p>The <a href="http://www.mono-project.com/Roadmap" rel="nofollow noreferrer">Mono Project Roadmap</a> indicates ASP.NET 3.5 for Mono 2.4 (next year). Any ideas on how to get this useful before then?</p>
<p>More details: The basic MVC Preview 5 template seems to work, so long as I avoid the root directory. If I request the root, I get:</p>
<pre><code>Server Error in '/' Application
The virtual path '' maps to another application.
Description: HTTP 500. Error processing request.
Stack Trace:
System.Web.HttpException: The virtual path '' maps to another application.
at System.Web.HttpContext.RewritePath (System.String filePath, System.String pathInfo, System.String queryString, Boolean setClientFilePath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path, Boolean rebaseClientPath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path) [0x00000]
at MvcApplication1._Default.Page_Load (System.Object sender, System.EventArgs e) [0x00000]
at System.Web.UI.Control.OnLoad (System.EventArgs e) [0x00000]
at System.Web.UI.Control.LoadRecursive () [0x00000]
at System.Web.UI.Page.ProcessLoad () [0x00000]
at System.Web.UI.Page.ProcessPostData () [0x00000]
at System.Web.UI.Page.InternalProcessRequest () [0x00000]
at System.Web.UI.Page.ProcessRequest (System.Web.HttpContext context) [0x00000]
Version information: Mono Version: 2.0.50727.42; ASP.NET Version: 2.0.50727.42
</code></pre>
|
[
{
"answer_id": 202568,
"author": "MichaelGG",
"author_id": 27012,
"author_profile": "https://Stackoverflow.com/users/27012",
"pm_score": 5,
"selected": true,
"text": "HttpContext.Current.RewritePath(\"/Home/Index\");\n"
},
{
"answer_id": 202570,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 1,
"selected": false,
"text": "HttpContext.Current.RewritePath(Request.ApplicationPath);\n ((IHttpHandler)new MvcHttpHandler()).ProcessRequest(HttpContext.Current);\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27012/"
] |
202,432
|
<p>I am trying to capture output from an install script (that uses scp) and log it. However, I am not getting everything that scp is printing out, namely, the progress bar. </p>
<p>screen output:</p>
<blockquote>
<p>Copying
/user2/cdb/builds/tmp/uat/myfiles/* to
server /users/myfiles as cdb</p>
<p>cdb@server's password:
myfile 100% |*****************************| 2503 00:00</p>
</blockquote>
<p>log output:</p>
<blockquote>
<p>Copying
/user2/cdb/builds/tmp/uat/myfiles/* to
server /users/myfiles as cdb</p>
</blockquote>
<p>I'd really like to know that my file got there. Here's what I am trying now to no avail:</p>
<blockquote>
<p>myscript.sh 2>&1 | tee mylogfile.log</p>
</blockquote>
<p>Does anyone have a good way to capture scp output and log it? </p>
<p>Thanks.</p>
|
[
{
"answer_id": 202479,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 4,
"selected": true,
"text": "scp myfile user@host.com:. && echo success!\n man scp scp exits with 0 on success or >0 if an error occurred.\n"
},
{
"answer_id": 12925408,
"author": "Martin",
"author_id": 1751663,
"author_profile": "https://Stackoverflow.com/users/1751663",
"pm_score": 5,
"selected": false,
"text": "script -q -c \"scp server:/file /tmp/\" > /tmp/test.txt\n file 0% 0 0.0KB/s --:-- ETA\nfile 18% 11MB 11.2MB/s 00:04 ETA\nfile 36% 22MB 11.2MB/s 00:03 ETA\nfile 54% 34MB 11.2MB/s 00:02 ETA\nfile 73% 45MB 11.2MB/s 00:01 ETA\nfile 91% 56MB 11.2MB/s 00:00 ETA\nfile 100% 61MB 10.2MB/s 00:06\n"
},
{
"answer_id": 24546732,
"author": "Fekensa D.",
"author_id": 2412924,
"author_profile": "https://Stackoverflow.com/users/2412924",
"pm_score": 1,
"selected": false,
"text": "scp myfile user@host.com:. && echo success! \n scp myfile user@host.com:. && echo myfile successfully copied! >> logfile 2>&1\n"
},
{
"answer_id": 26613793,
"author": "Benjamin Crouzier",
"author_id": 311744,
"author_profile": "https://Stackoverflow.com/users/311744",
"pm_score": -1,
"selected": false,
"text": "scp server:/file /tmp/ > /dev/tty\n"
},
{
"answer_id": 37545874,
"author": "ravi teja Kadem",
"author_id": 6404619,
"author_profile": "https://Stackoverflow.com/users/6404619",
"pm_score": 0,
"selected": false,
"text": "$ grep -r \"Error\" xyz.out > abc.txt\n grep"
},
{
"answer_id": 59227260,
"author": "Tregoreg",
"author_id": 1137187,
"author_profile": "https://Stackoverflow.com/users/1137187",
"pm_score": 2,
"selected": false,
"text": "&& echo success! scp -vrC root@host:/path/to/directory . 2> copy.log &\n -v -C -r grep file copy.log | wc -l\n"
},
{
"answer_id": 72377986,
"author": "Naresh B",
"author_id": 6933608,
"author_profile": "https://Stackoverflow.com/users/6933608",
"pm_score": 0,
"selected": false,
"text": "-c -c $ scp -q -v nb3510@servername:sftp.dummy . 2>&1 | grep 'Bytes per second'\nBytes per second: sent 52945.7, received 188047087.0\n -v"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807/"
] |
202,434
|
<p>How can I detect the current text formatting at the cursor position in a WPF RichTextBox?</p>
|
[
{
"answer_id": 202737,
"author": "Artur Carvalho",
"author_id": 1013,
"author_profile": "https://Stackoverflow.com/users/1013",
"pm_score": 2,
"selected": true,
"text": "TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);\nobject oFont = tr.GetPropertyValue(Run.FontFamilyProperty);\n"
},
{
"answer_id": 3453568,
"author": "msfanboy",
"author_id": 252289,
"author_profile": "https://Stackoverflow.com/users/252289",
"pm_score": 3,
"selected": false,
"text": "var obj = _myText.GetPropertyValue(Inline.TextDecorationsProperty);\n\n if (obj == DependencyProperty.UnsetValue) \n IsTextUnderline = false;// mixed formatting \n\n if (obj is TextDecorationCollection)\n {\n var objProper = obj as TextDecorationCollection;\n\n if (objProper.Count > 0) \n IsTextUnderline = true; // all underlined \n else \n IsTextUnderline = false; // nothing underlined \n } \n"
},
{
"answer_id": 25736503,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " TextRange textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);\n\n bool IsTextUnderline = false;\n bool IsTextStrikethrough = false;\n bool IsTextBold = false;\n bool IsTextItalic = false;\n bool IsSuperscript = false;\n bool IsSubscript = false;\n\n // determine underline property\n if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Strikethrough))\n IsTextStrikethrough = true; // all underlined \n else if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline))\n IsTextUnderline = true; // all strikethrough\n\n // determine bold property\n if (textRange.GetPropertyValue(Inline.FontWeightProperty).Equals(FontWeights.Bold))\n IsTextBold = true; // all bold\n\n // determine if superscript or subscript\n if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Subscript))\n IsSubscript = true; // all subscript\n else if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Superscript))\n IsSuperscript = true; // all superscript\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
202,440
|
<p>I am building a C#/ASP.NET app with an SQL backend. I am on deadline and finishing up my pages, out of left field one of my designers incorporated a full text search on one of my pages. My "searches" up until this point have been filters, being able to narrow a result set by certain factors and column values. </p>
<p>Being that I'm on deadline (you know 3 hours sleep a night, at the point where I am looking like something the cat ate and threw up), I was expecting this page to be very similar to be others and I'm trying to decide whether or not to make a stink. I have never done a full text search on a page before.... is this a mountain to climb or is there a simple solution?</p>
<p>thank you. </p>
|
[
{
"answer_id": 202474,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "SELECT UserName\nFROM Tbl_Users\nWHERE FREETEXT (UserName, 'bob' )\n\nResults:\n\nJimBob\nLittle Bobby Tables\n CONTAINS\n ( { column | * } , '< contains_search_condition >' \n ) \n\n< contains_search_condition > ::= \n { < simple_term > \n | < prefix_term > \n | < generation_term > \n | < proximity_term > \n | < weighted_term > \n } \n | { ( < contains_search_condition > ) \n { AND | AND NOT | OR } < contains_search_condition > [ ...n ] \n } \n\n< simple_term > ::= \n word | \" phrase \"\n\n< prefix term > ::= \n { \"word * \" | \"phrase * \" }\n\n< generation_term > ::= \n FORMSOF ( INFLECTIONAL , < simple_term > [ ,...n ] ) \n\n< proximity_term > ::= \n { < simple_term > | < prefix_term > } \n { { NEAR | ~ } { < simple_term > | < prefix_term > } } [ ...n ] \n\n< weighted_term > ::= \n ISABOUT \n ( { { \n < simple_term > \n | < prefix_term > \n | < generation_term > \n | < proximity_term > \n } \n [ WEIGHT ( weight_value ) ] \n } [ ,...n ] \n ) \n SELECT UserName\nFROM Tbl_Users\nWHERE CONTAINS(UserName, '\"little*\" NEAR tables')\n\nResults:\n\nLittle Bobby Tables\n"
},
{
"answer_id": 202494,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "/*This script will find any text value in the database*/\n/*Output will be directed to the Messages window. Don't forget to look there!!!*/\n\nSET NOCOUNT ON\nDECLARE @valuetosearchfor varchar(128), @objectOwner varchar(64)\nSET @valuetosearchfor = '%staff%' --should be formatted as a like search \nSET @objectOwner = 'dbo'\n\nDECLARE @potentialcolumns TABLE (id int IDENTITY, sql varchar(4000))\n\nINSERT INTO @potentialcolumns (sql)\nSELECT \n ('if exists (select 1 from [' +\n [tabs].[table_schema] + '].[' +\n [tabs].[table_name] + \n '] (NOLOCK) where [' + \n [cols].[column_name] + \n '] like ''' + @valuetosearchfor + ''' ) print ''SELECT * FROM [' +\n [tabs].[table_schema] + '].[' +\n [tabs].[table_name] + \n '] (NOLOCK) WHERE [' + \n [cols].[column_name] + \n '] LIKE ''''' + @valuetosearchfor + '''''' +\n '''') as 'sql'\nFROM information_schema.columns cols\n INNER JOIN information_schema.tables tabs\n ON cols.TABLE_CATALOG = tabs.TABLE_CATALOG\n AND cols.TABLE_SCHEMA = tabs.TABLE_SCHEMA\n AND cols.TABLE_NAME = tabs.TABLE_NAME\nWHERE cols.data_type IN ('char', 'varchar', 'nvchar', 'nvarchar','text','ntext')\n AND tabs.table_schema = @objectOwner\n AND tabs.TABLE_TYPE = 'BASE TABLE'\nORDER BY tabs.table_catalog, tabs.table_name, cols.ordinal_position\n\nDECLARE @count int\nSET @count = (SELECT MAX(id) FROM @potentialcolumns)\nPRINT 'Found ' + CAST(@count as varchar) + ' potential columns.'\nPRINT 'Beginning scan...'\nPRINT ''\nPRINT 'These columns contain the values being searched for...'\nPRINT ''\nDECLARE @iterator int, @sql varchar(4000)\nSET @iterator = 1\nWHILE @iterator <= (SELECT Max(id) FROM @potentialcolumns)\nBEGIN\n SET @sql = (SELECT [sql] FROM @potentialcolumns where [id] = @iterator)\n IF (@sql IS NOT NULL) and (RTRIM(LTRIM(@sql)) <> '')\n BEGIN\n --SELECT @sql --use when checking sql output\n EXEC (@sql)\n END\n SET @iterator = @iterator + 1\nEND\n\nPRINT ''\nPRINT 'Scan completed'\n"
},
{
"answer_id": 202614,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 1,
"selected": false,
"text": "SearchColumn = CONCAT(Title, Summary) SearchColumn SearchColumn = CONCAT(CONCAT(Title,Title), Summary)"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
202,442
|
<p>What tricks can be used to stop javascript callouts to various online services from slowing down page loading?</p>
<p>The obvious solution is to do all the javascript calls at the bottom of the page, but some calls need to happen at the top and in the middle. Another idea that comes to mind is using iframes. </p>
<p>Have you ever had to untangle a site full of externally loading javascript that is so slow that it does not release apache and causes outages on high load? Any tips and tricks?</p>
|
[
{
"answer_id": 202536,
"author": "Christopher Parker",
"author_id": 27583,
"author_profile": "https://Stackoverflow.com/users/27583",
"pm_score": 1,
"selected": false,
"text": "<html>\n <head>\n <title>Test Page</title>\n <script type=\"text/javascript\">\n window.onload = function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n };\n </script>\n <style type=\"text/css\">\n .testClass { color: green; background-color: red; }\n </style>\n </head>\n <body class=\"testClass\">\n <p>Test Content</p>\n </body>\n</html>\n <html>\n <head>\n <title>Test Page</title>\n <script type=\"text/javascript\">\n alert(\"Are you seeing a blank page underneath this alert?\");\n </script>\n <style type=\"text/css\">\n .testClass { color: green; background-color: red; }\n </style>\n </head>\n <body class=\"testClass\">\n <p>Test Content</p>\n </body>\n</html>\n if (!window.addOnLoad)\n{\n window.addOnLoad = function (f) {\n var o = window.onload;\n\n window.onload = function () {\n if (typeof o == \"function\") o();\n f();\n }\n };\n}\n window.addOnLoad(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n dojo.addOnLoad(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n $(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n if (!window.addScript)\n{\n window.addScript = function (src, callback) {\n var head = document.getElementsByTagName(\"head\")[0];\n var script = document.createElement(\"script\");\n script.src = src;\n script.type = \"text/javascript\";\n head.appendChild(script);\n if (typeof callback == \"function\") callback();\n };\n}\n\nwindow.addOnLoad(function () {\n window.addScript(\"example.js\");\n});\n dojo.addOnLoad(function () {\n dojo.require(\"dojo.io.script\");\n dojo.io.script.attach(\"exampleJsId\", \"example.js\");\n});\n $(function () {\n $.getScript(\"example.js\");\n});\n"
},
{
"answer_id": 202548,
"author": "Michael",
"author_id": 27966,
"author_profile": "https://Stackoverflow.com/users/27966",
"pm_score": 2,
"selected": false,
"text": "$(function(){\n // Document is ready\n});\n jQuery(function($) {\n // Your code using failsafe $ alias here...\n});\n jQuery(function($) {\n $.getScript(\"http://www.yourdomain.com/scripts/somescript1.js\"); \n $.getScript(\"http://www.yourdomain.com/scripts/somescript2.js\"); \n});\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
202,459
|
<p>I stumbled across this code and am too proud to go and ask the author what it means.</p>
<pre><code>Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
</code></pre>
<p>What is <code>gcnew</code> and how important is it to use that instead of simply <code>new</code>? (I'm also stumped by the caret; I asked about that <a href="https://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-cnet">over here</a>.)</p>
|
[
{
"answer_id": 202469,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "gcnew new delete gcnew new"
},
{
"answer_id": 36863084,
"author": "user2796283",
"author_id": 2796283,
"author_profile": "https://Stackoverflow.com/users/2796283",
"pm_score": 3,
"selected": false,
"text": "// pointer to new std::string object -> memory is not garbage-collected\nstd::string* strPtr = new std::string;\n\n// pointer to System::String object -> memory is garbage-collected\nSystem::String^ manStr = gcnew System::String;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
202,463
|
<p>I just came across this code and a few Google searches turn up no explanation of this mysterious (to me) syntax.</p>
<pre><code>Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
</code></pre>
<p>What the heck does the caret mean? (The <code>gcnew</code> is also new to me, and I asked about that <a href="https://stackoverflow.com/questions/202459/what-is-gcnew">here</a>.)</p>
|
[
{
"answer_id": 202487,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "^"
},
{
"answer_id": 14378351,
"author": "salomon",
"author_id": 958953,
"author_profile": "https://Stackoverflow.com/users/958953",
"pm_score": 7,
"selected": false,
"text": "// here normal pointer\nP* ptr = new P; // usual pointer allocated on heap\nP& nat = *ptr; // object on heap bind to native object\n\n//.. here CLI managed \nMO^ mngd = gcnew MO; // allocate on CLI heap\nMO% rr = *mngd; // object on CLI heap reference to gc-lvalue\n % ^ & * & % &ptr P* %mngd MO^"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
202,470
|
<p>In a script, when a command-let or other executable statement errors out, is there a try/catch type of mechanism to recover from these errors? I haven't run across one in the documentation.</p>
|
[
{
"answer_id": 202498,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "Trap [exception-type] {}"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
] |
202,471
|
<p>I'm trying to subclass NSCell for use in a NSTableView. The cell I want to create is fairly complicated so it would be very useful if I could design it in Interface Builder and then load the NSCell from a nib.</p>
<p>Is this possible? How do I do it?</p>
|
[
{
"answer_id": 203292,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 0,
"selected": false,
"text": "/* example of a silly way to load a UITableViewCell from a standalone nib */\n\n+ (CEntryTableViewCell *)cell\n{\n// TODO -- this is really silly.\nNSArray *theObjects = [[NSBundle mainBundle] loadNibNamed:@\"EntryTableViewCell\" owner:self options:NULL];\nfor (id theObject in theObjects)\n if ([theObject isKindOfClass:self])\n return(theObject);\nNSAssert(NO, @\"Could not find object of class CEntryTableViewCell in nib\");\nreturn(NULL);\n}\n"
},
{
"answer_id": 203760,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 3,
"selected": false,
"text": "YourCustomCellClass *cell = (YourCustomCellClass *)[tableView dequeueReusableCellWithIdentifier:<IDYouSetInXIBFile>];\nif ( cell == nil )\n{\n NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:<YourXIBName> owner:self options:nil];\n id firstObject = [topLevelObjects objectAtIndex:0];\n if ( [ firstObject isKindOfClass:[UITableViewCell class]] )\n cell = firstObject; \n else cell = [topLevelObjects objectAtIndex:1];\n}\n"
},
{
"answer_id": 237171,
"author": "Wil Shipley",
"author_id": 30602,
"author_profile": "https://Stackoverflow.com/users/30602",
"pm_score": 3,
"selected": false,
"text": "NSCells NSViews NSView NSCells NSViews NSCell NSCells NSViews"
},
{
"answer_id": 394980,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "UITableViewCell tableviewcontroller IBOutlet @interface KuguTableViewController : UITableViewController {\n IBOutlet UITableViewCell *customTypeCell;\n}\n\n@property (readonly) UITableViewCell *customTypeCell;\n cellForRowAtIndexPath static NSString *CellIdentifier = @\"CustomCell\"\ncell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\nif (cell == nil)\n cell = customTypeCell;\n cell.reuseIdentifier = CellIdentifier;\n"
},
{
"answer_id": 5807159,
"author": "JJD",
"author_id": 356895,
"author_profile": "https://Stackoverflow.com/users/356895",
"pm_score": 1,
"selected": false,
"text": "NSTextFieldCell NSTableViewDataSource NSTableViewDelegate Bindings ArrayController InterfaceBuilder"
},
{
"answer_id": 16937938,
"author": "supertrall",
"author_id": 2455166,
"author_profile": "https://Stackoverflow.com/users/2455166",
"pm_score": 0,
"selected": false,
"text": "NSViewController TableViewCell.h TableViewCell.h -(void)setText:(NSString *)text image:(NSImage *)image\n #import \"TableViewCell.h\" -(NSView *)tableView:viewForTableColumn:row: write: NSImage *img = //some image\nTableViewCell *cell = [[TableViewCell alloc] initWithWindowNibName:@\"TableViewCell\"];\ncell.view.init;\n[cell setText:@\"some text\" image:img];\nreturn cell;\n"
},
{
"answer_id": 23515705,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "(void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,481
|
<p>How can I use HttpWebRequest (.NET, C#) asynchronously?</p>
|
[
{
"answer_id": 202896,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 8,
"selected": true,
"text": "HttpWebRequest.BeginGetResponse() HttpWebRequest webRequest;\n\nvoid StartWebRequest()\n{\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n webRequest.EndGetResponse(result);\n}\n EndGetResponse()"
},
{
"answer_id": 4434127,
"author": "xlarsx",
"author_id": 541167,
"author_profile": "https://Stackoverflow.com/users/541167",
"pm_score": 6,
"selected": false,
"text": "HttpWebRequest webRequest;\n\nvoid StartWebRequest()\n{\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n webRequest.EndGetResponse(result);\n}\n void StartWebRequest()\n{\n HttpWebRequest webRequest = ...;\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), webRequest);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;\n}\n"
},
{
"answer_id": 12776096,
"author": "Sten Petrov",
"author_id": 1416035,
"author_profile": "https://Stackoverflow.com/users/1416035",
"pm_score": 2,
"selected": false,
"text": "public void GetResponseAsync (HttpWebRequest request, Action<HttpWebResponse> gotResponse)\n {\n if (request != null) { \n request.BeginGetRequestStream ((r) => {\n try { // there's a try/catch here because execution path is different from invokation one, exception here may cause a crash\n HttpWebResponse response = request.EndGetResponse (r);\n if (gotResponse != null) \n gotResponse (response);\n } catch (Exception x) {\n Console.WriteLine (\"Unable to get response for '\" + request.RequestUri + \"' Err: \" + x);\n }\n }, null);\n } \n }\n"
},
{
"answer_id": 13963255,
"author": "Isak",
"author_id": 371698,
"author_profile": "https://Stackoverflow.com/users/371698",
"pm_score": 6,
"selected": false,
"text": "BeginGetResponse() void DoWithResponse(HttpWebRequest request, Action<HttpWebResponse> responseAction)\n{\n Action wrapperAction = () =>\n {\n request.BeginGetResponse(new AsyncCallback((iar) =>\n {\n var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);\n responseAction(response);\n }), request);\n };\n wrapperAction.BeginInvoke(new AsyncCallback((iar) =>\n {\n var action = (Action)iar.AsyncState;\n action.EndInvoke(iar);\n }), wrapperAction);\n}\n HttpWebRequest request;\n// init your request...then:\nDoWithResponse(request, (response) => {\n var body = new StreamReader(response.GetResponseStream()).ReadToEnd();\n Console.Write(body);\n});\n"
},
{
"answer_id": 15254807,
"author": "eggbert",
"author_id": 519074,
"author_profile": "https://Stackoverflow.com/users/519074",
"pm_score": 3,
"selected": false,
"text": "var worker = new BackgroundWorker();\n\nworker.DoWork += (sender, args) => {\n args.Result = new WebClient().DownloadString(settings.test_url);\n};\n\nworker.RunWorkerCompleted += (sender, e) => {\n if (e.Error != null) {\n connectivityLabel.Text = \"Error: \" + e.Error.Message;\n } else {\n connectivityLabel.Text = \"Connectivity OK\";\n Log.d(\"result:\" + e.Result);\n }\n};\n\nconnectivityLabel.Text = \"Testing Connectivity\";\nworker.RunWorkerAsync();\n"
},
{
"answer_id": 23004036,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 6,
"selected": false,
"text": "var request = WebRequest.Create(\"http://www.stackoverflow.com\");\nvar response = (HttpWebResponse) await Task.Factory\n .FromAsync<WebResponse>(request.BeginGetResponse,\n request.EndGetResponse,\n null);\nDebug.Assert(response.StatusCode == HttpStatusCode.OK);\n Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,\n request.EndGetResponse,\n null)\n .ContinueWith(task =>\n {\n var response = (HttpWebResponse) task.Result;\n Debug.Assert(response.StatusCode == HttpStatusCode.OK);\n });\n"
},
{
"answer_id": 46833750,
"author": "tronman",
"author_id": 244104,
"author_profile": "https://Stackoverflow.com/users/244104",
"pm_score": 3,
"selected": false,
"text": "Task private async Task<String> MakeRequestAsync(String url)\n{ \n String responseText = await Task.Run(() =>\n {\n try\n {\n HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\n WebResponse response = request.GetResponse(); \n Stream responseStream = response.GetResponseStream();\n return new StreamReader(responseStream).ReadToEnd(); \n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: \" + e.Message);\n }\n return null;\n });\n\n return responseText;\n}\n String response = await MakeRequestAsync(\"http://example.com/\");\n WebRequest.GetResponseAsync() WebRequest.GetResponse() Dispose()"
},
{
"answer_id": 49225438,
"author": "dragansr",
"author_id": 1924224,
"author_profile": "https://Stackoverflow.com/users/1924224",
"pm_score": 3,
"selected": false,
"text": "public static async Task<byte[]> GetBytesAsync(string url) {\n var request = (HttpWebRequest)WebRequest.Create(url);\n using (var response = await request.GetResponseAsync())\n using (var content = new MemoryStream())\n using (var responseStream = response.GetResponseStream()) {\n await responseStream.CopyToAsync(content);\n return content.ToArray();\n }\n}\n\npublic static async Task<string> GetStringAsync(string url) {\n var bytes = await GetBytesAsync(url);\n return Encoding.UTF8.GetString(bytes, 0, bytes.Length);\n}\n"
},
{
"answer_id": 70461277,
"author": "Raiio",
"author_id": 17747759,
"author_profile": "https://Stackoverflow.com/users/17747759",
"pm_score": 0,
"selected": false,
"text": "private void DoWithResponseAsync(HttpWebRequest request, Action<HttpWebResponse> responseAction)\n{\n Action wrapperAction = () =>\n {\n request.BeginGetResponse(new AsyncCallback((iar) =>\n {\n HttpWebResponse response;\n try\n {\n response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);\n }\n catch (WebException ex)\n {\n // It needs to be done like this in order to read responses with error status:\n response = ex.Response as HttpWebResponse;\n }\n responseAction(response);\n }), request);\n };\n wrapperAction.BeginInvoke(new AsyncCallback((iar) =>\n {\n var action = (Action)iar.AsyncState;\n action.EndInvoke(iar);\n }), wrapperAction);\n}\n HttpWebRequest request;\n// init your request...then:\nDoWithResponse(request, (response) => {\n var body = new StreamReader(response.GetResponseStream()).ReadToEnd();\n Console.Write(body);\n});\n"
},
{
"answer_id": 70746121,
"author": "Jacksonkr",
"author_id": 332578,
"author_profile": "https://Stackoverflow.com/users/332578",
"pm_score": -1,
"selected": false,
"text": " string uri = \"http://some.place.online\";\n\n using (UnityWebRequest uwr = UnityWebRequest.Get(uri))\n {\n var asyncOp = uwr.SendWebRequest();\n while (asyncOp.isDone == false) await Task.Delay(1000 / 30); // 30 hertz\n\n if(uwr.result == UnityWebRequest.Result.Success) return uwr.downloadHandler.text;\n Debug.LogError(uwr.error);\n }\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
202,491
|
<p>Is there a way to automatically increment the "minimum required version" fields in a ClickOnce deployment to always equal the current build number? Basically, I always want my deployment to be automatically updated at launch.</p>
<p>I suspect I'm going to need a some pre-/post-build events, but I hope there's an easier way.</p>
|
[
{
"answer_id": 224522,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 3,
"selected": false,
"text": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup>\n <Util-VersionMajor>1</Util-VersionMajor>\n <Util-VersionMinor>11</Util-VersionMinor>\n <Util-VersionBuild>25</Util-VersionBuild>\n <Util-VersionRevision>0</Util-VersionRevision>\n <Util-VersionDots>$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)</Util-VersionDots>\n <Util-VersionUnders>$(Util-VersionMajor)_$(Util-VersionMinor)_$(Util-VersionBuild)_$(Util-VersionRevision)</Util-VersionUnders>\n <MinimumRequiredVersion>$(Util-VersionDots)</MinimumRequiredVersion>\n <ApplicationVersion>$(Util-VersionDots)</ApplicationVersion>\n <ApplicationRevision>$(Util-VersionRevision)</ApplicationRevision>\n </PropertyGroup>\n</Project>\n <Target Name=\"IncrementVersion\" DependsOnTargets=\"Build\" Condition=\"'$(BuildingInsideVisualStudio)'==''\">\n <ItemGroup>\n <Util-VersionProjectFileItem Include=\"$(Util-VersionProjectFile)\" />\n </ItemGroup>\n <PropertyGroup>\n <Util-VersionProjectFileFullPath>@(Util-VersionProjectFileItem->'%(FullPath)')</Util-VersionProjectFileFullPath>\n </PropertyGroup>\n <Exec Command=\""$(TfCommand)" get /overwrite /force /noprompt "$(Util-VersionProjectFileFullPath)"\" Outputs=\"\" />\n <Exec Command=\""$(TfCommand)" checkout /lock:checkout "$(Util-VersionProjectFileFullPath)"\" Outputs=\"\" />\n <Version Major=\"$(Util-VersionMajor)\" Minor=\"$(Util-VersionMinor)\" Build=\"$(Util-VersionBuild)\" Revision=\"$(Util-VersionRevision)\" RevisionType=\"None\" BuildType=\"Increment\">\n <Output TaskParameter=\"Major\" PropertyName=\"Util-VersionMajor\" />\n <Output TaskParameter=\"Minor\" PropertyName=\"Util-VersionMinor\" />\n <Output TaskParameter=\"Build\" PropertyName=\"Util-VersionBuild\" />\n <Output TaskParameter=\"Revision\" PropertyName=\"Util-VersionRevision\" />\n </Version>\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionMajor\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionMajor)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionMinor\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionMinor)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionBuild\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionBuild)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionRevision\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionRevision)\" />\n <Exec Command=\""$(TfCommand)" checkin /override:AutoBuildIncrement /comment:***NO_CI*** "$(Util-VersionProjectFileFullPath)"\" />\n <Exec Command=\""$(TfCommand)" get /overwrite /force /noprompt "$(Util-AssemblyInfoFile)"\" Outputs=\"\" />\n <Exec Command=\""$(TfCommand)" checkout /lock:checkout "$(Util-AssemblyInfoFile)"\" Outputs=\"\" />\n <AssemblyInfo CodeLanguage=\"CS\" OutputFile=\"$(Util-AssemblyInfoFile)\" AssemblyConfiguration=\"$(Configuration)\" AssemblyVersion=\"$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)\" AssemblyFileVersion=\"$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)\" />\n <Exec Command=\""$(TfCommand)" checkin /override:AutoBuildIncrement /comment:***NO_CI*** "$(Util-AssemblyInfoFile)"\" />\n </Target>\n"
},
{
"answer_id": 231129,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 3,
"selected": false,
"text": " Public Sub Publish()\n Try\n Dim startProjName As String = Nothing\n Dim targetProj As Project = Nothing\n Dim soln As Solution2 = TryCast(Me._applicationObject.DTE.Solution, Solution2)\n If soln IsNot Nothing Then\n For Each prop As [Property] In soln.Properties\n If prop.Name = \"StartupProject\" Then\n startProjName = prop.Value.ToString()\n Exit For\n End If\n Next\n If startProjName IsNot Nothing Then\n For Each proj As Project In soln.Projects\n If proj.Name = startProjName Then\n targetProj = proj\n Exit For\n End If\n Next\n If targetProj IsNot Nothing Then\n Dim currAssemVersionString As String = targetProj.Properties.Item(\"AssemblyVersion\").Value.ToString\n Dim currAssemVer As New Version(currAssemVersionString)\n Dim newAssemVer As New Version(currAssemVer.Major, currAssemVer.Minor, currAssemVer.Build, currAssemVer.Revision + 1)\n targetProj.Properties.Item(\"AssemblyVersion\").Value = newAssemVer.ToString()\n targetProj.Properties.Item(\"AssemblyFileVersion\").Value = newAssemVer.ToString()\n Dim publishProps As Properties = TryCast(targetProj.Properties.Item(\"Publish\").Value, Properties)\n Dim shouldPublish As Boolean = False\n If publishProps IsNot Nothing Then\n shouldPublish = CBool(publishProps.Item(\"Install\").Value)\n If shouldPublish Then\n targetProj.Properties.Item(\"GenerateManifests\").Value = \"true\"\n publishProps.Item(\"ApplicationVersion\").Value = newAssemVer.ToString()\n publishProps.Item(\"MinimumRequiredVersion\").Value = newAssemVer.ToString()\n publishProps.Item(\"ApplicationRevision\").Value = newAssemVer.Revision.ToString()\n End If\n End If\n targetProj.Save()\n Dim build As SolutionBuild2 = TryCast(soln.SolutionBuild, SolutionBuild2)\n If build IsNot Nothing Then\n build.Clean(True)\n build.Build(True)\n If shouldPublish Then\n If build.LastBuildInfo = 0 Then\n\n build.Publish(True)\n End If\n End If\n End If\n End If\n End If\n End If\n Catch ex As Exception\n MsgBox(ex.ToString)\n End Try\n End Sub\n"
},
{
"answer_id": 495458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Build.Utilities;\nusing Microsoft.Build.Framework;\n\nnamespace SynchBuild\n{\n public class RemoveAsterisk : Task\n {\n private string myVersion;\n\n [Required]\n public string Version\n {\n set{myVersion = value;}\n }\n\n\n [Output]\n public string ReturnValue\n {\n get { return myVersion.Replace(\"*\", \"\"); }\n }\n\n\n public override bool Execute()\n {\n return true;\n }\n }\n}\n <UsingTask AssemblyFile=\"$(MSBuildExtensionsPath)\\WegmansBuildTasks\\SynchBuild.dll\" TaskName=\"SynchBuild.RemoveAsterisk\" />\n <Target Name=\"GenerateDeploymentManifest\" DependsOnTargets=\"GenerateApplicationManifest\" Inputs=\"
 $(MSBuildAllProjects);
 @(ApplicationManifest)
 \" Outputs=\"@(DeployManifest)\">\n <RemoveAsterisk Version=\"$(ApplicationVersion)$(ApplicationRevision)\">\n <Output TaskParameter=\"ReturnValue\" PropertyName=\"MinimumRequiredVersion\" />\n </RemoveAsterisk>\n <GenerateDeploymentManifest MinimumRequiredVersion=\"$(MinimumRequiredVersion)\" AssemblyName=\"$(_DeploymentDeployManifestIdentity)\" AssemblyVersion=\"$(_DeploymentManifestVersion)\" CreateDesktopShortcut=\"$(CreateDesktopShortcut)\" DeploymentUrl=\"$(_DeploymentFormattedDeploymentUrl)\" Description=\"$(Description)\" DisallowUrlActivation=\"$(DisallowUrlActivation)\" EntryPoint=\"@(_DeploymentResolvedDeploymentManifestEntryPoint)\" ErrorReportUrl=\"$(_DeploymentFormattedErrorReportUrl)\" Install=\"$(Install)\" MapFileExtensions=\"$(MapFileExtensions)\" MaxTargetPath=\"$(MaxTargetPath)\" OutputManifest=\"@(DeployManifest)\" Platform=\"$(PlatformTarget)\" Product=\"$(ProductName)\" Publisher=\"$(PublisherName)\" SuiteName=\"$(SuiteName)\" SupportUrl=\"$(_DeploymentFormattedSupportUrl)\" TargetCulture=\"$(TargetCulture)\" TargetFrameworkVersion=\"$(TargetFrameworkVersion)\" TrustUrlParameters=\"$(TrustUrlParameters)\" UpdateEnabled=\"$(UpdateEnabled)\" UpdateInterval=\"$(_DeploymentBuiltUpdateInterval)\" UpdateMode=\"$(UpdateMode)\" UpdateUnit=\"$(_DeploymentBuiltUpdateIntervalUnits)\" Condition=\"'$(GenerateClickOnceManifests)'=='true'\">\n <Output TaskParameter=\"OutputManifest\" ItemName=\"FileWrites\" />\n</GenerateDeploymentManifest>\n </Target>\n"
},
{
"answer_id": 13483142,
"author": "Kev",
"author_id": 745813,
"author_profile": "https://Stackoverflow.com/users/745813",
"pm_score": 6,
"selected": true,
"text": " <Target Name=\"AutoSetMinimumRequiredVersion\" BeforeTargets=\"GenerateDeploymentManifest\">\n <FormatVersion Version=\"$(ApplicationVersion)\" Revision=\"$(ApplicationRevision)\">\n <Output PropertyName=\"MinimumRequiredVersion\" TaskParameter=\"OutputVersion\" />\n </FormatVersion>\n <FormatVersion Version=\"$(ApplicationVersion)\" Revision=\"$(ApplicationRevision)\">\n <Output PropertyName=\"_DeploymentBuiltMinimumRequiredVersion\" TaskParameter=\"OutputVersion\" />\n </FormatVersion>\n </Target>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6897/"
] |
202,502
|
<p>We have recently migrated a large, high demand web application to Tomcat 5.5 from Tomcat 4 and have noticed some peculiar slowdown behavior that appears to be related to JVM pauses. In order to run our application and support increased load over time on Tomcat 4, many not so standard JVM parameters were set and tuned as per the below, and I am hoping someone with Tomcat JVM tuning experience can comment on anything that would likely be detrimental to a Tomcat 5.5 install. Note also that some of these could be carry over from previous versions of Java (we were running Tomcat 4 on Java 1.6 with these parameters successfully for some time, but some may have been introduced to help garbage collection on Java 1.4 which was the basis of our Tomcat 4 install for a long time, and may now doing more harm than good).</p>
<p>Some notes:</p>
<ul>
<li>Application memory footprint is
around 1GB, probably slightly over.</li>
<li>CPU is not an issue - all machines
serving the app (load balanced) are
< 30% CPU</li>
<li>Lots of headroom on physical memory on the machines.</li>
<li>-XX:MaxPermSize=512m was the only parameter added as part of the 5.5 upgrade and was reactive to an outofmemory permgen space issue (which it solved).</li>
<li>Running on Java 1.6, Solaris OS</li>
</ul>
<p>-server -Xms1280m -Xmx1280m -XX:MaxPermSize=512m -XX:ParallelGCThreads=20 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX:TargetSurvivorRatio=75 -XX:MaxTenuringThreshold=0 -XX:+AggressiveOpts -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:-TraceClassUnloading -Dsun.io.useCanonCaches=false -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 </p>
|
[
{
"answer_id": 204756,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "conf/server.xml <Connector port=\"8080\" maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\" ...\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
] |
202,508
|
<p>Rather than population said DOM object with an external page such as HTML CFM or PHP, what if I simply want to send text?</p>
<p>I've tried:</p>
<p>$("#myDOMObject").val("some text");</p>
<p>No errors, but the object value doesn't update either.</p>
|
[
{
"answer_id": 202524,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "$(\"#myDOMObject\").text(\"some text\");"
},
{
"answer_id": 202543,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "jQuery(your_dom_object).text('Hello World!');\n $('#the_id_of_your_dom_object').text('Hello World');\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
202,540
|
<p>We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.</p>
<p>This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?</p>
<p>Thanks for any info.</p>
|
[
{
"answer_id": 202601,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": true,
"text": "<?php\n\necho PHP_INT_SIZE, \"\\n\", PHP_INT_MAX;\n\n?>\n <?php\n\necho intval( \"12345678901234567890\" );\n// prints 2147483647, the max value for a 32 bit signed int.\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27989/"
] |
202,547
|
<p>I am writing a command-line tool for Windows that uses libcurl to download files from the internet.</p>
<p>Obviously, the downloading doesn't work when the user is behind a proxy server, because the proxy needs to be configured. I want to keep my tool as simple as possible however, and not have to burden the user with having to configure the proxy. My tool doesn't even have a config file, so the user would otherwise have to pass in the proxy settings on every command, or set an environment variable or somesuch -- way too much hassle.</p>
<p>So I thought, everyone's browser will usually already be set up properly, proxy configured and everything. This will be true for even the most basic user because otherwise "their internet wouldn't work".</p>
<p>So I figure that I can find out whether to use a proxy by looking at IE's proxy settings.</p>
<p>How do I go about this? More specifically:</p>
<ul>
<li>Is there one set of "proxy settings" in Windows, used by all browsers (probably IE's), or would I have to write different routines for IE, Firefox, Opera, etc?</li>
<li>I know that I can probably read the values directly out of the appropriate registry locations if they are configured manually, but does this also work with "automatically detect proxy server?" Do I even have to bother with that option, or is it (almost) never used?</li>
</ul>
<p>Before people start suggesting alternatives: I'm using C, so I'm limited to the Win32 API, and I really really want to keep using C and libcurl.</p>
|
[
{
"answer_id": 202608,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 1,
"selected": false,
"text": "using System.Net;\n\nstring url = \"http://www.example.com\";\nWebClient client = new WebClient();\nbyte[] fileBuffer = client.DownloadFile(url);\n"
},
{
"answer_id": 203008,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 6,
"selected": true,
"text": "if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) )\n{\n if( ieProxyConfig.fAutoDetect )\n {\n fAutoProxy = TRUE;\n }\n\n if( ieProxyConfig.lpszAutoConfigUrl != NULL )\n {\n fAutoProxy = TRUE;\n autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;\n }\n}\nelse\n{\n // use autoproxy\n fAutoProxy = TRUE;\n}\n\nif( fAutoProxy )\n{\n if ( autoProxyOptions.lpszAutoConfigUrl != NULL )\n {\n autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;\n }\n else\n {\n autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;\n autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;\n }\n\n // basic flags you almost always want\n autoProxyOptions.fAutoLogonIfChallenged = TRUE;\n\n // here we reset fAutoProxy in case an auto-proxy isn't actually\n // configured for this url\n fAutoProxy = WinHttpGetProxyForUrl( hiOpen, pwszUrl, &autoProxyOptions, &autoProxyInfo );\n}\n\nif ( fAutoProxy )\n{\n // set proxy options for libcurl based on autoProxyInfo\n}\nelse\n{\n if( ieProxyConfig.lpszProxy != NULL )\n {\n // IE has an explicit proxy. set proxy options for libcurl here\n // based on ieProxyConfig\n //\n // note that sometimes IE gives just a single or double colon\n // for proxy or bypass list, which means \"no proxy\"\n }\n else\n {\n // there is no auto proxy and no manually configured proxy\n }\n}\n"
},
{
"answer_id": 11750887,
"author": "Maksym Kozlenko",
"author_id": 171847,
"author_profile": "https://Stackoverflow.com/users/171847",
"pm_score": 2,
"selected": false,
"text": "WinHttpGetIEProxyConfigForCurrentUser winhttp.dll [TestClass]\npublic class UnitTest1\n{\n [StructLayout(LayoutKind.Sequential)]\n public struct WinhttpCurrentUserIeProxyConfig\n {\n [MarshalAs(UnmanagedType.Bool)]\n public bool AutoDetect;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string AutoConfigUrl;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string Proxy;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string ProxyBypass;\n\n }\n\n [DllImport(\"winhttp.dll\", SetLastError = true)]\n static extern bool WinHttpGetIEProxyConfigForCurrentUser(ref WinhttpCurrentUserIeProxyConfig pProxyConfig);\n\n [TestMethod]\n public void TestMethod1()\n {\n var config = new WinhttpCurrentUserIeProxyConfig();\n\n WinHttpGetIEProxyConfigForCurrentUser(ref config);\n\n Console.WriteLine(config.Proxy);\n Console.WriteLine(config.AutoConfigUrl);\n Console.WriteLine(config.AutoDetect);\n Console.WriteLine(config.ProxyBypass);\n }\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2474/"
] |
202,552
|
<p>How do you get a pointer to the .text section of memory for a program from within that program? I also need the length of the section to do a "Flash to Memory" compare as part of a continuous selftest that runs in the background.</p>
<p>The toolset automatically generates the linker .cmd file for the tools I'm using, and the Board Support Package for the board I'm using requires I use the generated .cmd file instead of making my own. (No make file either to add a script to muck with it afterwords.)</p>
<p>Edit:
I'm working with a TI TMS 6713 DSP using the code composer 3.1 environment. The card I'm using was contracted by our customer and produced by another organization so I can't really point you to any info on it. However the BSP is dependant upon TI's "DSP BIOS" config tool, and I can't really fudge the settings too much without digging into an out of scope effort.</p>
|
[
{
"answer_id": 202572,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 2,
"selected": false,
"text": " __FlashStart = .;\n extern unsigned long int _FlashStart;\nunsigned long int address = (unsigned long int)&_FlashStart;\n"
},
{
"answer_id": 203670,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "#include <bfd.h>\n\nbfd *abfd;\nasection *p;\nchar *filename = \"/path/to/my/file\";\n\nif ((abfd = bfd_openr(filename, NULL)) == NULL) {\n /* ... error handling */\n}\n\nif (!bfd_check_format (abfd, bfd_object)) {\n /* ... error handling */\n}\n\nfor (p = abfd->sections; p != NULL; p = p->next) {\n bfd_vma base_addr = bfd_section_vma(abfd, p);\n bfd_size_type size = bfd_section_size (abfd, p);\n const char *name = bfd_section_name(abfd, p);\n flagword flags = bfd_get_section_flags(abfd, p);\n\n if (flags & SEC_CODE) {\n printf(\"%s: addr=%p size=%d\\n\", name, base_addr, size);\n }\n}\n"
},
{
"answer_id": 203700,
"author": "LarryH",
"author_id": 13923,
"author_profile": "https://Stackoverflow.com/users/13923",
"pm_score": 1,
"selected": false,
"text": "__sfb(...) __sfe(...) __sfs(...)"
},
{
"answer_id": 206598,
"author": "ZungBang",
"author_id": 27831,
"author_profile": "https://Stackoverflow.com/users/27831",
"pm_score": 1,
"selected": false,
"text": "__text__ __etext__ .text .map"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134597/"
] |
202,557
|
<p>Assuming a fluid layout is not an option (since that is a different discussion all together), what is the recommended width for a site layout? What are the pros and cons of different sizes?</p>
|
[
{
"answer_id": 202571,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 1,
"selected": false,
"text": "800px 1000px 1024x768 1024x768"
},
{
"answer_id": 202575,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 6,
"selected": true,
"text": "960px 1024x768"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007/"
] |
202,560
|
<p>So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields. </p>
<p>One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:</p>
<pre><code>var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");
</code></pre>
<p>As for static fields, is creating singelton-objects their best use? </p>
|
[
{
"answer_id": 202585,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 5,
"selected": false,
"text": "this Point::distance(Point a, Point b);"
},
{
"answer_id": 202587,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 3,
"selected": false,
"text": "static"
},
{
"answer_id": 202689,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 1,
"selected": false,
"text": "class AbstractClass {\n static createObject(int i) {\n if (i==1) {\n return new ConcreteClass1();\n } else if (i==2) {\n return new ConcreteClass2();\n }\n }\n}\n"
},
{
"answer_id": 203880,
"author": "David Grayson",
"author_id": 28128,
"author_profile": "https://Stackoverflow.com/users/28128",
"pm_score": 2,
"selected": false,
"text": "class Foo\n{\n public Foo(){}\n public static void bar(){} // valid with or without 'static'\n public void nonStatic(){ bar(); }\n}\n\n...\nFoo a = new Foo();\na.bar();\n"
},
{
"answer_id": 49628227,
"author": "A Coder",
"author_id": 1083030,
"author_profile": "https://Stackoverflow.com/users/1083030",
"pm_score": 3,
"selected": false,
"text": "Math GetNumberOfObjects()"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
] |
202,586
|
<p>I've used <a href="http://members.fortunecity.com/neshkov/dj.html" rel="noreferrer">DJ Java Decompiler</a>, which has a handy GUI, but it seems as if the latest version is only a trial and forces you to purchase the software after some period of days (I recall using an earlier free version about a year ago at a previous job).</p>
<p>I'm aware of Jad and Jadclipse, but what I loved about DJ Java Decompiler was that it integrated with Windows Explorer - so I could simply open up a JAR in something like WinRAR, navigate thru the packages, and double-click on a .class file to view it's decompiled source.</p>
<p>Can anyone suggest other good, free, .class viewers? The criteria I have in mind for these would be: </p>
<ul>
<li>GUI-based</li>
<li>Integrates to Windows Explorer (so I don't have to run some command-line options like with JAD)</li>
<li>optional - can also show raw JVM bytecode commands </li>
</ul>
<p>In other words - I'd like to find the closest thing to <a href="http://www.red-gate.com/products/reflector/index.htm" rel="noreferrer">.NET Reflector</a> for Java as possible.</p>
|
[
{
"answer_id": 17206060,
"author": "Happy",
"author_id": 2412606,
"author_profile": "https://Stackoverflow.com/users/2412606",
"pm_score": 0,
"selected": false,
"text": ".class class"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
202,605
|
<p>What is the best or most concise method for returning a string repeated an arbitrary amount of times?</p>
<p>The following is my best shot so far:</p>
<pre><code>function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
</code></pre>
|
[
{
"answer_id": 202626,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "function repeat(s, n) { var r=\"\"; for (var a=0;a<n;a++) r+=s; return r;}\n"
},
{
"answer_id": 202627,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 9,
"selected": false,
"text": "String.prototype.repeat = function( num )\n{\n return new Array( num + 1 ).join( this );\n}\n\nalert( \"string to repeat\\n\".repeat( 4 ) );\n"
},
{
"answer_id": 1411966,
"author": "BitOfUniverse",
"author_id": 172159,
"author_profile": "https://Stackoverflow.com/users/172159",
"pm_score": 3,
"selected": false,
"text": "/** \n@desc: repeat string \n@param: n - times \n@param: d - delimiter \n*/\n\nString.prototype.repeat = function (n, d) {\n return --n ? this + (d || '') + this.repeat(n, d) : '' + this\n};\n"
},
{
"answer_id": 2433358,
"author": "antichris",
"author_id": 292382,
"author_profile": "https://Stackoverflow.com/users/292382",
"pm_score": 4,
"selected": false,
"text": "String.prototype.repeat = function(num) {\n return new Array(isNaN(num)? 1 : ++num).join(this);\n }\n var foo = 'bar';\nalert(foo.repeat(3)); // Will work, \"barbarbar\"\nalert(foo.repeat('3')); // Same as above\nalert(foo.repeat(true)); // Same as foo.repeat(1)\n\nalert(foo.repeat(0)); // This and all the following return an empty\nalert(foo.repeat(false)); // string while not causing an exception\nalert(foo.repeat(null));\nalert(foo.repeat(undefined));\nalert(foo.repeat({})); // Object\nalert(foo.repeat(function () {})); // Function\n ++num"
},
{
"answer_id": 4152613,
"author": "wnrph",
"author_id": 345520,
"author_profile": "https://Stackoverflow.com/users/345520",
"pm_score": 5,
"selected": false,
"text": "String.prototype.repeat = function(times){\n var result=\"\";\n var pattern=this;\n while (times > 0) {\n if (times&1)\n result+=pattern;\n times>>=1;\n pattern+=pattern;\n }\n return result;\n};\n"
},
{
"answer_id": 5450113,
"author": "disfated",
"author_id": 489553,
"author_profile": "https://Stackoverflow.com/users/489553",
"pm_score": 8,
"selected": false,
"text": "String.prototype.repeat = function(count) {\n if (count < 1) return '';\n var result = '', pattern = this.valueOf();\n while (count > 1) {\n if (count & 1) result += pattern;\n count >>= 1, pattern += pattern;\n }\n return result + pattern;\n};\n function repeat(pattern, count) {\n if (count < 1) return '';\n var result = '';\n while (count > 1) {\n if (count & 1) result += pattern;\n count >>= 1, pattern += pattern;\n }\n return result + pattern;\n}\n count new Array(count + 1).join(string) pattern = this pattern = this.valueOf() if (count < 1) count count"
},
{
"answer_id": 6557722,
"author": "John",
"author_id": 825985,
"author_profile": "https://Stackoverflow.com/users/825985",
"pm_score": 2,
"selected": false,
"text": "String.prototype.repeat = function(n,s) {\ns = s || \"\"\nif(n>0) {\n s += this\n s = this.repeat(--n,s)\n}\nreturn s}\n"
},
{
"answer_id": 7649473,
"author": "Fordi",
"author_id": 353872,
"author_profile": "https://Stackoverflow.com/users/353872",
"pm_score": 1,
"selected": false,
"text": "function repeat(n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n with(Math) { return repeat(floor(n/2), s)+repeat(ceil(n/2), s); }\n}\n"
},
{
"answer_id": 7649897,
"author": "Fordi",
"author_id": 353872,
"author_profile": "https://Stackoverflow.com/users/353872",
"pm_score": 2,
"selected": false,
"text": "var repeatMethods = {\n control: function (n,s) {\n /* all of these lines are common to all methods */\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return '';\n },\n divideAndConquer: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n with(Math) { return arguments.callee(floor(n/2), s)+arguments.callee(ceil(n/2), s); }\n },\n linearRecurse: function (n,s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return s+arguments.callee(--n, s);\n },\n newArray: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n return (new Array(isNaN(n) ? 1 : ++n)).join(s);\n },\n fillAndJoin: function (n, s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n var ret = [];\n for (var i=0; i<n; i++)\n ret.push(s);\n return ret.join('');\n },\n concat: function (n,s) {\n if (n==0) return '';\n if (n==1 || isNaN(n)) return s;\n var ret = '';\n for (var i=0; i<n; i++)\n ret+=s;\n return ret;\n },\n artistoex: function (n,s) {\n var result = '';\n while (n>0) {\n if (n&1) result+=s;\n n>>=1, s+=s;\n };\n return result;\n }\n};\nfunction testNum(len, dev) {\n with(Math) { return round(len+1+dev*(random()-0.5)); }\n}\nfunction testString(len, dev) {\n return (new Array(testNum(len, dev))).join(' ');\n}\nvar testTime = 1000,\n tests = {\n biggie: { str: { len: 25, dev: 12 }, rep: {len: 200, dev: 50 } },\n smalls: { str: { len: 5, dev: 5}, rep: { len: 5, dev: 5 } }\n };\nvar testCount = 0;\nvar winnar = null;\nvar inflight = 0;\nfor (var methodName in repeatMethods) {\n var method = repeatMethods[methodName];\n for (var testName in tests) {\n testCount++;\n var test = tests[testName];\n var testId = methodName+':'+testName;\n var result = {\n id: testId,\n testParams: test\n }\n result.count=0;\n\n (function (result) {\n inflight++;\n setTimeout(function () {\n result.start = +new Date();\n while ((new Date() - result.start) < testTime) {\n method(testNum(test.rep.len, test.rep.dev), testString(test.str.len, test.str.dev));\n result.count++;\n }\n result.end = +new Date();\n result.rate = 1000*result.count/(result.end-result.start)\n console.log(result);\n if (winnar === null || winnar.rate < result.rate) winnar = result;\n inflight--;\n if (inflight==0) {\n console.log('The winner: ');\n console.log(winnar);\n }\n }, (100+testTime)*testCount);\n }(result));\n }\n}\n"
},
{
"answer_id": 9655348,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "String.prototype.repeat = function (num) {\n var a = [];\n a.length = num << 0 + 1;\n return a.join(this);\n};\n"
},
{
"answer_id": 14026829,
"author": "Dennis",
"author_id": 1913959,
"author_profile": "https://Stackoverflow.com/users/1913959",
"pm_score": 3,
"selected": false,
"text": "count > 1 result += pattnern pattern += pattern String.prototype.repeat = function(count) {\n if (count < 1) return '';\n var result = '', pattern = this.valueOf();\n while (count > 1) {\n if (count & 1) result += pattern;\n count >>= 1, pattern += pattern;\n }\n result += pattern;\n return result;\n};\n"
},
{
"answer_id": 14580575,
"author": "Semra",
"author_id": 1262441,
"author_profile": "https://Stackoverflow.com/users/1262441",
"pm_score": 2,
"selected": false,
"text": "for (var i = 0, result = ''; i < N; i++) result += S;\n"
},
{
"answer_id": 15423652,
"author": "Andrew Hallendorff",
"author_id": 2171624,
"author_profile": "https://Stackoverflow.com/users/2171624",
"pm_score": 1,
"selected": false,
"text": "// repeated string\nvar string = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';\n// count paremeter is changed on every test iteration, limit it's maximum value here\nvar maxCount = 200;\n\nvar n = 0;\n$.each(tests, function (name) {\n var fn = tests[name];\n JSLitmus.test(++n + '. ' + name, function (count) {\n var index = 0;\n while (count--) {\n fn.call(string.slice(0, index % string.length), index % maxCount);\n index++;\n }\n });\n if (fn.call('>', 10).length !== 10) $('body').prepend('<h1>Error in \"' + name + '\"</h1>');\n});\n\nJSLitmus.runAll();\n // final: growing pattern + prototypejs check (count < 1)\n'final avoid': function (count) {\n if (!count) return '';\n if (count == 1) return this.valueOf();\n var pattern = this.valueOf();\n if (count == 2) return pattern + pattern;\n if (count == 3) return pattern + pattern + pattern;\n var result;\n if (count & 1) result = pattern;\n else result = '';\n count >>= 1;\n do {\n pattern += pattern;\n if (count & 1) result += pattern;\n count >>= 1;\n } while (count > 1);\n return result + pattern + pattern;\n}\n"
},
{
"answer_id": 16800987,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 1,
"selected": false,
"text": "String.prototype.repeat = function(num) {\n num = parseInt(num);\n if (num < 0) return '';\n return new Array(num + 1).join(this);\n}\n"
},
{
"answer_id": 17800645,
"author": "Joseph Myers",
"author_id": 2188862,
"author_profile": "https://Stackoverflow.com/users/2188862",
"pm_score": 6,
"selected": false,
"text": "n /*\n * Usage: stringFill3(\"abc\", 2) == \"abcabc\"\n */\n\nfunction stringFill3(x, n) {\n var s = '';\n for (;;) {\n if (n & 1) s += x;\n n >>= 1;\n if (n) x += x;\n else break;\n }\n return s;\n}\n stringFill1() function stringFill1(x, n) { \n var s = ''; \n while (s.length < n) s += x; \n return s; \n} \n/* Example of output: stringFill1('x', 3) == 'xxx' */ \n s.length x stringFill1() x string.length stringFill2() function stringFill2(x, n) { \n var s = ''; \n while (n-- > 0) s += x; \n return s; \n} \n stringFill1() stringFill2() function testFill(functionToBeTested, outputSize) { \n var i = 0, t0 = new Date(); \n do { \n functionToBeTested('x', outputSize); \n t = new Date() - t0; \n i++; \n } while (t < 2000); \n return t/i/1000; \n} \nseconds1 = testFill(stringFill1, 100); \nseconds2 = testFill(stringFill2, 100); \n stringFill2() stringFill1() stringFill2() stringFill2() stringFill2() N C(N) = 1 + 2 + 3 + ... + N = N(N+1)/2 = O(N^2) O(N^2) html = 'abcd\\n' + 'efgh\\n' + ... + 'xyz.\\n' O(N^2) N = 9 x = 'x'; \ns = ''; \ns += x; /* Now s = 'x' */ \nx += x; /* Now x = 'xx' */ \nx += x; /* Now x = 'xxxx' */ \nx += x; /* Now x = 'xxxxxxxx' */ \ns += x; /* Now s = 'xxxxxxxxx' as desired */\n C(9) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 9 = 45 C(9) = 1 + 2 + 4 + 8 + 9 = 24 N(N+1)/2 O(N) >>= 1 n = 10011 n >>= 1 n = 1001 & n & 1 n n stringFill3() function stringFill3(x, n) { \n var s = ''; \n for (;;) { \n if (n & 1) s += x; \n n >>= 1; \n if (n) x += x; \n else break; \n } \n return s; \n} \n O(N^2) O(N) stringFill1() stringFill2() stringFill3() stringFill3() stringFill1() stringFill2() a_1 / (1-r) = 2N n (n + 1) / 2 = 16 (17) / 2 = 8 (17) = 136 stringFill3() stringFill1() C1 N^2 C2 N C1 C1 = 0.0808 / (123457)2 = .00000000000530126997 C2 C2 = 0.001058 / 123457 = .00000000856978543136 for (;;)"
},
{
"answer_id": 25135949,
"author": "Robin Rizvi",
"author_id": 1145904,
"author_profile": "https://Stackoverflow.com/users/1145904",
"pm_score": 2,
"selected": false,
"text": "function repeat(s, n){\n return ((new Array(n+1)).join(s));\n}\nalert(repeat('R', 10));\n"
},
{
"answer_id": 25586878,
"author": "Nelo Mitranim",
"author_id": 1882154,
"author_profile": "https://Stackoverflow.com/users/1882154",
"pm_score": 1,
"selected": false,
"text": "function repeat (string, times) {\n var result = ''\n while (times-- > 0) result += string\n return result\n}\n function repeat (string, times) {\n var result = ''\n while (times > 0) {\n if (times & 1) result += string\n times >>= 1\n string += string\n }\n return result\n}\n"
},
{
"answer_id": 26414234,
"author": "Fred Gandt",
"author_id": 1832568,
"author_profile": "https://Stackoverflow.com/users/1832568",
"pm_score": 2,
"selected": false,
"text": "function ditto( s, r, c ) {\n return c-- ? ditto( s, r += s, c ) : r;\n}\n\nditto( \"foo\", \"\", 128 );\n String.prototype.ditto = function( c ) {\n return --c ? this + this.ditto( c ) : this;\n};\n\n\"foo\".ditto( 128 );\n String.prototype.ditto = function() {\n var c = Number( arguments[ 0 ] ) || 2,\n r = this.valueOf();\n while ( --c ) {\n r += this;\n }\n return r;\n}\n\n\"foo\".ditto();\n"
},
{
"answer_id": 27325273,
"author": "André Laszlo",
"author_id": 98057,
"author_profile": "https://Stackoverflow.com/users/98057",
"pm_score": 7,
"selected": true,
"text": "String.prototype.repeat \"yo\".repeat(2);\n// returns: \"yoyo\"\n"
},
{
"answer_id": 27548734,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 2,
"selected": false,
"text": "String.repeat String.prototype.repeat = String.prototype.repeat || function(n){\n return n<=1 ? this : this.concat(this.repeat(n-1));\n}\n Array.join repeat(1000)"
},
{
"answer_id": 29483806,
"author": "Lewis",
"author_id": 3247703,
"author_profile": "https://Stackoverflow.com/users/3247703",
"pm_score": 4,
"selected": false,
"text": "'abc'.repeat(3); //abcabcabc\n"
},
{
"answer_id": 32133812,
"author": "Kalpesh Patel",
"author_id": 1044026,
"author_profile": "https://Stackoverflow.com/users/1044026",
"pm_score": 3,
"selected": false,
"text": "Array(N+1).join(\"string_to_repeat\")"
},
{
"answer_id": 33530860,
"author": "l3x",
"author_id": 1978383,
"author_profile": "https://Stackoverflow.com/users/1978383",
"pm_score": 2,
"selected": false,
"text": "> _.repeat('yo', 2)\n\"yoyo\"\n"
},
{
"answer_id": 35634264,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 2,
"selected": false,
"text": "function repeat(s, n) { return new Array(n+1).join(s); }\n function repeat(s, n) { var a=[],i=0;for(;i<n;)a[i++]=s;return a.join(''); }\n function repeat(s,n) { return s.repeat(n) };\n"
},
{
"answer_id": 36173160,
"author": "nikolay",
"author_id": 626067,
"author_profile": "https://Stackoverflow.com/users/626067",
"pm_score": 2,
"selected": false,
"text": "function repeat(pattern, count) {\n for (var result = '';;) {\n if (count & 1) {\n result += pattern;\n }\n if (count >>= 1) {\n pattern += pattern;\n } else {\n return result;\n }\n }\n}\n Array.join"
},
{
"answer_id": 36678697,
"author": "karlzafiris",
"author_id": 4141689,
"author_profile": "https://Stackoverflow.com/users/4141689",
"pm_score": 1,
"selected": false,
"text": "function concatStr(str, num) {\n var arr = [];\n\n //Construct an array\n for (var i = 0; i < num; i++)\n arr[i] = str;\n\n //Join all elements\n str = arr.join('');\n\n return str;\n}\n\nconsole.log(concatStr(\"abc\", 3));\n"
},
{
"answer_id": 41574167,
"author": "xgqfrms",
"author_id": 5934465,
"author_profile": "https://Stackoverflow.com/users/5934465",
"pm_score": 2,
"selected": false,
"text": "ES-Next ES2015 ES6 repeat() /** \n * str: String\n * count: Number\n */\nconst str = `hello repeat!\\n`, count = 3;\n\nlet resultString = str.repeat(count);\n\nconsole.log(`resultString = \\n${resultString}`);\n/*\nresultString = \nhello repeat!\nhello repeat!\nhello repeat!\n*/\n\n({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);\n// 'abcabc' (repeat() is a generic method)\n\n// Examples\n\n'abc'.repeat(0); // ''\n'abc'.repeat(1); // 'abc'\n'abc'.repeat(2); // 'abcabc'\n'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer)\n// 'abc'.repeat(1/0); // RangeError\n// 'abc'.repeat(-1); // RangeError ES2017 ES8 String.prototype.padStart() const str = 'abc ';\nconst times = 3;\n\nconst newStr = str.padStart(str.length * times, str.toUpperCase());\n\nconsole.log(`newStr =`, newStr);\n// \"newStr =\" \"ABC ABC abc \" ES2017 ES8 String.prototype.padEnd() const str = 'abc ';\nconst times = 3;\n\nconst newStr = str.padEnd(str.length * times, str.toUpperCase());\n\nconsole.log(`newStr =`, newStr);\n// \"newStr =\" \"abc ABC ABC \""
},
{
"answer_id": 41905186,
"author": "oboshto",
"author_id": 2160038,
"author_profile": "https://Stackoverflow.com/users/2160038",
"pm_score": 2,
"selected": false,
"text": "function repeat(s, n) {\n var str = '';\n for (var i = 0; i < n; i++) {\n str += s;\n }\n return str;\n}\n"
},
{
"answer_id": 55944841,
"author": "wizzfizz94",
"author_id": 7144427,
"author_profile": "https://Stackoverflow.com/users/7144427",
"pm_score": 1,
"selected": false,
"text": "padStart padEnd var str = 'cat';\nvar num = 23;\nvar size = str.length * num;\n\"\".padStart(size, str) // outputs: 'catcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcatcat'\n"
},
{
"answer_id": 63642522,
"author": "saigowthamr",
"author_id": 9278645,
"author_profile": "https://Stackoverflow.com/users/9278645",
"pm_score": 1,
"selected": false,
"text": "repeat() const name = \"king\";\n\nconst repeat = name.repeat(4);\n\nconsole.log(repeat);\n \"kingkingkingking\"\n repeat() function repeat(str, n) {\n if (!str || !n) {\n return;\n }\n\n let final = \"\";\n while (n) {\n final += s;\n n--;\n }\n return final;\n}\n\nconsole.log(repeat(\"king\", 3))\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208/"
] |
202,609
|
<p>This is what I currently have:</p>
<pre><code>CREATE OR REPLACE TRIGGER MYTRIGGER
AFTER INSERT ON SOMETABLE
FOR EACH ROW
DECLARE
v_emplid varchar2(10);
BEGIN
SELECT
personnum into v_emplid
FROM PERSON
WHERE PERSONID = :new.EMPLOYEEID;
dbms_output.put(v_emplid);
/* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values from the trigger table*/
END MYTRIGGER;
</code></pre>
<p>DBA_ERRORS has this error:
PL/SQL: ORA-00923: FROM keyword not found where expected</p>
|
[
{
"answer_id": 202634,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 4,
"selected": true,
"text": "SQL> create table someTable( employeeid number );\n\nTable created.\n\nSQL> create table person( personid number, personnum varchar2(10) );\n\nTable created.\n\nSQL> ed\nWrote file afiedt.buf\n\n 1 CREATE OR REPLACE TRIGGER MYTRIGGER\n 2 AFTER INSERT ON SOMETABLE\n 3 FOR EACH ROW\n 4 DECLARE\n 5 v_emplid varchar2(10);\n 6 BEGIN\n 7 SELECT personnum\n 8 into v_emplid\n 9 FROM PERSON\n 10 WHERE PERSONID = :new.EMPLOYEEID;\n 11 dbms_output.put(v_emplid);\n 12 /* INSERT INTO SOMEOTHERTABLE USING v_emplid and some of the other values\n from the trigger table*/\n 13* END MYTRIGGER;\n 14 /\n\nTrigger created.\n\nSQL> insert into person values( 1, '123' );\n\n1 row created.\n\nSQL> insert into sometable values( 1 );\n\n1 row created.\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20836/"
] |
202,610
|
<p>I have two scripts that often need to be run with the same parameter:</p>
<pre><code>$ populate.ksh 9241 && check.ksh 9241
</code></pre>
<p>When I need to change the parameter (<strong>9241</strong> in this example), I can go back and edit the line in history. But since I need to change the number in two places, I sometimes make a typo. I'd like to be able to change the parameter just once to change it in both places.</p>
|
[
{
"answer_id": 202611,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "r=$1\npopulate.ksh $r && check.ksh $r\n for r; do\n populate.ksh $r && check.ksh $r\ndone\n $ r=9241; populate.ksh $r && check.ksh $r\n $ for r in 9241 9242; do populate.ksh $r && check.ksh $r; done\n"
},
{
"answer_id": 202637,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 3,
"selected": false,
"text": "!pop:gs/9241/1234\n $ populate.ksh 9241 && check.ksh 9241\n...\n$ !pop:gs/9241/1234\npopulate.ksh 1234 && check.ksh 1234\n...\n"
},
{
"answer_id": 202638,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "!!:gs/9241/9243/\n gs/// s///g pop populate.sh"
},
{
"answer_id": 205286,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "HISTCONTROL histchars man bash"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] |
202,630
|
<p>How do I determine if an object reference is null in C# w/o throwing an exception if it is null?</p>
<p>i.e. If I have a class reference being passed in and I don't know if it is null or not.</p>
|
[
{
"answer_id": 202642,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "(YourObject != Null)\n"
},
{
"answer_id": 202646,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 4,
"selected": false,
"text": "void DoSomething( MyClass value )\n{\n if( value != null )\n {\n value.Method();\n }\n}\n"
},
{
"answer_id": 202664,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "void DoSomething( MyClass value )\n{\n if ( value == null ) return;\n // I might throw an ArgumentNullException here, instead\n\n value.Method();\n}\n"
},
{
"answer_id": 202665,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 2,
"selected": false,
"text": "if(p != null)\n{\n DoWork(p);\n}\n IExample e = p as IExample;\nif(e != null)\n DoWork(e);\n"
},
{
"answer_id": 202679,
"author": "Fred",
"author_id": 177,
"author_profile": "https://Stackoverflow.com/users/177",
"pm_score": 0,
"selected": false,
"text": "private SortedList myList;\n if ( myList == null)\n myList = new SortedList();\n"
},
{
"answer_id": 202747,
"author": "Jason V",
"author_id": 27912,
"author_profile": "https://Stackoverflow.com/users/27912",
"pm_score": 1,
"selected": false,
"text": "if (null == obj) {\n obj = new Obj();\n}\n if (obj == null) {\n obj = new Obj();\n}\n if (obj = null) {\n obj = new Obj();\n}\n if (null = obj) {\n obj = new Obj();\n}\n"
},
{
"answer_id": 202760,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": false,
"text": "public void DoSomething(Object myParam)\n{\n if (myParam == null) throw new ArgumentNullException(\"myParam\");\n\n // Carry on\n}\n"
},
{
"answer_id": 35134460,
"author": "James Harcourt",
"author_id": 1461680,
"author_profile": "https://Stackoverflow.com/users/1461680",
"pm_score": 2,
"selected": false,
"text": "value?.Method();\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177/"
] |
202,631
|
<p>I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.</p>
<p>Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.</p>
<p>I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?</p>
|
[
{
"answer_id": 392472,
"author": "Alex",
"author_id": 42707,
"author_profile": "https://Stackoverflow.com/users/42707",
"pm_score": 3,
"selected": false,
"text": "ShoppingController.ListPaymentMethods()\n new ShoppingController().ListPaymentMethods()\n"
},
{
"answer_id": 26827569,
"author": "Black Dog",
"author_id": 4232349,
"author_profile": "https://Stackoverflow.com/users/4232349",
"pm_score": 3,
"selected": false,
"text": "ShapeUtils.DrawCircle(stroke, pen, origin, radius);\n\nShapeUtils.DrawSquare(stroke, pen, x, y, width, length);\n ShapeUtils utils = new ShapeUtils(stroke,pen);\n\nutil.DrawCircle(origin,radius);\n\nutil.DrawSquare(x,y,width,length);\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] |
202,644
|
<p>e.g, Is the user playing a movie full screen, or looking at powerpoint in full screen mode?</p>
<p>I could have sworn I saw a IsFullScreenInteractive API before, but can't find it now</p>
|
[
{
"answer_id": 495389,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(IsForegroundWwindowFullScreen());\n }\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern int GetSystemMetrics(int smIndex);\n\n public const int SM_CXSCREEN = 0;\n public const int SM_CYSCREEN = 1;\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool GetWindowRect(IntPtr hWnd, out W32RECT lpRect);\n\n [StructLayout(LayoutKind.Sequential)]\n public struct W32RECT\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n }\n\n public static bool IsForegroundWwindowFullScreen()\n {\n int scrX = GetSystemMetrics(SM_CXSCREEN),\n scrY = GetSystemMetrics(SM_CYSCREEN);\n\n IntPtr handle = GetForegroundWindow();\n if (handle == IntPtr.Zero) return false;\n\n W32RECT wRect;\n if (!GetWindowRect(handle, out wRect)) return false;\n\n return scrX == (wRect.Right - wRect.Left) && scrY == (wRect.Bottom - wRect.Top);\n }\n }\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,662
|
<p>I have a VB6 dll that is trying to create a COM object using the following line of code:</p>
<pre><code>Set CreateObj = CreateObject("OPSValuer.OPSValue")
</code></pre>
<p>However this fails with the error "Object variable or With block variable not set".</p>
<p>I can see OPSValuer.OPSValue in dcomcnfg and it appears to be registered fine. Does anyone have any ideas about what may be causing the problem?</p>
|
[
{
"answer_id": 213491,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "OPSValuer.OPSValue Class_Initialize"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
202,663
|
<p>I am testing an application that checks if a file exists across a network. In my testing, I am purposefully pulling the network plug so the file will not be found. The problem is this causes my app to go unresponsive for at least 15 seconds. I have used both the FileExists() and GetAttr() functions in VB6. Does anyone know how to fix this problem? (No, I can't stop using VB6)</p>
<p>Thanks,
Charlie</p>
|
[
{
"answer_id": 202852,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": -1,
"selected": false,
"text": "Dim objFSO As New FileSystemObject \nIf objFSO.FileExists(\"C:\\path\\to\\your_file.txt\") Then\n ' Do some stuff with the file\nElse\n ' File isn't here...be nice to the user.\nEndIf\n"
},
{
"answer_id": 207112,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 3,
"selected": false,
"text": "Private Declare Function WNetGetConnection Lib \"mpr.dll\" Alias _\n \"WNetGetConnectionA\" (ByVal lpszLocalName As String, _\n ByVal lpszRemoteName As String, ByRef cbRemoteName As Long) As Long\n\nPrivate Declare Function PathIsNetworkPath Lib \"shlwapi.dll\" Alias _\n \"PathIsNetworkPathA\" (ByVal pszPath As String) As Long\n\nPrivate Declare Function PathIsUNC Lib \"shlwapi.dll\" Alias \"PathIsUNCA\" _\n (ByVal pszPath As String) As Long\n Private Declare Function InternetGetConnectedState Lib \"wininet.dll\" _\n (ByRef lpdwFlags As Long, ByVal dwReserved As Long) As Long\n\nConst INTERNET_CONNECTION_MODEM = 1\nConst INTERNET_CONNECTION_LAN = 2\nConst INTERNET_CONNECTION_PROXY = 4\nConst INTERNET_CONNECTION_MODEM_BUSY = 8\n"
},
{
"answer_id": 5019777,
"author": "Kuuri",
"author_id": 620094,
"author_profile": "https://Stackoverflow.com/users/620094",
"pm_score": 1,
"selected": false,
"text": "Dim FlSize as long \nflsize=filelen(\"yourfilepath\")\nif err.number=53 then msgbox(\"file not found\")\nif err.number=78 then msgbox(\"Path Does no Exist\")\n"
},
{
"answer_id": 19256033,
"author": "barnameha",
"author_id": 2680724,
"author_profile": "https://Stackoverflow.com/users/2680724",
"pm_score": 0,
"selected": false,
"text": "Private Declare Function InternetGetConnectedState Lib \"wininet.dll\" (ByRef dwFlags As Long, ByVal dwReserved As Long) As Long\n\nPrivate Const CONNECT_LAN As Long = &H2\n Private Const CONNECT_MODEM As Long = &H1\n Private Const CONNECT_PROXY As Long = &H4\n Private Const CONNECT_OFFLINE As Long = &H20\n Private Const CONNECT_CONFIGURED As Long = &H40\n\n\n\n Public Function checknet() As Boolean\nDim Msg As String\n\n If IsWebConnected(Msg) Then\nchecknet = True\n Else\n If (Msg = \"LAN\") Or (Msg = \"Offline\") Or (Msg = \"Configured\") Or (Msg = \"Proxy\") Then\n\n checknet = False\n End If\n End If\n\n End Function\n\n\n\nPrivate Function IsWebConnected(Optional ByRef ConnType As String) As Boolean\n Dim dwFlags As Long\n Dim WebTest As Boolean\n ConnType = \"\"\n WebTest = InternetGetConnectedState(dwFlags, 0&)\n Select Case WebTest\n Case dwFlags And CONNECT_LAN: ConnType = \"LAN\"\n Case dwFlags And CONNECT_MODEM: ConnType = \"Modem\"\n Case dwFlags And CONNECT_PROXY: ConnType = \"Proxy\"\n Case dwFlags And CONNECT_OFFLINE: ConnType = \"Offline\"\n Case dwFlags And CONNECT_CONFIGURED: ConnType = \"Configured\"\n Case dwFlags And CONNECT_RAS: ConnType = \"Remote\"\n End Select\n IsWebConnected = WebTest\n End Function\n If checknet = False Then\n\n...\n\nelse\n\n...\n\nend if\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27689/"
] |
202,685
|
<p>I truly love VIM - it's one of only a handful of applications I've every come across that make you feel warm and fuzzy inside. However, for PHP development, I still use PDT Eclipse although I would love to switch. </p>
<p>The reason I can't quite at the moment is the CTRL+SPACE code-assist functionality that I rely on so much - it's so useful, especially when type hinting, or using PHPDoc variable comment blocks. </p>
<p>I know there are cool plugins for VIM out there that can probably replicate this functionality and then some - but what are they? </p>
|
[
{
"answer_id": 202726,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": true,
"text": "filetype plugin on\nau FileType php set omnifunc=phpcomplete#CompletePHP\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25517/"
] |
202,699
|
<p>What is the best way to create a clone of a DTO? There is not an ICloneable interface or a BinaryFormatter class in Silverlight. Is reflection the only way?</p>
|
[
{
"answer_id": 2195954,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 4,
"selected": true,
"text": "Public Shared Function Clone(Of T)(ByVal source As T) As T\n Dim serializer As New DataContractSerializer(GetType(T))\n Using ms As New MemoryStream\n serializer.WriteObject(ms, source)\n ms.Seek(0, SeekOrigin.Begin)\n Return DirectCast(serializer.ReadObject(ms), T)\n End Using\nEnd Function\n"
},
{
"answer_id": 7751623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " IEnumerable<LayerDto> layers;\n\n DataContractSerializer serializer = new DataContractSerializer(typeof(IEnumerable<LayerDto>));\n using (MemoryStream ms = new MemoryStream())\n {\n serializer.WriteObject(ms, source);\n ms.Seek(0, SeekOrigin.Begin);\n //return (IEnumerable<LayerDto>)serializer.ReadObject(ms);\n layers = (IEnumerable<LayerDto>)serializer.ReadObject(ms);\n return layers;\n }\n"
},
{
"answer_id": 7751814,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public LayerDto Clone(LayerDto source)\n {\n\n DataContractSerializer serializer = new DataContractSerializer(typeof(LayerDto));\n using (MemoryStream ms = new MemoryStream())\n {\n serializer.WriteObject(ms, source);\n ms.Seek(0, SeekOrigin.Begin);\n return (LayerDto)serializer.ReadObject(ms);\n }\n }\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4231/"
] |
202,702
|
<p>I'm not sure why the TSpeedButton has this property but when a TSpeedButton is the only button of a given groupindex, it doesn't stay pressed, whether or not "AllowAllUp" is pressed. Maybe a Jedi control would suffice, but hopefully there's some fix. Any help or anecdotes are appreciated.</p>
<p>BTW, I'm (still) using Delphi 7, not sure if this is an across the board conundrum.</p>
|
[
{
"answer_id": 202722,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 1,
"selected": false,
"text": "Down Down Checked Down Checked"
},
{
"answer_id": 202980,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "object SpeedButton1: TSpeedButton\n Left = 152\n Top = 384\n Width = 23\n Height = 22\n AllowAllUp = True\n GroupIndex = 99\nend\n"
},
{
"answer_id": 205248,
"author": "Uwe Raabe",
"author_id": 26833,
"author_profile": "https://Stackoverflow.com/users/26833",
"pm_score": 4,
"selected": false,
"text": "TSpeedButton AllowAllUp := true; GroupIndex := 1;"
},
{
"answer_id": 247501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "AllowAllUp := True; \nGroupIndex := 1;\n OnClick procedure TForm1.SpeedButton1Click(Sender: TObject);\nbegin\n if( SpeedButton1.AllowAllUp ) then \n begin \n SpeedButton1.AllowAllUp := False; \n SpeedButton1.Down := True; \n end else \n begin \n SpeedButton1.AllowAllUp := True; \n SpeedButton1.Down := False; \n end; \nend;\n"
},
{
"answer_id": 15212862,
"author": "MacGyver",
"author_id": 2133703,
"author_profile": "https://Stackoverflow.com/users/2133703",
"pm_score": 1,
"selected": false,
"text": "OnClick ....\nbtn.AllowAllUp := not btn.AllowAllUp;\nbtn.Down := not btn.Down;\n....\n"
},
{
"answer_id": 22293246,
"author": "Mark Patterson",
"author_id": 1087046,
"author_profile": "https://Stackoverflow.com/users/1087046",
"pm_score": 1,
"selected": false,
"text": "procedure TForm1.SpeedButton1Click(Sender: TObject);\nbegin\n MyBoolProperty := not MyBoolProperty;\n SpeedButton1.Down := MyBoolProperty;\nend;\n"
},
{
"answer_id": 29434550,
"author": "Steve Graham",
"author_id": 2219556,
"author_profile": "https://Stackoverflow.com/users/2219556",
"pm_score": 0,
"selected": false,
"text": " with Speedbutton1 do\n begin\n if tag = 1 then tag := 0 else tag := 1;\n down := (tag = 1);\n end;\n"
},
{
"answer_id": 46848605,
"author": "Jacek Krawczyk",
"author_id": 1960514,
"author_profile": "https://Stackoverflow.com/users/1960514",
"pm_score": 0,
"selected": false,
"text": "GroupIndex 0 AllowAllUp"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
202,718
|
<p>Is there a good method for writing C / C++ function headers with default parameters that are function calls? </p>
<p>I have some header with the function:</p>
<pre><code>int foo(int x, int y = 0);
</code></pre>
<p>I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do:</p>
<pre><code>int foo(int x, int y = bar());
</code></pre>
<p>Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like:</p>
<pre><code>int foo(int x, int y = baz.bar());
</code></pre>
<p>Where baz is a function belonging to an object that has not been instantiated within the header file.</p>
|
[
{
"answer_id": 202758,
"author": "Tim Sharrock",
"author_id": 12840,
"author_profile": "https://Stackoverflow.com/users/12840",
"pm_score": 3,
"selected": false,
"text": "int foo(int x, int y); int foo(int x){return foo(x,bar);}"
},
{
"answer_id": 202759,
"author": "user21714",
"author_id": 21714,
"author_profile": "https://Stackoverflow.com/users/21714",
"pm_score": 3,
"selected": false,
"text": "int foo(int x)\n{\n Bar bar = //whatever initialization\n return foo(x,bar.baz());\n}\n\nint foo(int x,int y)\n{\n //whatever the implementation is right now\n}\n"
},
{
"answer_id": 203249,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 2,
"selected": false,
"text": "void An_object::An_object(\n const Foo &a,\n const Bar &b,\n const Strategem &s = Default_strategem()\n);\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3022/"
] |
202,723
|
<p>This is something I've always wondered, and I can't find any mention of it anywhere online. When a shop from, say Japan, writes code, would I be able to read it in English? Or do languages, like C, PHP, anything, have Japanese translations that they write?</p>
<p>I guess what I'm asking is does every single coder in the world know enough English to use the exact same reserved words I do?</p>
<p>Would this code:</p>
<pre><code>If (i < size){
switch
case 1:
print "hi there"
default:
print "no, thank you"
} else {
print "yes, thank you"
}
</code></pre>
<p>display the exact same as I'm seeing it right now in English, or would some other non-English-speaking person see the words "if", "switch", "case", "default", "print", and "else" in their native language?</p>
<p>EDIT - yes, this is serious. I didn't know if different localizations of a language have different keywords. or if there are even different localizations at all.</p>
|
[
{
"answer_id": 202841,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 5,
"selected": false,
"text": "interface Foo {\n\n Color getCouleur();\n\n void setCouleur(Color couleur);\n}\n"
},
{
"answer_id": 202851,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 8,
"selected": true,
"text": " for( i = 0 ; i < 100 ; i++ ) {}\n"
},
{
"answer_id": 288320,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 2,
"selected": false,
"text": "int foo)int i, char c( }\n int six = 2 / 3:\n int two = six + 4:\n if )i > 0( }\n printf)\"i is negative\"(:\n {\n{\n"
},
{
"answer_id": 290462,
"author": "Lara Dougan",
"author_id": 4081,
"author_profile": "https://Stackoverflow.com/users/4081",
"pm_score": 5,
"selected": false,
"text": "// In Japanese, it makes more sense to put the keywords/modifiers as\n// postfix expressions rather than prefix expressions.\n(i < size)か {\n (l[i])は {\n 1だ:\n 「もしもし。」を書く;\n 省略時値:\n 「いいえ、いいですよ。」を書く;\n }\n} ない {\n 「はい、ありがとうございます。」を書く;\n}\n"
},
{
"answer_id": 1284297,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 2,
"selected": false,
"text": "SOMMA(A1:A10) se (i < size){\n commuta\n caso 1:\n stampa \"hi there\"\n normalmente:\n stampa \"no, thank you\"\n} altrimenti {\n stampa \"yes, thank you\"\n}\n"
},
{
"answer_id": 1284299,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "Si (i < taille) {\n cas par cas :\n cas 1:\n afficher \"salut\"\n défaut:\n afficher \"non merci\"\n} sinon {\n afficher \"oui, merci\"\n}\n"
},
{
"answer_id": 1284323,
"author": "Stefano Borini",
"author_id": 78374,
"author_profile": "https://Stackoverflow.com/users/78374",
"pm_score": 1,
"selected": false,
"text": "se (i < dimensione){\n scegli\n caso 1:\n stampa \"ciao\"\n mancante:\n stampa \"no, grazie\"\n} altrimenti {\n stampa \"sì, grazie\"\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] |
202,740
|
<p>Can I set timeouts for JSP pages in tomcat either on a per page or server level?</p>
|
[
{
"answer_id": 202795,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 3,
"selected": true,
"text": "catalina.bat catalina.sh jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 \n"
},
{
"answer_id": 230399,
"author": "Mojo",
"author_id": 30462,
"author_profile": "https://Stackoverflow.com/users/30462",
"pm_score": 3,
"selected": false,
"text": "connectionTimeout <Connector\n URIEncoding=\"UTF-8\"\n acceptCount=\"100\"\n connectionTimeout=\"20000\"\n disableUploadTimeout=\"true\"\n enableLookups=\"false\"\n maxHttpHeaderSize=\"8192\"\n maxSpareThreads=\"75\"\n maxThreads=\"150\"\n minSpareThreads=\"25\"\n port=\"7777\"\n redirectPort=\"8443\" />\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14481/"
] |
202,750
|
<p>I mean, is there a coded language with human style coding?
For example:</p>
<pre><code>Create an object called MyVar and initialize it to 10;
Take MyVar and call MyMethod() with parameters. . .
</code></pre>
<p>I know it's not so useful, but it can be interesting to create such a grammar.</p>
|
[
{
"answer_id": 202763,
"author": "Robert P",
"author_id": 18097,
"author_profile": "https://Stackoverflow.com/users/18097",
"pm_score": 3,
"selected": false,
"text": "print \"hello!\" and open my $File, '<', $path or die \"Couldn't open the file after saying hello!\";\n"
},
{
"answer_id": 202766,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 5,
"selected": false,
"text": "tell application \"iTunes\"\n activate\n play playlist \"Party Shuffle\"\nend tell\n"
},
{
"answer_id": 202771,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 8,
"selected": true,
"text": "SET MYVAR TO 10.\nEXECUTE MYMETHOD with 10, MYVAR.\n ADD YEARS TO AGE.\nMULTIPLY PRICE BY QUANTITY GIVING COST.\nSUBTRACT DISCOUNT FROM COST GIVING FINAL-COST.\n SET VAR_00_MYVAR_PIC99 TO 10.\nEXECUTE PROC_10_MYMETHOD with 10, VAR_00_MYVAR_PIC99.\n"
},
{
"answer_id": 202772,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 3,
"selected": false,
"text": "tell application \"Finder\"\n set the percent_free to ¬\n (((the free space of the startup disk) / (the capacity of the startup disk)) * 100) div 1\nend tell\nif the percent_free is less than 10 then\n tell application (path to frontmost application as text)\n display dialog \"The startup disk has only \" & the percent_free & ¬\n \" percent of its capacity available.\" & return & return & ¬\n \"Should this script continue?\" with icon 1\n end tell\nend if\n"
},
{
"answer_id": 202800,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 7,
"selected": false,
"text": "HAI\nCAN HAS STDIO?\nVISIBLE \"HAI WORLD!\"\nKTHXBYE\n"
},
{
"answer_id": 202844,
"author": "b3.",
"author_id": 14946,
"author_profile": "https://Stackoverflow.com/users/14946",
"pm_score": 4,
"selected": false,
"text": "bob is a parent of tim.\nmary is a parent of bob.\n\n?- X is a grandparent of tim.\nX = mary\n\n?- jim is a parent of bob.\nfalse\n"
},
{
"answer_id": 202950,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 7,
"selected": false,
"text": "\"Hello Deductible\" by \"I.F. Author\"\n\nThe story headline is \"An Interactive Example\".\n\nThe Living Room is a room. \"A comfortably furnished living room.\"\nThe Kitchen is north of the Living Room.\nThe Front Door is south of the Living Room.\nThe Front Door is a door. The Front Door is closed and locked.\n\nThe insurance salesman is a man in the Living Room. The description is \"An insurance salesman in a tacky polyester suit. He seems eager to speak to you.\" Understand \"man\" as the insurance salesman.\n\nA briefcase is carried by the insurance salesman. The description is \"A slightly worn, black briefcase.\" Understand \"case\" as the briefcase.\n\nThe insurance paperwork is in the briefcase. The description is \"Page after page of small legalese.\" Understand \"papers\" or \"documents\" or \"forms\" as the paperwork.\n\nInstead of listening to the insurance salesman: \n say \"The salesman bores you with a discussion of life insurance policies. From his briefcase he pulls some paperwork which he hands to you.\";\n move the insurance paperwork to the player.\n"
},
{
"answer_id": 202996,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 1,
"selected": false,
"text": " <doc keywords=\"x y z\"> doc -keywords=<<x y z>>\n <title/> title\n <body id=\"db13\"> body -id=db13\n This is text. <<This is text.>>\n </body>\n</doc>\n"
},
{
"answer_id": 203326,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 4,
"selected": false,
"text": "Ingredients.\n72 g haricot beans\n101 eggs\n108 g lard\n111 cups oil\n32 zucchinis\n119 ml water\n114 g red salmon\n100 g dijon mustard\n33 potatoes\n\nMethod.\nPut potatoes into the mixing bowl. Put dijon mustard into the mixing bowl. \nPut lard into the mixing bowl. Put red salmon into the mixing bowl. Put oil into the mixing bowl. \nPut water into the mixing bowl. Put zucchinis into the mixing bowl. Put oil into the mixing bowl. \nPut lard into the mixing bowl. Put lard into the mixing bowl. Put eggs into the mixing bowl. \nPut haricot beans into the mixing bowl. Liquefy contents of the mixing bowl. \nPour contents of the mixing bowl into the baking dish.\n"
},
{
"answer_id": 205063,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 2,
"selected": false,
"text": "-module(listsort).\n-export([by_length/1]).\n\n by_length(Lists) ->\n F = fun(A,B) when is_list(A), is_list(B) ->\n length(A) < length(B)\n end,\n qsort(Lists, F).\n\n qsort([], _)-> [];\n qsort([Pivot|Rest], Smaller) ->\n qsort([ X || X <- Rest, Smaller(X,Pivot)], Smaller)\n ++ [Pivot] ++\n qsort([ Y ||Y <- Rest, not(Smaller(Y, Pivot))], Smaller).\n"
},
{
"answer_id": 287891,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 2,
"selected": false,
"text": "test \"Searching google for watin\"\n goto \"http://www.google.se\"\n type \"watin\" into \"q\"\n click \"btnG\"\n assert that text \"WatiN Home\" exists\n assert that element \"res\" exists\nend\n"
},
{
"answer_id": 287978,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 2,
"selected": false,
"text": "if Time_To_Loop then\n for i in Some_Array loop\n Some_Array(i) := i;\n end loop;\nend if;\n if (timeToLoop != 0) {\n for (int i=0;i<SOME_ARRAY_LENGTH;i++) {\n someArray[i] = i;\n }\n}\n"
},
{
"answer_id": 665651,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 3,
"selected": false,
"text": "SELECT name, address FROM customers WHERE region = 'Europe'\n"
},
{
"answer_id": 694662,
"author": "Arjan",
"author_id": 84237,
"author_profile": "https://Stackoverflow.com/users/84237",
"pm_score": 0,
"selected": false,
"text": "If <condition> Then\n <something>\nEnd If\n Als <condition> Dan\n <something>\nEinde Als\n"
},
{
"answer_id": 694677,
"author": "ewakened",
"author_id": 38354,
"author_profile": "https://Stackoverflow.com/users/38354",
"pm_score": 0,
"selected": false,
"text": "\n\nventi = Starbucks.new(:kind => :coffee, :size => :venti)\nhalf_foam_venti = add_half_foam(venti)\nserve(half_foam_venti)\n\n"
},
{
"answer_id": 700993,
"author": "peSHIr",
"author_id": 50846,
"author_profile": "https://Stackoverflow.com/users/50846",
"pm_score": 1,
"selected": false,
"text": " HOW TO RETURN words document:\n PUT {} IN collection\n FOR line IN document:\n FOR word IN split line:\n IF word not.in collection:\n INSERT word IN collection\n RETURN collection\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68336/"
] |
202,777
|
<p>I'm creating a invoice crystal report for sage mas 500 AR module. In it, I'm attempting to add the <code>tarinvoice.balance</code> field with the following formula: </p>
<pre><code>if {tarPrintInvcHdrWrk.Posted} = 1 then
ToText({tarInvoice.Balance})
</code></pre>
<p>I'm assuming that when the <code>{tarPrintInvcHdrWrk.Posted} = 1</code> conditional statement holds FALSE, it doesn't attempt to pull the invoice field because when I remove the formula from the report, the form displays correctly without it. </p>
<p>When the conditional statement renders true in the report, the balance fields behaves correctly. However, with the formula renders FALSE in the CR form, the entire crystal report bombs and displays blank. Any ideas why or what I'm doing wrong?</p>
<hr>
<p>Just tried setting everything to zero and the report still bombs. I'm starting to think its more of a query error in the report. I wish there was a way to exclude the field in the query when posted = 0. </p>
<p>With <code>tarinvoice.balance</code> removed when the posted = 0, the report works fine.<br>
With <code>tarinvoice.balance</code> included and posted = 1, report works fine. </p>
<p>With <code>tarinvoice.balance</code> included and posted =0, report bombs.</p>
|
[
{
"answer_id": 205047,
"author": "user28014",
"author_id": 28014,
"author_profile": "https://Stackoverflow.com/users/28014",
"pm_score": 0,
"selected": false,
"text": "if isnull({tarPrintInvcHdrWrk.Posted}) = FALSE then \n if {tarPrintInvcHdrWrk.Posted} = 1 then \n if isnull({tarInvoice.Balance}) = FALSE then \n ToText({tarInvoice.Balance})\n else \n \"0.00\" \n else \n \"0.0\"\nelse \n\"0\"\n"
},
{
"answer_id": 211416,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 0,
"selected": false,
"text": "NumberVar InvoiceBalance; \nIf isnull({tarInvoice.Balance}) then\n InvoiceBalance := 0\nElse\n InvoiceBalance := {tarInvoice.Balance};\n\nIf {tarPrintInvcHdrWrk.Posted} = 1 then\n ToText(InvoiceBalance);\n\n"
},
{
"answer_id": 7685700,
"author": "vice",
"author_id": 933136,
"author_profile": "https://Stackoverflow.com/users/933136",
"pm_score": 0,
"selected": false,
"text": "if isnull({tarPrintInvcHdrWrk.Posted}) or {tarPrintInvcHdrWrk.Posted}=0 then\n\" \"\nelse\nif {tarPrintInvcHdrWrk.Posted} = 1 then \n ToText({tarInvoice.Balance})\nelse\n\" \"\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28014/"
] |
202,786
|
<p>I need to merge a forked project.
Unfortunately, the CVS $Id lines are different so the merge tools I tried report that all the files are different (and 95% of them have only this line different)</p>
<p>Is there a merge tool that can be configured to ignore line comparison results based on a pattern ?</p>
<p>[edit]
I discovered that WinMerge has line filters - setting up them correctly actually works.</p>
<p>Francesco</p>
|
[
{
"answer_id": 202868,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 2,
"selected": false,
"text": "\\$\\w+(:[^\\n$]+)?\\$\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,790
|
<p>I have an <strong>"ldquo"</strong>, <strong>"rdquo"</strong> and several other entities under my RSS feed. Seems like if I add</p>
<pre><code><!DOCTYPE rss [
<!ENTITY % HTMLspec PUBLIC
"-//W3C//ENTITIES Latin 1 for XHTML//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent">
%HTMLspec;
</code></pre>
<p>below the <strong>xml</strong> tag and above the <strong>rss</strong> tag then I'll be able to include those entities. I added but it doesn't seem to work. Does anyone knows what I missing? Thanks</p>
|
[
{
"answer_id": 203765,
"author": "cowgod",
"author_id": 6406,
"author_profile": "https://Stackoverflow.com/users/6406",
"pm_score": 2,
"selected": false,
"text": "“ “"
},
{
"answer_id": 13870473,
"author": "giacoder",
"author_id": 582864,
"author_profile": "https://Stackoverflow.com/users/582864",
"pm_score": 1,
"selected": false,
"text": "’ &rsquo;"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
202,792
|
<p>I'm using a whole bunch of CALayers, creating a tile-based image not unlike GoogleMaps (different versions of the same image with more/less detail).</p>
<p>The code I'm using to do this is:</p>
<pre><code>UIImage* image = [self loadImage:obj.fileName zoomLevel:obj.zoomLevel];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
obj.layerToAddTo.contents = [image CGImage];
[CATransaction commit];
</code></pre>
<p>I don't really feel like loading the CGImage from file using CoreGraphics because I'm lazy. But I will if there's a big performance boost! LoadImage just mangles a string to get the right path for loading said image, and obj is a NSObject-struct that holds all the info I need for this thread. </p>
<p>Help?</p>
|
[
{
"answer_id": 3815801,
"author": "Phil M",
"author_id": 450263,
"author_profile": "https://Stackoverflow.com/users/450263",
"pm_score": -1,
"selected": false,
"text": "UIImage -imageNamed:"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28019/"
] |
202,803
|
<p>I use emacs for viewing and editing code and other text files. I wanted to know if there is a way to search forward or backward for text which is marked in the current buffer. Similar to what I can do in notepad or wordpad. As in can I mark some text in the buffer and do a C-s or C-r and be able to search with the marked text without actually typing in the whole search text? </p>
<p>Thank you,</p>
<p>Rohit</p>
|
[
{
"answer_id": 202829,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 6,
"selected": true,
"text": "M-W C-s <RET> C-y <RET> C-s C-r"
},
{
"answer_id": 203026,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 7,
"selected": false,
"text": "C-s C-w C-w C-s C-w C-w C-w C-s M-s C-e C-s C-M-y M-s C-e C-s"
},
{
"answer_id": 11930011,
"author": "Marc Haesen",
"author_id": 1594707,
"author_profile": "https://Stackoverflow.com/users/1594707",
"pm_score": 4,
"selected": false,
"text": " (defun search-selection (beg end)\n \"search for selected text\"\n (interactive \"r\")\n (kill-ring-save beg end)\n (isearch-mode t nil nil nil)\n (isearch-yank-pop)\n )\n (define-key global-map (kbd \"<C-f3>\") 'search-selection)\n (defun search-selection (beg end)\n \"search for selected text\"\n (interactive \"r\")\n (let (\n (selection (buffer-substring-no-properties beg end))\n )\n (deactivate-mark)\n (isearch-mode t nil nil nil)\n (isearch-yank-string selection)\n )\n )\n (define-key global-map (kbd \"<C-f3>\") 'search-selection)\n"
},
{
"answer_id": 32002122,
"author": "Jackson",
"author_id": 1468130,
"author_profile": "https://Stackoverflow.com/users/1468130",
"pm_score": 3,
"selected": false,
"text": "(defun jrh-isearch-with-region ()\n \"Use region as the isearch text.\"\n (when mark-active\n (let ((region (funcall region-extract-function nil)))\n (deactivate-mark)\n (isearch-push-state)\n (isearch-yank-string region))))\n\n(add-hook 'isearch-mode-hook #'jrh-isearch-with-region)\n"
},
{
"answer_id": 36777176,
"author": "laurentmeyer",
"author_id": 4158478,
"author_profile": "https://Stackoverflow.com/users/4158478",
"pm_score": 2,
"selected": false,
"text": "isearch-forward-symbol-at-point hi chill command-f (global-set-key (kbd \"s-f\") 'isearch-forward-symbol-at-point)"
},
{
"answer_id": 72957030,
"author": "Viaceslavus",
"author_id": 15324798,
"author_profile": "https://Stackoverflow.com/users/15324798",
"pm_score": 0,
"selected": false,
"text": " (defun swiper-isearch-selected ()\n \"Use region as the isearch text.\"\n (interactive)\n (if mark-active\n (swiper-isearch (funcall region-extract-function nil))\n (swiper-isearch)))\n swiper-isearch"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27928/"
] |
202,813
|
<p>Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:</p>
<pre><code>int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
</code></pre>
<p>For those who have used PHP, here's what I'm trying to do in C#:</p>
<pre><code>$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
</code></pre>
|
[
{
"answer_id": 202830,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "int [] terms = new int[400]; // allocate an array of 400 ints\nfor(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again\n{\n terms[runs] = value;\n}\n"
},
{
"answer_id": 202839,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 1,
"selected": false,
"text": "int[] terms = new int[400];\n\nfor(int runs = 0; runs < 400; runs++)\n{\n terms[runs] = value;\n}\n"
},
{
"answer_id": 202849,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 3,
"selected": false,
"text": "int ArraySize = 400;\n\nint[] terms = new int[ArraySize];\n\n\nfor(int runs = 0; runs < ArraySize; runs++)\n{\n\n terms[runs] = runs;\n\n}\n"
},
{
"answer_id": 202853,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "List<int> Collection<int> ToArray()"
},
{
"answer_id": 202854,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 11,
"selected": true,
"text": "int[] terms = new int[400];\nfor (int runs = 0; runs < 400; runs++)\n{\n terms[runs] = value;\n}\n List<int> termsList = new List<int>();\nfor (int runs = 0; runs < 400; runs++)\n{\n termsList.Add(value);\n}\n\n// You can convert it back to an array if you would like to\nint[] terms = termsList.ToArray();\n"
},
{
"answer_id": 202861,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "int [] terms = new int[400];\nfor(int runs = 0; runs < 400; runs++)\n{\n terms[runs] = value;\n}\n List<int> terms = new List<int>();\nfor(int runs = 0; runs < 400; runs ++)\n{\n terms.Add(runs);\n}\n"
},
{
"answer_id": 202865,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "using System.Collections.Generic;\n\n// Create a List, and it can only contain integers.\nList<int> list = new List<int>();\n\nfor (int i = 0; i < 400; i++)\n{\n list.Add(i);\n}\n"
},
{
"answer_id": 203330,
"author": "Amanda Mitchell",
"author_id": 26628,
"author_profile": "https://Stackoverflow.com/users/26628",
"pm_score": 7,
"selected": false,
"text": "int[] terms = Enumerable.Range(0, 400).ToArray();\n List<int> terms = Enumerable.Range(0, 400).ToList();\n terms.Add(1337);\n"
},
{
"answer_id": 14620935,
"author": "jhyap",
"author_id": 2028195,
"author_profile": "https://Stackoverflow.com/users/2028195",
"pm_score": 2,
"selected": false,
"text": "int[] terms = new int[10]; //create 10 empty index in array terms\n\n//fill value = 400 for every index (run) in the array\n//terms.Length is the total length of the array, it is equal to 10 in this case \nfor (int run = 0; run < terms.Length; run++) \n{\n terms[run] = 400;\n}\n\n//print value from each of the index\nfor (int run = 0; run < terms.Length; run++)\n{\n Console.WriteLine(\"Value in index {0}:\\t{1}\",run, terms[run]);\n}\n\nConsole.ReadLine();\n"
},
{
"answer_id": 22375937,
"author": "user3404904",
"author_id": 3404904,
"author_profile": "https://Stackoverflow.com/users/3404904",
"pm_score": 1,
"selected": false,
"text": " static void Main(string[] args)\n {\n int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/\n int i, j;\n\n\n /*initialize elements of array arrayname*/\n for (i = 0; i < 5; i++)\n {\n arrayname[i] = i + 100;\n }\n\n /*output each array element value*/\n for (j = 0; j < 5; j++)\n {\n Console.WriteLine(\"Element and output value [{0}]={1}\",j,arrayname[j]);\n }\n Console.ReadKey();/*Obtains the next character or function key pressed by the user.\n The pressed key is displayed in the console window.*/\n }\n"
},
{
"answer_id": 22376114,
"author": "user3404904",
"author_id": 3404904,
"author_profile": "https://Stackoverflow.com/users/3404904",
"pm_score": 1,
"selected": false,
"text": " /*arrayname is an array of 5 integer*/\n int[] arrayname = new int[5];\n int i, j;\n /*initialize elements of array arrayname*/\n for (i = 0; i < 5; i++)\n {\n arrayname[i] = i + 100;\n }\n"
},
{
"answer_id": 25880091,
"author": "Ali Humayun",
"author_id": 1845464,
"author_profile": "https://Stackoverflow.com/users/1845464",
"pm_score": 2,
"selected": false,
"text": "int runs = 0; \nbool batting = true; \nstring scorecard;\n\nwhile (batting = runs < 400)\n scorecard += \"!\" + runs++;\n\nreturn scorecard.Split(\"!\");\n"
},
{
"answer_id": 30147352,
"author": "Steve",
"author_id": 4817023,
"author_profile": "https://Stackoverflow.com/users/4817023",
"pm_score": 3,
"selected": false,
"text": "using System.Collections.Generic;\n\n// Create a List, and it can only contain integers.\nList<int> list = new List<int>();\n\nfor (int i = 0; i < 400; i++)\n{\n list.Add(i);\n}\n\nint [] terms = list.ToArray();\n"
},
{
"answer_id": 30314234,
"author": "LCarter",
"author_id": 688126,
"author_profile": "https://Stackoverflow.com/users/688126",
"pm_score": 2,
"selected": false,
"text": "List<T> var termsList = terms.ToList(); var terms = termsList.ToArray(); var terms = default(int[]);\nvar termsList = terms == null ? new List<int>() : terms.ToList();\n\nfor(var i = 0; i < 400; i++)\n termsList.Add(i);\n\nterms = termsList.ToArray();\n var terms = default(int[]);\n\nfor(var i = 0; i < 400; i++)\n{\n if(terms == null)\n terms = new int[1];\n else \n Array.Resize<int>(ref terms, terms.Length + 1);\n \n terms[terms.Length - 1] = i;\n}\n Array.Add(...); List<T> List<T>"
},
{
"answer_id": 31542691,
"author": "Thracx",
"author_id": 296924,
"author_profile": "https://Stackoverflow.com/users/296924",
"pm_score": 4,
"selected": false,
"text": "public static T[] Add<T>(this T[] target, T item)\n{\n if (target == null)\n {\n //TODO: Return null or throw ArgumentNullException;\n }\n T[] result = new T[target.Length + 1];\n target.CopyTo(result, 0);\n result[target.Length] = item;\n return result;\n}\n"
},
{
"answer_id": 32515159,
"author": "Mark",
"author_id": 1463355,
"author_profile": "https://Stackoverflow.com/users/1463355",
"pm_score": 4,
"selected": false,
"text": "public static T[] Add<T>(this T[] target, params T[] items)\n {\n // Validate the parameters\n if (target == null) {\n target = new T[] { };\n }\n if (items== null) {\n items = new T[] { };\n }\n\n // Join the arrays\n T[] result = new T[target.Length + items.Length];\n target.CopyTo(result, 0);\n items.CopyTo(result, target.Length);\n return result;\n }\n"
},
{
"answer_id": 43203172,
"author": "Yitzhak Weinberg",
"author_id": 4871015,
"author_profile": "https://Stackoverflow.com/users/4871015",
"pm_score": 7,
"selected": false,
"text": "int[] array = new int[] { 3, 4 };\n\narray = array.Concat(new int[] { 2 }).ToArray();\n"
},
{
"answer_id": 56422608,
"author": "David",
"author_id": 948366,
"author_profile": "https://Stackoverflow.com/users/948366",
"pm_score": 2,
"selected": false,
"text": "Enumerable.Range(0, 400).Select(x => x).ToArray();\n"
},
{
"answer_id": 60394294,
"author": "Maghalakshmi Saravana",
"author_id": 12562878,
"author_profile": "https://Stackoverflow.com/users/12562878",
"pm_score": 0,
"selected": false,
"text": " List<string> list = new List<string>();\n list.Add(\"one\");\n list.Add(\"two\");\n list.Add(\"three\");\n list.Add(\"four\");\n list.Add(\"five\");\n string[] values = new string[list.Count];//assigning the count for array\n for(int i=0;i<list.Count;i++)\n {\n values[i] = list[i].ToString();\n }\n"
},
{
"answer_id": 61063681,
"author": "Safi Habhab",
"author_id": 9339924,
"author_profile": "https://Stackoverflow.com/users/9339924",
"pm_score": 2,
"selected": false,
"text": "string[] arrayToBeFilled;\narrayToBeFilled= arrayToBeFilled.Append(\"str\").ToArray();\n //the array you want to fill values in\nstring[] arrayToBeFilled;\n//list of values that you want to fill inside an array\nList<string> listToFill = new List<string> { \"a1\", \"a2\", \"a3\" };\n//looping through list to start filling the array\n\nforeach (string str in listToFill){\n// here are the LINQ extensions\narrayToBeFilled= arrayToBeFilled.Append(str).ToArray();\n}\n\n"
},
{
"answer_id": 63263549,
"author": "Manar Gul",
"author_id": 6312235,
"author_profile": "https://Stackoverflow.com/users/6312235",
"pm_score": 2,
"selected": false,
"text": "List<int> termsLst=new List<int>();\nfor (int runs = 0; runs < 400; runs++)\n{\n termsLst.Add(runs);\n}\nint[] terms = termsLst.ToArray();\n List<int> termsLst = terms.ToList();\n for (int runs = 0; runs < 400; runs++)\n {\n termsLst.Add(runs);\n }\n terms = termsLst.ToArray();\n"
},
{
"answer_id": 63923685,
"author": "Phillip Holmes",
"author_id": 1084830,
"author_profile": "https://Stackoverflow.com/users/1084830",
"pm_score": 2,
"selected": false,
"text": "var usageList = usageArray.ToList();\nusageList.Add(\"newstuff\");\nusageArray = usageList.ToArray();\n"
},
{
"answer_id": 63974902,
"author": "jerryurenaa",
"author_id": 11611288,
"author_profile": "https://Stackoverflow.com/users/11611288",
"pm_score": 0,
"selected": false,
"text": "List<string> info = new List<string>();\ninfo.Add(\"finally worked\");\n return info.ToArray();\n"
},
{
"answer_id": 64387791,
"author": "Leandro Bardelli",
"author_id": 888472,
"author_profile": "https://Stackoverflow.com/users/888472",
"pm_score": 6,
"selected": false,
"text": "Append Prepend LinQ using System.Linq;\n terms = terms.Append(21);\n terms = terms.Append(21).ToArray();\n"
},
{
"answer_id": 66295175,
"author": "Mondonno",
"author_id": 11824362,
"author_profile": "https://Stackoverflow.com/users/11824362",
"pm_score": 2,
"selected": false,
"text": "public void ArrayPush<T>(ref T[] table, object value)\n{\n Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)\n table.SetValue(value, table.Length - 1); // Setting the value for the new element\n}\n"
},
{
"answer_id": 72397743,
"author": "theAccountant.py",
"author_id": 2130154,
"author_profile": "https://Stackoverflow.com/users/2130154",
"pm_score": -1,
"selected": false,
"text": "int[] ids = new int[10];\nids[0] = 1;\nstring[] names = new string[10];\n\ndo\n{\n for (int i = 0; i < names.Length; i++)\n {\n Console.WriteLine(\"Enter Name\");\n names[i] = Convert.ToString(Console.ReadLine());\n Console.WriteLine($\"The Name is: {names[i]}\");\n Console.WriteLine($\"the index of name is: {i}\");\n Console.WriteLine(\"Enter ID\");\n ids[i] = Convert.ToInt32(Console.ReadLine());\n Console.WriteLine($\"The number is: {ids[i]}\");\n Console.WriteLine($\"the index is: {i}\");\n }\n\n\n} while (names.Length <= 10);\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
202,824
|
<p>I am trying to start a service from the command line using "net start SERVICENAME" and I get an access denied error.</p>
<p>I am an administrator on this server since I am in a domain group that are admins on the server. I <strong>can</strong> start/stop the service from the Services tool.</p>
<p>I am new to 2008/Vista so maybe I am just missing something..</p>
<p>update:
I did not use "run as administrator". Is this something new in 2008? Where do I find this option?</p>
|
[
{
"answer_id": 203596,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 1,
"selected": false,
"text": "runas /user:DOMAIN\\Administrator cmd\n net start SERVICENAME\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12262/"
] |
202,860
|
<p>I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0.</p>
<p>I have a label component, and I'm dynamically assigning it text from an xml document. For example:</p>
<pre><code>label.text = "<b>" + xml_node.firstChild + "</b>";
</code></pre>
<p>This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using <code><font></code> tags won't work.</p>
<p>Am I missing something? How do I make the font larger? ActionScript is just so picky!</p>
|
[
{
"answer_id": 209472,
"author": "MattSayar",
"author_id": 557,
"author_profile": "https://Stackoverflow.com/users/557",
"pm_score": 2,
"selected": true,
"text": "label.text = \"<b><font size=24>\" + xml_node.firstChild + \"</font></b>\";\n //note the 'single quotes' around the 24\nlabel.text = \"<b><font size='24'>\" + xml_node.firstChild + \"</font></b>\";\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
202,871
|
<p>I use MyGeneration along with nHibernate to create the basic POCO objects and XML mapping files. I have heard some people say they think code generators are not a good idea. What is the current best thinking? Is it just that code generation is bad when it generates thousands of lines of not understandable code?</p>
|
[
{
"answer_id": 203070,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 6,
"selected": true,
"text": "-- =============================================================\n-- === Foobar Module ===========================================\n-- =============================================================\n--\n-- === THIS IS GENERATED CODE. DO NOT EDIT. ===\n--\n-- =============================================================\n"
},
{
"answer_id": 203154,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "#line #line"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
202,907
|
<p>i'm having a problem to create a text_field without a method association. Maybe i even don't need it :-)</p>
<p>I have two radio_buttons associated to the same method:</p>
<pre><code><%= radio_button :comment, :author, "anonymous" %> Anonymous <br>
<%= radio_button :comment, :author, "real_name" %> Name <br>
</code></pre>
<p>What i would like to do is to have an text_field which when the user click on the radio_button "real_name" i can verify the value in this new text_field. </p>
<p>Basically my Controller would be something like:</p>
<p>@comment = Comment.new(params[:comment])</p>
<p>if @comment.author == "real_name"
@comment.author = "value-from-the-new-textfield
end</p>
<p>There is any way to do it?</p>
<p>Regards,</p>
<p>Victor</p>
|
[
{
"answer_id": 202970,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 4,
"selected": true,
"text": "text_field_tag"
},
{
"answer_id": 204141,
"author": "JasonOng",
"author_id": 6048,
"author_profile": "https://Stackoverflow.com/users/6048",
"pm_score": 1,
"selected": false,
"text": "<%= radio_button :verify, :author, \"anonymous\" %> Anonymous <br>\n<%= radio_button :verify, :author, \"real_name\" %> Name <br>\n if params[:verify][:author] == 'real_name' ...\n"
},
{
"answer_id": 209276,
"author": "Misplaced",
"author_id": 13710,
"author_profile": "https://Stackoverflow.com/users/13710",
"pm_score": 0,
"selected": false,
"text": "text_field_tag attr_accessor"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
202,912
|
<p>I have some hierarchical data - each entry has an id and a (nullable) parent entry id.
I want to retrieve all entries in the tree under a given entry. This is in a SQL Server 2005 database. I am querying it with LINQ to SQL in C# 3.5.</p>
<p>LINQ to SQL does not support <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" rel="noreferrer">Common Table Expressions</a> directly. My choices are to assemble the data in code with several LINQ queries, or to make a view on the database that surfaces a CTE. </p>
<p>Which option (or another option) do you think will perform better when data volumes get large?
Is SQL Server 2008's <a href="http://msdn.microsoft.com/en-us/library/bb677173.aspx" rel="noreferrer">HierarchyId type</a> supported in Linq to SQL?</p>
|
[
{
"answer_id": 203071,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "CREATE TABLE [dbo].[hierarchical_table](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [parent_id] [int] NULL,\n [data] [varchar](255) NOT NULL,\n CONSTRAINT [PK_hierarchical_table] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nCREATE VIEW [dbo].[vw_recursive_view]\nAS\nWITH hierarchy_cte(id, parent_id, data, lvl) AS\n(SELECT id, parent_id, data, 0 AS lvl\n FROM dbo.hierarchical_table\n WHERE (parent_id IS NULL)\n UNION ALL\n SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl\n FROM dbo.hierarchical_table AS t1 INNER JOIN\n hierarchy_cte AS h ON t1.parent_id = h.id)\nSELECT id, parent_id, data, lvl\nFROM hierarchy_cte AS result\n\n\nCREATE FUNCTION [dbo].[fn_tree_for_parent] \n(\n @parent int\n)\nRETURNS \n@result TABLE \n(\n id int not null,\n parent_id int,\n data varchar(255) not null,\n lvl int not null\n)\nAS\nBEGIN\n WITH hierarchy_cte(id, parent_id, data, lvl) AS\n (SELECT id, parent_id, data, 0 AS lvl\n FROM dbo.hierarchical_table\n WHERE (id = @parent OR (parent_id IS NULL AND @parent IS NULL))\n UNION ALL\n SELECT t1.id, t1.parent_id, t1.data, h.lvl + 1 AS lvl\n FROM dbo.hierarchical_table AS t1 INNER JOIN\n hierarchy_cte AS h ON t1.parent_id = h.id)\n INSERT INTO @result\n SELECT id, parent_id, data, lvl\n FROM hierarchy_cte AS result\nRETURN \nEND\n\nALTER TABLE [dbo].[hierarchical_table] WITH CHECK ADD CONSTRAINT [FK_hierarchical_table_hierarchical_table] FOREIGN KEY([parent_id])\nREFERENCES [dbo].[hierarchical_table] ([id])\n\nALTER TABLE [dbo].[hierarchical_table] CHECK CONSTRAINT [FK_hierarchical_table_hierarchical_table]\n using (DataContext dc = new HierarchicalDataContext())\n{\n HierarchicalTableEntity h = (from e in dc.HierarchicalTableEntities\n select e).First();\n var query = dc.FnTreeForParent( h.ID );\n foreach (HierarchicalTableViewEntity entity in query) {\n ...process the tree node...\n }\n}\n"
},
{
"answer_id": 203159,
"author": "JarrettV",
"author_id": 16340,
"author_profile": "https://Stackoverflow.com/users/16340",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<T> ByHierarchy<T>(\n this IEnumerable<T> source, Func<T, bool> startWith, Func<T, T, bool> connectBy)\n{\n if (source == null)\n throw new ArgumentNullException(\"source\");\n\n if (startWith == null)\n throw new ArgumentNullException(\"startWith\");\n\n if (connectBy == null)\n throw new ArgumentNullException(\"connectBy\");\n\n foreach (T root in source.Where(startWith))\n {\n yield return root;\n foreach (T child in source.ByHierarchy(c => connectBy(root, c), connectBy))\n {\n yield return child;\n }\n }\n}\n comments.ByHierarchy(comment => comment.ParentNum == parentNum, \n (parent, child) => child.ParentNum == parent.CommentNum && includeChildren)\n"
},
{
"answer_id": 203190,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 1,
"selected": false,
"text": "var categories = from c in db.Categories\n select new Category\n {\n CategoryID = c.CategoryID,\n ParentCategoryID = c.ParentCategoryID,\n SubCategories = new List<Category>(\n from sc in db.Categories\n where sc.ParentCategoryID == c.CategoryID\n select new Category {\n CategoryID = sc.CategoryID, \n ParentProductID = sc.ParentProductID\n }\n )\n };\n"
},
{
"answer_id": 203309,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "public IQueryable<Node> GetChildrenAtDepth(int NodeID, int depth)\n{\n IQueryable<Node> query = db.Nodes.Where(n => n.NodeID == NodeID);\n for(int i = 0; i < depth; i++)\n query = query.SelectMany(n => n.Children);\n //use this if the Children association has not been defined\n //query = query.SelectMany(n => db.Nodes.Where(c => c.ParentID == n.NodeID));\n return query;\n}\n"
},
{
"answer_id": 2503467,
"author": "too",
"author_id": 291496,
"author_profile": "https://Stackoverflow.com/users/291496",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE Person (\n Id INTEGER,\n Name TEXT\n);\n\nCREATE TABLE PersonInPerson (\n PersonId INTEGER NOT NULL,\n InPersonId INTEGER NOT NULL,\n Level INTEGER,\n RelationKind VARCHAR(1)\n);\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5599/"
] |
202,914
|
<p>I have a storyboard(1) that does some basic animations in 2 seconds. I want the storyboard(1) to do all the property animations I have set it up to do (this all works fine). But at 3 seconds into the storyboard(1) I want to begin storyboard(2) and exit storyboard(1) without user interaction at all.</p>
<p>Only thing I've seen that allows me to do this is when the user clicks on something. I want this to be automatic based on the position of the current storyboard(1) timeline.</p>
<p>I hope this makes enough sense. Please let me know if you need me to explain something in more detail.</p>
<p>Thanks.</p>
<p>Edit: Please post the answer in XAML or VB.net language. :)</p>
|
[
{
"answer_id": 205118,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 3,
"selected": false,
"text": "<StackPanel>\n <Rectangle Name=\"recProgressBar\"\n Fill=\"Orange\"\n Width=\"1\"\n Height=\"25\"\n Margin=\"20\"\n HorizontalAlignment=\"Left\" />\n <Button Content=\"Start Animation\"\n Width=\"150\"\n Height=\"25\">\n <Button.Triggers>\n <EventTrigger RoutedEvent=\"Button.Click\">\n <BeginStoryboard>\n <Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"recProgressBar\"\n Storyboard.TargetProperty=\"Width\"\n From=\"0\"\n To=\"250\"\n Duration=\"0:0:2\" />\n <Storyboard BeginTime=\"0:0:3\">\n <ColorAnimation Storyboard.TargetName=\"recProgressBar\"\n Storyboard.TargetProperty=\"Fill.Color\"\n To=\"DarkGreen\"\n Duration=\"0:0:1\" />\n </Storyboard>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </Button.Triggers>\n </Button>\n</StackPanel>\n"
},
{
"answer_id": 205184,
"author": "ScottN",
"author_id": 27494,
"author_profile": "https://Stackoverflow.com/users/27494",
"pm_score": 0,
"selected": false,
"text": "Dim board As Storyboard = New Storyboard\nboard = DirectCast(TryFindResource(\"Animation1\"), Storyboard)\nIf board IsNot Nothing Then\n board.Begin(Me)\n While board.GetCurrentState(Me) = ClockState.Active\n 'Wait until Animation1 ends\n End While\n 'Start Animation2\n board = DirectCast(TryFindResource(\"Animation2\"), Storyboard)\n If board IsNot Nothing Then\n board.Begin(Me)\n End If\nEnd If\n"
},
{
"answer_id": 206436,
"author": "ScottN",
"author_id": 27494,
"author_profile": "https://Stackoverflow.com/users/27494",
"pm_score": 1,
"selected": true,
"text": " Dim board As Storyboard = New Storyboard\n board = DirectCast(TryFindResource(\"DoSplit\"), Storyboard)\n If board IsNot Nothing Then\n board.Begin(Me, True)\n\n Dim t As Thread\n t = New Thread(AddressOf Me.WaitToHidePanel)\n t.SetApartmentState(ApartmentState.STA)\n t.Start()\n\n End If\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27494/"
] |
202,946
|
<p>I'm working on an application that makes extensive use of ComponentOne's C1FlexGrid. Of the dozens we use, three are missing their licenses.licx file and cause the demo splash screen to pop up while I'm starting the application.</p>
<p>Is there any way to determine which forms are causing this behavior. Short of checking hundreds of directories by hand, I don't see a way.</p>
|
[
{
"answer_id": 56021714,
"author": "StayOnTarget",
"author_id": 3195477,
"author_profile": "https://Stackoverflow.com/users/3195477",
"pm_score": 0,
"selected": false,
"text": "LicxGenerator [-r] [-p prefix] [-s] [sourcePath] [outputPath]\n -r -p -s sourcePath -s outputPath sourcePath"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
202,962
|
<p>How do I connect to a MSSQL database using Perl's DBI module in Windows?</p>
|
[
{
"answer_id": 202973,
"author": "culix",
"author_id": 28037,
"author_profile": "https://Stackoverflow.com/users/28037",
"pm_score": 3,
"selected": false,
"text": "use DBI;\nmy $dbs = \"dbi:ODBC:DRIVER={SQL Server};SERVER={ServerName}\";\nmy ($username, $password) = ('username', 'password');\n\nmy $dbh = DBI->connect($dbs, $username, $password);\n\nif (defined($dbh))\n{\n #write code here\n $dbh->disconnect;\n}\nelse\n{\n print \"Error connecting to database: Error $DBI::err - $DBI::errstr\\n\";\n}\n"
},
{
"answer_id": 203095,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 5,
"selected": true,
"text": "my $dbh = DBI->connect(\"dbi:ODBC:$dsn\", $user, $pwd, \\%attr);\n"
},
{
"answer_id": 37714262,
"author": "Neil McGuigan",
"author_id": 223478,
"author_profile": "https://Stackoverflow.com/users/223478",
"pm_score": 0,
"selected": false,
"text": "DBI:ADO:Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=localhost;Initial Catalog=$dbName;"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28037/"
] |
202,971
|
<p>I've built a simple application that applies grid-lines to an image or just simple colors for use as desktop wallpaper. The idea is that the desktop icons can be arranged within the grid. The problem is that depending on more things than I understand the actual spacing in pixels seems to be different from system to system. I've learned that at least these things play a factor:</p>
<ul>
<li>Resolution (duh)</li>
<li>Taskbar size and placement</li>
<li>Fonts</li>
</ul>
<p>There has to be more than this. Maybe there's some api call that I don't know about?</p>
|
[
{
"answer_id": 202997,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 3,
"selected": true,
"text": "using System.Management; \n\npublic string GetWinIconSpace()\n\n{\n\nManagementObjectSearcher searcher = new ManagementObjectSearcher(\"root\\\\CIMV2\",\"SELECT * FROM Win32_Desktop\"); \n\nforeach (ManagementObject wmi in searcher.Get())\n{\n try\n {\n\n return \"Desktop Icon Spacing: \" + wmi.GetPropertyValue(\"IconSpacing\").ToString();\n\n }\n\n catch { }\n\n}\n\nreturn \"Desktop Icon Spacing: Unknown\";\n\n\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"root\\\\CIMV2\",\"SELECT * FROM Win32_Desktop\"); \n\nforeach (ManagementObject wmi in searcher.Get())\n{\n try\n {\n\n return \"Desktop Icon Spacing: \" + wmi.GetPropertyValue(\"IconSpacing\").ToString();\n\n }\n\n catch { }\n\n}\n\nreturn \"Desktop Icon Spacing: Unknown\";\n } \n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16260/"
] |
202,974
|
<p>Especially when considering a fresh Rails project, what does your version control and deployment workflow look like? What tools do you use?</p>
<p>I'm interested in answers for Mac, *nix and Windows work machines. Assume a *nix server.</p>
<p>I'll edit for clarity if need be.</p>
|
[
{
"answer_id": 202991,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 5,
"selected": true,
"text": "deploy.rb cap deploy:setup && cap deploy:cold cap deploy"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9619/"
] |
202,990
|
<p>Suppose I have a dataset with those two immortal tables: Employee & Order <br/>
<strong>Emp</strong> -> ID, Name <br/>
<strong>Ord</strong> -> Something, Anotherthing, EmpID <br/>
And relation <strong>Rel</strong>: Ord (EmpID) -> Emp (ID) <br/></p>
<p>It works great in standard master/detail scenario <br/>
(show employees, follow down the relation, show related orders), <br/>
but what when I wan't to go the opposite way (show Ord table with Emp.Name)? <br/></p>
<p>Something like this:<br/></p>
<pre><code><stackpanel> // with datacontext set from code to dataset.tables["ord"]
<TextBox Text="{Binding Something}"/>
<TextBox Text="{Binding Anotherthing}"/>
<TextBox Text="{Binding ???}"/> // that's my problem, how to show related Emp.Name
</stackpanel>
</code></pre>
<p>Any ideas? I can create value converter, but if I wan't to use dataset instance which I get from parent module it gets tricky.</p>
|
[
{
"answer_id": 207805,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 0,
"selected": false,
"text": "using System.Data;\n\npublic partial class OrdDataTable : DataTable\n{\n public string EmpName\n {\n get { return this.EmpRow.Name; }\n }\n}\n"
},
{
"answer_id": 221226,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 0,
"selected": false,
"text": "<StackPanel>\n <StackPanel.Resources>\n <ObjectDataProvider x:Key=\"ds\" ObjectType=\"{x:Type mynamespace:MyDataSet}\" />\n </StackPanel.Resources>\n\n <!-- Notice we set the data context to the first item in the array of tables -->\n <StackPanel DataContext=\"{Binding Source={StaticResource ds}, Path=USERS[0]}\">\n <TextBox Text=\"{Binding NAME}\"/>\n <TextBox Text=\"{Binding COUNTRIESRow.NAME}\"/>\n </StackPanel>\n</StackPanel>\n"
},
{
"answer_id": 232876,
"author": "Enrico Campidoglio",
"author_id": 26396,
"author_profile": "https://Stackoverflow.com/users/26396",
"pm_score": 2,
"selected": true,
"text": "<StackPanel>\n <StackPanel.Resources>\n <ObjectDataProvider x:Key=\"ds\" ObjectType=\"{x:Type mynamespace:MyDataSet}\" />\n </StackPanel.Resources>\n\n <!-- We set the data context to the collection of rows in the table -->\n <StackPanel DataContext=\"{Binding Source={StaticResource ds}, Path=USERS.Rows}\">\n <ListBox ItemsSource=\"{Binding}\"\n DisplayMemberPath=\"NAME\"\n IsSynchronizedWithCurrentItem=\"True\" />\n <TextBox Text=\"{Binding Path=NAME}\"/>\n <TextBox Text=\"{Binding Path=COUNTRIESRow.NAME}\"/>\n </StackPanel>\n</StackPanel>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27956/"
] |
203,022
|
<p>I'm writing a simple CMS.</p>
<p>I want to be able to load a View, having it included inside a master page, and then scan the HTML so that I can replace some custom tags (like {{blog}} with my own blog output) and then serve it up to the browser.</p>
<p>How can I get access to the HTML from the ViewResult in order to intercept it?</p>
|
[
{
"answer_id": 203850,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": true,
"text": "ActionFilterAttribute ActionResult"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2285/"
] |
203,030
|
<p>I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.</p>
<p>Edit: My current solution, as suggested, is to use an anonymous Comparator:</p>
<pre><code>File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
} });
</code></pre>
|
[
{
"answer_id": 4248059,
"author": "Jason Orendorff",
"author_id": 94977,
"author_profile": "https://Stackoverflow.com/users/94977",
"pm_score": 6,
"selected": false,
"text": "class Pair implements Comparable {\n public long t;\n public File f;\n\n public Pair(File file) {\n f = file;\n t = file.lastModified();\n }\n\n public int compareTo(Object o) {\n long u = ((Pair) o).t;\n return t < u ? -1 : t == u ? 0 : 1;\n }\n};\n\n// Obtain the array of (file, timestamp) pairs.\nFile[] files = directory.listFiles();\nPair[] pairs = new Pair[files.length];\nfor (int i = 0; i < files.length; i++)\n pairs[i] = new Pair(files[i]);\n\n// Sort them by timestamp.\nArrays.sort(pairs);\n\n// Take the sorted pairs and extract only the file part, discarding the timestamp.\nfor (int i = 0; i < files.length; i++)\n files[i] = pairs[i].f;\n"
},
{
"answer_id": 9929956,
"author": "Calvin Schultz",
"author_id": 1301413,
"author_profile": "https://Stackoverflow.com/users/1301413",
"pm_score": 2,
"selected": false,
"text": "public String[] getDirectoryList(String path) {\n String[] dirListing = null;\n File dir = new File(path);\n dirListing = dir.list();\n\n Arrays.sort(dirListing, 0, dirListing.length);\n return dirListing;\n}\n"
},
{
"answer_id": 15455840,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 1,
"selected": false,
"text": "Function<File, Long> getLastModified = new Function<File, Long>() {\n public Long apply(File file) {\n return file.lastModified();\n }\n};\n\nList<File> orderedFiles = Ordering.natural().onResultOf(getLastModified).\n sortedCopy(files);\n"
},
{
"answer_id": 17625095,
"author": "Matthew Madson",
"author_id": 1028367,
"author_profile": "https://Stackoverflow.com/users/1028367",
"pm_score": 4,
"selected": false,
"text": "private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {\n try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {\n return fileStream\n .map(Path::toFile)\n .collect(Collectors.toMap(Function.identity(), File::lastModified))\n .entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue())\n// .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) // replace the previous line with this line if you would prefer files listed newest first\n .map(Map.Entry::getKey)\n .map(File::toPath) // remove this line if you would rather work with a List<File> instead of List<Path>\n .collect(Collectors.toList());\n }\n}\n private static List<File> listFilesOldestFirst(final String directoryPath) throws IOException {\n final List<File> files = Arrays.asList(new File(directoryPath).listFiles());\n final Map<File, Long> constantLastModifiedTimes = new HashMap<File,Long>();\n for (final File f : files) {\n constantLastModifiedTimes.put(f, f.lastModified());\n }\n Collections.sort(files, new Comparator<File>() {\n @Override\n public int compare(final File f1, final File f2) {\n return constantLastModifiedTimes.get(f1).compareTo(constantLastModifiedTimes.get(f2));\n }\n });\n return files;\n}\n private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {\n try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {\n return fileStream\n .map(Path::toFile)\n .sorted(Comparator.comparing(File::lastModified))\n .map(File::toPath) // remove this line if you would rather work with a List<File> instead of List<Path>\n .collect(Collectors.toList());\n }\n}\n final List<File> sorted = Arrays.asList(new File(directoryPathString).listFiles());\nsorted.sort(Comparator.comparing(File::lastModified));\n"
},
{
"answer_id": 21534151,
"author": "PhannGor",
"author_id": 1845885,
"author_profile": "https://Stackoverflow.com/users/1845885",
"pm_score": 5,
"selected": false,
"text": "File[] files = directory.listFiles();\n\nArrays.sort(files, new Comparator<File>() {\n public int compare(File f1, File f2) {\n return Long.compare(f1.lastModified(), f2.lastModified());\n }\n});\n"
},
{
"answer_id": 24159031,
"author": "Vikas",
"author_id": 3711592,
"author_profile": "https://Stackoverflow.com/users/3711592",
"pm_score": 1,
"selected": false,
"text": " import org.apache.commons.io.comparator.LastModifiedFileComparator; \n\n\nFile[] files = directory.listFiles();\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);\n for (File file : files) {\n Date lastMod = new Date(file.lastModified());\n System.out.println(\"File: \" + file.getName() + \", Date: \" + lastMod + \"\");\n }\n"
},
{
"answer_id": 25254566,
"author": "Balaji Boggaram Ramanarayan",
"author_id": 2101290,
"author_profile": "https://Stackoverflow.com/users/2101290",
"pm_score": 4,
"selected": false,
"text": "org.apache.commons.io.comparator.LastModifiedFileComparator\n public static void main(String[] args) throws IOException {\n File directory = new File(\".\");\n // get just files, not directories\n File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);\n\n System.out.println(\"Default order\");\n displayFiles(files);\n\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);\n System.out.println(\"\\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)\");\n displayFiles(files);\n\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);\n System.out.println(\"\\nLast Modified Descending Order (LASTMODIFIED_REVERSE)\");\n displayFiles(files);\n\n }\n"
},
{
"answer_id": 32955978,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 4,
"selected": false,
"text": "Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));"
},
{
"answer_id": 33951175,
"author": "Hirdesh Vishwdewa",
"author_id": 1479735,
"author_profile": "https://Stackoverflow.com/users/1479735",
"pm_score": 0,
"selected": false,
"text": "android File downloadDir = new File(\"mypath\"); \nFile[] list = downloadDir.listFiles();\n for (int i = list.length-1; i >=0 ; i--) {\n //use list.getName to get the name of the file\n }\n"
},
{
"answer_id": 38729275,
"author": "Jaydev",
"author_id": 4269615,
"author_profile": "https://Stackoverflow.com/users/4269615",
"pm_score": 1,
"selected": false,
"text": "private static List<File> sortByLastModified(String dirPath) {\n List<File> files = listFilesRec(dirPath);\n Collections.sort(files, new Comparator<File>() {\n public int compare(File o1, File o2) {\n return Long.compare(o1.lastModified(), o2.lastModified());\n }\n });\n return files;\n}\n"
},
{
"answer_id": 44445813,
"author": "viniciussss",
"author_id": 4077150,
"author_profile": "https://Stackoverflow.com/users/4077150",
"pm_score": 6,
"selected": false,
"text": "File[] files = directory.listFiles();\nArrays.sort(files, Comparator.comparingLong(File::lastModified));\n File[] files = directory.listFiles();\nArrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());\n"
},
{
"answer_id": 49572642,
"author": "Anand Savjani",
"author_id": 4749098,
"author_profile": "https://Stackoverflow.com/users/4749098",
"pm_score": 2,
"selected": false,
"text": "Collections.sort(listFiles, new Comparator<File>() {\n public int compare(File f1, File f2) {\n return Long.compare(f1.lastModified(), f2.lastModified());\n }\n });\n listFiles"
},
{
"answer_id": 51573553,
"author": "user4378029",
"author_id": 4378029,
"author_profile": "https://Stackoverflow.com/users/4378029",
"pm_score": -1,
"selected": false,
"text": "list.add(1, object1)\nlist.add(2, object3)\nlist.add(2, object2)\n"
},
{
"answer_id": 51590308,
"author": "user4378029",
"author_id": 4378029,
"author_profile": "https://Stackoverflow.com/users/4378029",
"pm_score": 0,
"selected": false,
"text": "String modified_20_digits = (\"00000000000000000000\".concat(Long.toString(temp.lastModified()))).substring(Long.toString(temp.lastModified()).length()); \n\nresult_filenames.add(modified_20_digits+temp.getAbsoluteFile().toString());\n"
},
{
"answer_id": 63954685,
"author": "Ward",
"author_id": 1649029,
"author_profile": "https://Stackoverflow.com/users/1649029",
"pm_score": 0,
"selected": false,
"text": "files = Arrays.stream(files)\n .map(FileWithLastModified::ofFile)\n .sorted(comparingLong(FileWithLastModified::lastModified))\n .map(FileWithLastModified::file)\n .toArray(File[]::new);\n\nprivate static class FileWithLastModified {\n private final File file;\n private final long lastModified;\n\n private FileWithLastModified(File file, long lastModified) {\n this.file = file;\n this.lastModified = lastModified;\n }\n\n public static FileWithLastModified ofFile(File file) {\n return new FileWithLastModified(file, file.lastModified());\n }\n\n public File file() {\n return file;\n }\n\n public long lastModified() {\n return lastModified;\n }\n}\n"
},
{
"answer_id": 68571076,
"author": "NoviceCoder",
"author_id": 2853499,
"author_profile": "https://Stackoverflow.com/users/2853499",
"pm_score": 2,
"selected": false,
"text": "val filesList = directory.listFiles()\n\nfilesList?.let{ list ->\n Arrays.sort(list) { \n f1, f2 -> f2.lastModified().compareTo(f1.lastModified()) \n }\n}\n"
},
{
"answer_id": 70019349,
"author": "shubham chouhan",
"author_id": 9955950,
"author_profile": "https://Stackoverflow.com/users/9955950",
"pm_score": 2,
"selected": false,
"text": "Ascending -> Arrays.sort(files, (o1, o2) -> Long.compare(o1.lastModified(), o2.lastModified()));\n\nDescending -> Arrays.sort(files, (o1, o2) -> Long.compare(o2.lastModified(), o1.lastModified()));\n"
},
{
"answer_id": 70892622,
"author": "josemerazo",
"author_id": 18057080,
"author_profile": "https://Stackoverflow.com/users/18057080",
"pm_score": 0,
"selected": false,
"text": " File[] listaArchivos = folder.listFiles();\n Arrays.sort(listaArchivos, new Comparator<File>() {\n @Override\n public int compare(File f1, File f2) {\n return (f1.lastModified() < f2.lastModified()) ? -1 : ((f1.lastModified() == f2.lastModified()) ? 0 : 1);\n }\n }); \n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
] |
203,050
|
<p>I want to deploy my site on my web hosting package by doing a checkout through subversion. I do not have SSH access to my hosting package, which is just a basic LAMP web hosting package, but I do know that there is an SVN client installed on the web server.</p>
<p>I was thinking of writing some sort of script (PHP or Shell) that can do different functions. Like a checkout, update, switch to another tag etc. and that I can call externally in some sort of fashion.</p>
<p>Any input on best practices, things to look out for and how to go about this is very much appreciated.</p>
<blockquote>
<p><strong>UPDATE</strong>: I have been using the
following technique for the past
couple of weeks now. I've carefully
crafted (and well tested) a couple
shell scripts that I can execute from
cron through cPanel. Whenever cron has
completed a job it will email me the
console output of the job. this way I
can monitor if all commands succeeded. Since I only
do updates on the server and no
commits, I haven't run into any
issues concerning Subversion. Of course, in my .htaccess
files I have created a rule that will deny
any access to the hidden .svn folders.</p>
</blockquote>
|
[
{
"answer_id": 203084,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "rsync"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] |
203,058
|
<p>I have a C application that I've created in VS2008. I am creating a mock creation function that overrides function references in a struct. However if I try and do this in a straight forward fashion with something like:</p>
<pre><code>void *ptr = &(*env)->GetVersion;
*ptr = <address of new function>
</code></pre>
<p>then I get a "error C2100: illegal indirection" error as *ptr, when ptr is a void * seems to be a banned construct. I can get around it by using a int/long pointer as well, mapping that to the same address and modifying the contents of the long pointer:</p>
<pre><code>*structOffsetPointer = &(*env)->GetVersion;
functionPointer = thisGetVersion;
structOffsetPointerAsLong = (long *)structOffsetPointer;
*structOffsetPointerAsLong = (long)functionPointer;
</code></pre>
<p>but I am concerned that using long or int pointers will cause problems if I switch between 32 and 64 bit environments.</p>
<p>So is there are easy way to disable this error? Assuming not, is either int or long 64 bits under win64?</p>
|
[
{
"answer_id": 203077,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "UINT_PTR uintptr_t stdint.h"
},
{
"answer_id": 203093,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 2,
"selected": false,
"text": "void blah = 0xdeadbabe; // let's assume a 32-bit addressing system\n int GetVersion();\n int (**ptr)() = &(*env)->GetVersion;\n"
},
{
"answer_id": 203111,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 3,
"selected": true,
"text": "void **ptr = (void **) &(*env)->GetVersion;\n*ptr = <address of new function>\n typedef int (*fncPtr)(void);\nfncPtr *ptr = &(*env)->GetVersion;\n*ptr = NewFunction;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7122/"
] |
203,075
|
<p>For example, I'm writing tests against a CsvReader. It's a simple class that enumerates and splits rows of text. Its only <em>raison d'être</em> is ignoring commas within quotes. It's less than a page.</p>
<p>By "black box" testing the class, I've checked things like</p>
<ul>
<li>What if the file doesn't exist?</li>
<li>What if I don't have permission on the file?</li>
<li>What if the file has non-Windows line-breaks?</li>
</ul>
<p>But in fact, all of these things are the StreamReader's business. My class works without doing anything about these cases. So in essence, my tests are catching errors thrown by StreamReader, and testing behavior handled by the framework. It feels like a lot of work for nothing.</p>
<p>I've seen the related questions</p>
<ul>
<li><a href="https://stackoverflow.com/questions/164170/should-qa-test-from-a-strictly-black-box-perspective">Should QA test from a strictly black-box perspective?</a> </li>
<li><a href="https://stackoverflow.com/questions/12569/rigor-in-capturing-test-cases-for-unit-testing">Rigor in capturing test cases for unit testing</a></li>
</ul>
<p>My question is, am I missing the point of "glass box" testing if I use what I know to <em>avoid</em> this kind of work?</p>
|
[
{
"answer_id": 203175,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "public class CvsReader {\n private string filename;\n public CvsReader(string filename)\n {\n this.filename = filename;\n }\n\n public string Read()\n {\n StreamReader reader = new StreamReader( this.filename );\n string contents = reader.ReadToEnd();\n .... do some stuff with contents...\n return contents;\n }\n}\n public class CvsReader {\n private IStream stream;\n public CvsReader( IStream stream )\n {\n this.stream = stream;\n }\n\n public string Read()\n {\n StreamReader reader = new StreamReader( this.stream );\n string contents = reader.ReadToEnd();\n ... do some stuff with contents ...\n return contents;\n }\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
203,085
|
<p>How can I make my compilation optimized for Windows 64 bit?</p>
|
[
{
"answer_id": 204099,
"author": "TimothyP",
"author_id": 28149,
"author_profile": "https://Stackoverflow.com/users/28149",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Runtime.InteropServices;\n\nclass SystemChecker\n{\n static bool Is64Bit\n {\n get { return Marshal.SizeOf(typeof(IntPtr)) == 8; }\n }\n}\n"
},
{
"answer_id": 12466981,
"author": "Lorenz Lo Sauer",
"author_id": 901946,
"author_profile": "https://Stackoverflow.com/users/901946",
"pm_score": 1,
"selected": false,
"text": "/platform /platform:x86 /platform:anycpu /platform:anycpu bool is64BitProcess = IntPtr.Size == 8;\nint bitProcess = IntPtr.Size*8;\n//C# 4 provides System.Environment.Is64BitProcess\n//TimothyP's solution:\nbool is64BitProcess = Marshal.SizeOf(typeof(IntPtr)) == 8;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
203,090
|
<p>Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="https://stackoverflow.com/a/19799236/8479">https://stackoverflow.com/a/19799236/8479</a></p>
<hr>
<p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p>
<p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p>
<p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p>
<p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p>
<pre><code>rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
</code></pre>
<p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p>
<p>I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p>
|
[
{
"answer_id": 203099,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 3,
"selected": false,
"text": "::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like \"backup_04.15.08.7z\")\nSET DT=%date%\nSET DT=%DT:/=.%\nSET DT=%DT:-=.%\n"
},
{
"answer_id": 203108,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 4,
"selected": false,
"text": "FOR /F \"TOKENS=1* DELIMS= \" %%A IN ('DATE/T') DO SET CDATE=%%B\nFOR /F \"TOKENS=1,2 eol=/ DELIMS=/ \" %%A IN ('DATE/T') DO SET mm=%%B\nFOR /F \"TOKENS=1,2 DELIMS=/ eol=/\" %%A IN ('echo %CDATE%') DO SET dd=%%B\nFOR /F \"TOKENS=2,3 DELIMS=/ \" %%A IN ('echo %CDATE%') DO SET yyyy=%%B\nSET date=%mm%%dd%%yyyy%\n"
},
{
"answer_id": 203115,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 4,
"selected": false,
"text": "@For /F \"tokens=2,3,4 delims=/ \" %%A in ('Date /t') do @( \n Set Month=%%A\n Set Day=%%B\n Set Year=%%C\n)\n\n@echo DAY = %Day%\n@echo Month = %Month%\n@echo Year = %Year%\n"
},
{
"answer_id": 203116,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 11,
"selected": true,
"text": "@echo off\nFor /f \"tokens=2-4 delims=/ \" %%a in ('date /t') do (set mydate=%%c-%%a-%%b)\nFor /f \"tokens=1-2 delims=/:\" %%a in ('time /t') do (set mytime=%%a%%b)\necho %mydate%_%mytime%\n For /f \"tokens=1-2 delims=/:\" %%a in (\"%TIME%\") do (set mytime=%%a%%b)\n @echo off\nfor /F \"usebackq tokens=1,2 delims==\" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j\nset ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%\necho Local date is [%ldt%]\n"
},
{
"answer_id": 203127,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": "set hour=%time:~0,2%\nif \"%time:~0,1%\"==\" \" set hour=0%time:~1,1%\nset _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%\n"
},
{
"answer_id": 741748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%\n"
},
{
"answer_id": 1849224,
"author": "DigiP",
"author_id": 225031,
"author_profile": "https://Stackoverflow.com/users/225031",
"pm_score": 4,
"selected": false,
"text": "\"d:\\Program Files\\7-Zip\\7z.exe\" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip\n"
},
{
"answer_id": 1951681,
"author": "Uri Liebeskind",
"author_id": 237474,
"author_profile": "https://Stackoverflow.com/users/237474",
"pm_score": 7,
"selected": false,
"text": "%DATE% dir date.exe date.exe +\"%Y-%m-%d\" date.exe +\"%T\" date.exe +\"%Y%m%d %H%M%S: Any text\" date.exe +\"Text: %y/%m/%d-any text-%H.%M\" Command: date.exe +\"%m-%d \"\"\"%H %M %S \"\"\"\" date.exe -r c:\\file.txt +\"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S\" for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n\n for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y-%%m-%%d %%H:%%M:%%S\"') do set timestamp=%%i\n for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n\n for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y-%%m-%%d.%%H%%M%%S\"') do ren file.txt file.%%i.txt\n date.exe date"
},
{
"answer_id": 2854857,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 4,
"selected": false,
"text": " :: Start - Run , type:\n cmd /c \"powershell get-date -format ^\"{yyyy-MM-dd HH:mm:ss}^\"|clip\"\n\n :: click into target media, Ctrl + V to paste the result \n @echo off\n :: START USAGE ==================================================================\n ::SET THE NICETIME \n :: SET NICETIME=BOO\n :: CALL GetNiceTime.cmd \n\n :: ECHO NICETIME IS %NICETIME%\n\n :: echo nice time is %NICETIME%\n :: END USAGE ==================================================================\n\n echo set hhmmsss\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=:\" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c \n ::DEBUG ECHO hhmmsss IS %hhmmsss%\n ::DEBUG PAUSE\n echo %yyyymmdd%\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=.\" %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D\n ::DEBUG ECHO yyyymmdd IS %yyyymmdd%\n ::DEBUG PAUSE\n\n\n set NICETIME=%yyyymmdd%_%hhmmsss%\n ::DEBUG echo THE NICETIME IS %NICETIME%\n\n ::DEBUG PAUSE\n"
},
{
"answer_id": 3202796,
"author": "vMax",
"author_id": 386539,
"author_profile": "https://Stackoverflow.com/users/386539",
"pm_score": 6,
"selected": false,
"text": "-----------8<------8<------------ snip -- snip ----------8<-------------\n :: Works on any NT/2k machine independent of regional date settings\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set '%%c'=%%k))\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'% \n ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n\n :EOF\n-----------8<------8<------------ snip -- snip ----------8<-------------\n"
},
{
"answer_id": 3859042,
"author": "Matthew Johnson",
"author_id": 466219,
"author_profile": "https://Stackoverflow.com/users/466219",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %a in ('%date% %time%') do echo %c-%a-%b %d%e\n"
},
{
"answer_id": 4061880,
"author": "Sally",
"author_id": 478885,
"author_profile": "https://Stackoverflow.com/users/478885",
"pm_score": 2,
"selected": false,
"text": "DateFormat.exe --h"
},
{
"answer_id": 4584577,
"author": "Jeroen Wiert Pluimers",
"author_id": 29290,
"author_profile": "https://Stackoverflow.com/users/29290",
"pm_score": 3,
"selected": false,
"text": "%date% date/t date echo:^|date date/t C:\\temp>set-date-cmd.bat\nToday is Year: [2011] Month: [01] Day: [03]\n20110103\n :: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional date settings\n::\n:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale\n:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'\n:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date\n:: set '%%c'=%%k\n:: set 'yy'=%%k\n::\n:: In addition, date will display the current date before the input prompt using dashes\n:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch\n:: and one occurence in English.\n:: This skips the first iteration:\n:: if \"%%a\" GEQ \"A\"\n::\n:: echo:^|date\n:: Huidige datum: ma 03-01-2011\n:: Voer de nieuwe datum in: (dd-mm-jj)\n:: The current date is: Mon 01/03/2011\n:: Enter the new date: (mm-dd-yy)\n::\n:: date/t\n:: ma 03-01-2011\n:: Mon 01/03/2011\n::\n:: The assumption in this batch-file is that echo:^|date will return the date format\n:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.\n::\n:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.\n:: That will resolve the order of the tokens.\n::\n@ECHO off\n set v_day=\n set v_month=\n set v_year=\n\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n::DEBUG echo toks=%toks%\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n::DEBUG echo first token=%%a\n if \"%%a\" GEQ \"A\" (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set 'yy'=%%k\n )\n )\n )\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'%\n\n ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n set datestring=%V_Year%%V_Month%%V_Day%\n echo %datestring%\n\n :EOF\n"
},
{
"answer_id": 4584820,
"author": "Jeroen Wiert Pluimers",
"author_id": 29290,
"author_profile": "https://Stackoverflow.com/users/29290",
"pm_score": 3,
"selected": false,
"text": ":: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional time settings\n::\n:: Gets the time in ISO 8601 24-hour format\n::\n:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.\n:: Since ISO 8601 does not care about AM/PM, we use %time%\n::\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n for /f \"tokens=1-4 delims=:,.-/ \" %%i in ('echo %time%') do (\n set 'hh'=%%i\n set 'mm'=%%j\n set 'ss'=%%k\n set 'ff'=%%l)\n ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%\n\n ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]\n set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%\n echo %timestring%\n\n :EOF\n"
},
{
"answer_id": 6348634,
"author": "KChiki",
"author_id": 798300,
"author_profile": "https://Stackoverflow.com/users/798300",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=1-5 delims=/ \" %%d in (\"%date%\") do rename \"decrypted.txt\" %%g-%%e-%%f.txt\n"
},
{
"answer_id": 6707326,
"author": "sudipto roy",
"author_id": 846495,
"author_profile": "https://Stackoverflow.com/users/846495",
"pm_score": 5,
"selected": false,
"text": "echo %Date:~0,3%day\n"
},
{
"answer_id": 7319693,
"author": "V15I0N",
"author_id": 930610,
"author_profile": "https://Stackoverflow.com/users/930610",
"pm_score": 2,
"selected": false,
"text": "rem save the existing format definition\nfor /f \"skip=2 tokens=3\" %%a in ('reg query \"HKCU\\Control Panel\\International\" /v sShortDate') do set FORMAT=%%a\nrem set ISO specific format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:\nrem query the date in the ISO specific format \nset ISODATE=%DATE%\nrem restore previous format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:\n"
},
{
"answer_id": 16264795,
"author": "John Langstaff",
"author_id": 714326,
"author_profile": "https://Stackoverflow.com/users/714326",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e\n"
},
{
"answer_id": 19799236,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 7,
"selected": false,
"text": "@echo off\npushd \"%temp%\"\nmakecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul\nfor /f \"tokens=3-7\" %%a in ('find /i \"makecab\"^<~.rpt') do (\n set \"current-date=%%e-%%b-%%c\"\n set \"current-time=%%d\"\n set \"weekday=%%a\"\n)\ndel ~.*\npopd\necho %weekday% %current-date% %current-time%\npause\n @echo off\nsetlocal\nfor /f \"skip=8 tokens=2,3,4,5,6,7,8 delims=: \" %%D in ('robocopy /l * \\ \\ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (\n set \"dow=%%D\"\n set \"month=%%E\"\n set \"day=%%F\"\n set \"HH=%%G\"\n set \"MM=%%H\"\n set \"SS=%%I\"\n set \"year=%%J\"\n)\n\necho Day of the week: %dow%\necho Day of the month : %day%\necho Month : %month%\necho hour : %HH%\necho minutes : %MM%\necho seconds : %SS%\necho year : %year%\nendlocal\n .bat @if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment\n\n@echo off\ncscript //E:JScript //nologo \"%~f0\"\nexit /b 0\n*------------------------------------------------------------------------------*/\n\nfunction GetCurrentDate() {\n // Today date time which will used to set as default date.\n var todayDate = new Date();\n todayDate = todayDate.getFullYear() + \"-\" +\n (\"0\" + (todayDate.getMonth() + 1)).slice(-2) + \"-\" +\n (\"0\" + todayDate.getDate()).slice(-2) + \" \" + (\"0\" + todayDate.getHours()).slice(-2) + \":\" +\n (\"0\" + todayDate.getMinutes()).slice(-2);\n\n return todayDate;\n }\n\nWScript.Echo(GetCurrentDate());\n :sub echo(str) :end sub\necho off\n'>nul 2>&1|| copy /Y %windir%\\System32\\doskey.exe %windir%\\System32\\'.exe >nul\n'& echo current date:\n'& cscript /nologo /E:vbscript \"%~f0\"\n'& exit /b\n\n'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.\n'1 = vbLongDate - Returns date: weekday, monthname, year\n'2 = vbShortDate - Returns date: mm/dd/yy\n'3 = vbLongTime - Returns time: hh:mm:ss PM/AM\n'4 = vbShortTime - Return time: hh:mm\n\nWScript.echo Replace(FormatDateTime(Date,1),\", \",\"-\")\n C:\\> powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"\n for /f \"delims=\" %%# in ('powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"') do @set _date=%%#\n @if (@X)==(@Y) @end /****** silent line that start JScript comment ******\n\n@echo off\n::::::::::::::::::::::::::::::::::::\n::: Compile the script ::::\n::::::::::::::::::::::::::::::::::::\nsetlocal\nif exist \"%~n0.exe\" goto :skip_compilation\n\nset \"frm=%SystemRoot%\\Microsoft.NET\\Framework\\\"\n\n:: Searching the latest installed .NET framework\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\v*\"') do (\n if exist \"%%v\\jsc.exe\" (\n rem :: the javascript.net compiler\n set \"jsc=%%~dpsnfxv\\jsc.exe\"\n goto :break_loop\n )\n)\necho jsc.exe not found && exit /b 0\n:break_loop\n\n\ncall %jsc% /nologo /out:\"%~n0.exe\" \"%~dpsfnx0\"\n::::::::::::::::::::::::::::::::::::\n::: End of compilation ::::\n::::::::::::::::::::::::::::::::::::\n:skip_compilation\n\n\"%~n0.exe\"\n\nexit /b 0\n\n\n****** End of JScript comment ******/\nimport System;\nimport System.IO;\n\nvar dt=DateTime.Now;\nConsole.WriteLine(dt.ToString(\"yyyy-MM-dd hh:mm:ss\"));\n @echo off\nsetlocal\ndel /q /f %temp%\\timestampfile_*\n\nLogman.exe stop ts-CPU 1>nul 2>&1\nLogman.exe delete ts-CPU 1>nul 2>&1\n\nLogman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c \"\\Processor(_Total)\\%% Processor Time\" -o %temp%\\timestampfile_ >nul\nLogman.exe start ts-CPU 1>nul 2>&1\n\nLogman.exe stop ts-CPU >nul 2>&1\nLogman.exe delete ts-CPU >nul 2>&1\nfor /f \"tokens=2 delims=_.\" %%t in ('dir /b %temp%\\timestampfile_*^&del /q/f %temp%\\timestampfile_*') do set timestamp=%%t\n\necho %timestamp%\necho MM: %timestamp:~0,2%\necho dd: %timestamp:~2,2%\necho hh: %timestamp:~4,2%\necho mm: %timestamp:~6,2%\n\nendlocal\nexit /b 0\n for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in (\"%%#\") do @set %%@\necho %day%\necho %DayOfWeek%\necho %hour%\necho %minute%\necho %month%\necho %quarter%\necho %second%\necho %weekinmonth%\necho %year%\n @echo off\nsetlocal\n\n:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance\n::if defined USERDOMAIN_roamingprofile (set \"v=v4\") else (set \"v=\")\n\nfor /f \"tokens=4 delims=. \" %%# in ('ver') do if %%# GTR 5 (set \"v=v4\") else (\"v=\")\nset \"mon=\"\nfor /f \"skip=2 delims=,\" %%# in ('typeperf \"\\UDP%v%\\*\" -si 0 -sc 1') do (\n if not defined mon (\n for /f \"tokens=1-7 delims=.:/ \" %%a in (%%#) do (\n set mon=%%a\n set date=%%b\n set year=%%c\n set hour=%%d\n set minute=%%e\n set sec=%%f\n set ms=%%g\n )\n )\n)\necho %year%.%mon%.%date%\necho %hour%:%minute%:%sec%.%ms%\nendlocal\n <!-- : Batch portion\n\n@echo off\nsetlocal\n\nfor /f \"delims=\" %%I in ('mshta \"%~f0\"') do set \"now.%%~I\"\n\nrem Display all variables beginning with \"now.\"\nset now.\n\ngoto :EOF\n\nend batch / begin HTA -->\n\n<script>\n resizeTo(0,0)\n var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),\n now = new Date(),\n props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',\n 'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',\n 'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',\n 'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',\n 'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],\n output = [];\n\n for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}\n close(fso.Write(output.join('\\n')));\n</script>\n"
},
{
"answer_id": 21282321,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "wmic :Now -- Gets the current date and time into separate variables\n:: %~1: [out] Year\n:: %~2: [out] Month\n:: %~3: [out] Day\n:: %~4: [out] Hour\n:: %~5: [out] Minute\n:: %~6: [out] Second\n setlocal\n for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t\n endlocal & (\n if \"%~1\" neq \"\" set %~1=%T:~0,4%\n if \"%~2\" neq \"\" set %~2=%T:~4,2%\n if \"%~3\" neq \"\" set %~3=%T:~6,2%\n if \"%~4\" neq \"\" set %~4=%T:~8,2%\n if \"%~5\" neq \"\" set %~5=%T:~10,2%\n if \"%~6\" neq \"\" set %~6=%T:~12,2%\n )\ngoto:eof\n call:Now Y M D H N S\necho %Y%-%M%-%D% %H%:%N%:%S%\n 2014-01-22 12:51:53\n call:Now Y M"
},
{
"answer_id": 25714111,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 5,
"selected": false,
"text": "@echo off\nfor /f \"tokens=2 delims==\" %%a in ('wmic OS Get localdatetime /value') do set \"dt=%%a\"\nset \"YY=%dt:~2,2%\" & set \"YYYY=%dt:~0,4%\" & set \"MM=%dt:~4,2%\" & set \"DD=%dt:~6,2%\"\nset \"HH=%dt:~8,2%\" & set \"Min=%dt:~10,2%\" & set \"Sec=%dt:~12,2%\"\n\nset \"datestamp=%YYYY%%MM%%DD%\" & set \"timestamp=%HH%%Min%%Sec%\" & set \"fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%\"\necho datestamp: \"%datestamp%\"\necho timestamp: \"%timestamp%\"\necho fullstamp: \"%fullstamp%\"\npause\n"
},
{
"answer_id": 27012486,
"author": "gdelfino",
"author_id": 93947,
"author_profile": "https://Stackoverflow.com/users/93947",
"pm_score": 3,
"selected": false,
"text": "PowerShell -Command \"get-date\"\n"
},
{
"answer_id": 38905219,
"author": "bvj",
"author_id": 241296,
"author_profile": "https://Stackoverflow.com/users/241296",
"pm_score": -1,
"selected": false,
"text": "ECHOTIMESTAMP DTS @ECHO off\n\nCALL :ECHOTIMESTAMP\nGOTO END\n\n:TIMESTAMP\nSETLOCAL EnableDelayedExpansion\n SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!\n SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!\n SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!\nENDLOCAL & SET \"%~1=%DTS%\"\nGOTO :EOF\n\n:ECHOTIMESTAMP\nSETLOCAL\n CALL :TIMESTAMP DTS\n ECHO %DTS%\nENDLOCAL\nGOTO :EOF\n\n:END\n\nEXIT /b 0\n"
},
{
"answer_id": 38958529,
"author": "NotepadPlusPlus PRO",
"author_id": 2920692,
"author_profile": "https://Stackoverflow.com/users/2920692",
"pm_score": -1,
"selected": false,
"text": ":: Check your local date format\necho %date%\n\n :: Output is Mon 08/15/2016\n\n:: get day (start index, number of characters)\n:: (index starts with zero)\nset myday=%DATE:~0,4%\necho %myday%\n :: output is Mon \n\n:: get month\nset mymonth=%DATE:~4,2%\necho %mymonth%\n :: output is 08\n\n:: get date \nset mydate=%DATE:~7,2% \necho %mydate%\n :: output is 15\n\n:: get year\nset myyear=%DATE:~10,4%\necho %myyear%\n :: output is 2016\n"
},
{
"answer_id": 38972828,
"author": "Frizz1977",
"author_id": 1794049,
"author_profile": "https://Stackoverflow.com/users/1794049",
"pm_score": -1,
"selected": false,
"text": "SET DATE=%date%\nSET YEAR=%DATE:~0,4%\nSET MONTH=%DATE:~5,2%\nSET DAY=%DATE:~8,2%\nECHO %YEAR%\nECHO %MONTH%\nECHO %DAY%\n\nSET DATE_FRM=%YEAR%-%MONTH%-%DAY% \nECHO %DATE_FRM%\n"
},
{
"answer_id": 43903620,
"author": "Adolfo",
"author_id": 3075331,
"author_profile": "https://Stackoverflow.com/users/3075331",
"pm_score": 2,
"selected": false,
"text": ":: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format\n:: - Sets environment variables %_isotime% and %_now% to current time\n:: - On failure, clears these environment variables\n:: Inspired on -> https://ss64.com/nt/syntax-getdate.html\n:: - (cX) 2017 adolfo.dimare@gmail.com\n:: - http://stackoverflow.com/questions/203090\n@echo off\n\nset _isotime=\nset _now=\n\n:: Check that WMIC.exe is available\nWMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_\n\nif not (%1)==() goto _help\nSetLocal EnableDelayedExpansion\n\n:: Use WMIC.exe to retrieve date and time\nFOR /F \"skip=1 tokens=1-6\" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (\n IF \"%%~L\"==\"\" goto _WMIC_done_\n set _yyyy=%%L\n set _mm=00%%J\n set _dd=00%%G\n set _hour=00%%H\n set _minute=00%%I\n set _second=00%%K\n)\n:_WMIC_done_\n\n:: 1 2 3 4 5 6\n:: %%G %%H %%I %%J %%K %%L\n:: Day Hour Minute Month Second Year\n:: 27 9 35 4 38 2017\n\n:: Remove excess leading zeroes\n set _mm=%_mm:~-2%\n set _dd=%_dd:~-2%\n set _hour=%_hour:~-2%\n set _minute=%_minute:~-2%\n set _second=%_second:~-2%\n:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%\n\n:: Set date/time in ISO 8601 format:\n Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%\n:: -> http://google.com/search?num=100&q=ISO+8601+format\n\nif 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am\nif 1%_hour% LSS 112 goto _skip_12_\n set /a _hour=1%_hour%-12\n set _hour=%_hour:~-2%\n set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm\n :: -> https://ss64.com/nt/if.html\n :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows\n :: 'if () else ()' will NOT set %_now% correctly !?\n:_skip_12_\n\nEndLocal & set _isotime=%_isotime% & set _now=%_now%\ngoto _out\n\n:_WMIC_MISSING_\necho.\necho WMIC.exe command not available\necho - WMIC.exe needs Administrator privileges to run in Windows\necho - Usually the path to WMIC.exe is \"%windir%\\System32\\wbem\\WMIC.exe\"\n\n:_help\necho.\necho GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format\necho.\necho %%_now%% environment variable set to current date and time\necho %%_isotime%% environment variable to current time in ISO format\necho set _today=%%_isotime:~0,10%%\necho.\n\n:_out\n:: EOF: GetDate.cmd\n"
},
{
"answer_id": 53649000,
"author": "Ed999",
"author_id": 1863462,
"author_profile": "https://Stackoverflow.com/users/1863462",
"pm_score": -1,
"selected": false,
"text": "FOR /F \"tokens=1-3 delims=/\" %%A IN (\"%date%\") DO (SET today=%%C-%%B-%%A)\necho %today%\n"
},
{
"answer_id": 62874781,
"author": "Gerhard",
"author_id": 7818749,
"author_profile": "https://Stackoverflow.com/users/7818749",
"pm_score": 2,
"selected": false,
"text": "Powershell @echo off\nfor /f \"tokens=1-6 delims=-\" %%a in ('PowerShell -Command \"& {Get-Date -format \"yyyy-MM-dd-HH-mm-ss\"}\"') do (\n echo year: %%a\n echo month: %%b\n echo day: %%c\n echo hour: %%d\n echo minute: %%e\n echo second: %%f\n)\n MMM MMMM hh HH"
},
{
"answer_id": 65943831,
"author": "om-ha",
"author_id": 10830091,
"author_profile": "https://Stackoverflow.com/users/10830091",
"pm_score": 0,
"selected": false,
"text": "date.exe date_unxutils.exe bin :: Add binaries to temp path\nIF EXIST bin SET PATH=%PATH%;bin\n\n:: Create UTC Timestamp string in a custom format\n:: Example: 20210128172058\nset timestamp_command='date_unxutils.exe -u +\"%%Y%%m%%d%%H%%M%%S\"'\nFOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i\necho %timestamp%\n"
},
{
"answer_id": 69833816,
"author": "Brendan Harris",
"author_id": 9688181,
"author_profile": "https://Stackoverflow.com/users/9688181",
"pm_score": 0,
"selected": false,
"text": "[int] $day = Get-Date -UFormat %d\n[int] $month = Get-Date -UFormat %m\n[int] $year = Get-Date -UFormat %y\n[String] $date = \"$($day)$($month)$($year)\"\n$time = Get-Date -UFormat %R\n$time -replace ‘[:]’,”\"\n$fileFolderName = $date + time\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] |
203,096
|
<p>I created an Interop user control in VS2005. When the user control is shown inside VB6, it does not pickup/use the XP styles (The buttons and the tabs look like VB6 buttons/tabs). </p>
<p>How do I get the XP styles to work with my control while it is in VB6?</p>
|
[
{
"answer_id": 203099,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 3,
"selected": false,
"text": "::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like \"backup_04.15.08.7z\")\nSET DT=%date%\nSET DT=%DT:/=.%\nSET DT=%DT:-=.%\n"
},
{
"answer_id": 203108,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 4,
"selected": false,
"text": "FOR /F \"TOKENS=1* DELIMS= \" %%A IN ('DATE/T') DO SET CDATE=%%B\nFOR /F \"TOKENS=1,2 eol=/ DELIMS=/ \" %%A IN ('DATE/T') DO SET mm=%%B\nFOR /F \"TOKENS=1,2 DELIMS=/ eol=/\" %%A IN ('echo %CDATE%') DO SET dd=%%B\nFOR /F \"TOKENS=2,3 DELIMS=/ \" %%A IN ('echo %CDATE%') DO SET yyyy=%%B\nSET date=%mm%%dd%%yyyy%\n"
},
{
"answer_id": 203115,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 4,
"selected": false,
"text": "@For /F \"tokens=2,3,4 delims=/ \" %%A in ('Date /t') do @( \n Set Month=%%A\n Set Day=%%B\n Set Year=%%C\n)\n\n@echo DAY = %Day%\n@echo Month = %Month%\n@echo Year = %Year%\n"
},
{
"answer_id": 203116,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 11,
"selected": true,
"text": "@echo off\nFor /f \"tokens=2-4 delims=/ \" %%a in ('date /t') do (set mydate=%%c-%%a-%%b)\nFor /f \"tokens=1-2 delims=/:\" %%a in ('time /t') do (set mytime=%%a%%b)\necho %mydate%_%mytime%\n For /f \"tokens=1-2 delims=/:\" %%a in (\"%TIME%\") do (set mytime=%%a%%b)\n @echo off\nfor /F \"usebackq tokens=1,2 delims==\" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j\nset ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%\necho Local date is [%ldt%]\n"
},
{
"answer_id": 203127,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": "set hour=%time:~0,2%\nif \"%time:~0,1%\"==\" \" set hour=0%time:~1,1%\nset _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%\n"
},
{
"answer_id": 741748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%\n"
},
{
"answer_id": 1849224,
"author": "DigiP",
"author_id": 225031,
"author_profile": "https://Stackoverflow.com/users/225031",
"pm_score": 4,
"selected": false,
"text": "\"d:\\Program Files\\7-Zip\\7z.exe\" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip\n"
},
{
"answer_id": 1951681,
"author": "Uri Liebeskind",
"author_id": 237474,
"author_profile": "https://Stackoverflow.com/users/237474",
"pm_score": 7,
"selected": false,
"text": "%DATE% dir date.exe date.exe +\"%Y-%m-%d\" date.exe +\"%T\" date.exe +\"%Y%m%d %H%M%S: Any text\" date.exe +\"Text: %y/%m/%d-any text-%H.%M\" Command: date.exe +\"%m-%d \"\"\"%H %M %S \"\"\"\" date.exe -r c:\\file.txt +\"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S\" for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n\n for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe +\"%%y-%%m-%%d %%H:%%M:%%S\"') do set timestamp=%%i\n for /f \"tokens=1,2,3,4,5,6* delims=,\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y,%%m,%%d,%%H,%%M,%%S\"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n\n for /f \"tokens=*\" %%i in ('C:\\Tools\\etc\\date.exe -r file.txt +\"%%y-%%m-%%d.%%H%%M%%S\"') do ren file.txt file.%%i.txt\n date.exe date"
},
{
"answer_id": 2854857,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 4,
"selected": false,
"text": " :: Start - Run , type:\n cmd /c \"powershell get-date -format ^\"{yyyy-MM-dd HH:mm:ss}^\"|clip\"\n\n :: click into target media, Ctrl + V to paste the result \n @echo off\n :: START USAGE ==================================================================\n ::SET THE NICETIME \n :: SET NICETIME=BOO\n :: CALL GetNiceTime.cmd \n\n :: ECHO NICETIME IS %NICETIME%\n\n :: echo nice time is %NICETIME%\n :: END USAGE ==================================================================\n\n echo set hhmmsss\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=:\" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c \n ::DEBUG ECHO hhmmsss IS %hhmmsss%\n ::DEBUG PAUSE\n echo %yyyymmdd%\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=.\" %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D\n ::DEBUG ECHO yyyymmdd IS %yyyymmdd%\n ::DEBUG PAUSE\n\n\n set NICETIME=%yyyymmdd%_%hhmmsss%\n ::DEBUG echo THE NICETIME IS %NICETIME%\n\n ::DEBUG PAUSE\n"
},
{
"answer_id": 3202796,
"author": "vMax",
"author_id": 386539,
"author_profile": "https://Stackoverflow.com/users/386539",
"pm_score": 6,
"selected": false,
"text": "-----------8<------8<------------ snip -- snip ----------8<-------------\n :: Works on any NT/2k machine independent of regional date settings\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set '%%c'=%%k))\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'% \n ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n\n :EOF\n-----------8<------8<------------ snip -- snip ----------8<-------------\n"
},
{
"answer_id": 3859042,
"author": "Matthew Johnson",
"author_id": 466219,
"author_profile": "https://Stackoverflow.com/users/466219",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %a in ('%date% %time%') do echo %c-%a-%b %d%e\n"
},
{
"answer_id": 4061880,
"author": "Sally",
"author_id": 478885,
"author_profile": "https://Stackoverflow.com/users/478885",
"pm_score": 2,
"selected": false,
"text": "DateFormat.exe --h"
},
{
"answer_id": 4584577,
"author": "Jeroen Wiert Pluimers",
"author_id": 29290,
"author_profile": "https://Stackoverflow.com/users/29290",
"pm_score": 3,
"selected": false,
"text": "%date% date/t date echo:^|date date/t C:\\temp>set-date-cmd.bat\nToday is Year: [2011] Month: [01] Day: [03]\n20110103\n :: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional date settings\n::\n:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale\n:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'\n:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date\n:: set '%%c'=%%k\n:: set 'yy'=%%k\n::\n:: In addition, date will display the current date before the input prompt using dashes\n:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch\n:: and one occurence in English.\n:: This skips the first iteration:\n:: if \"%%a\" GEQ \"A\"\n::\n:: echo:^|date\n:: Huidige datum: ma 03-01-2011\n:: Voer de nieuwe datum in: (dd-mm-jj)\n:: The current date is: Mon 01/03/2011\n:: Enter the new date: (mm-dd-yy)\n::\n:: date/t\n:: ma 03-01-2011\n:: Mon 01/03/2011\n::\n:: The assumption in this batch-file is that echo:^|date will return the date format\n:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.\n::\n:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.\n:: That will resolve the order of the tokens.\n::\n@ECHO off\n set v_day=\n set v_month=\n set v_year=\n\n SETLOCAL ENABLEEXTENSIONS\n if \"%date%A\" LSS \"A\" (set toks=1-3) else (set toks=2-4)\n::DEBUG echo toks=%toks%\n for /f \"tokens=2-4 delims=(-)\" %%a in ('echo:^|date') do (\n::DEBUG echo first token=%%a\n if \"%%a\" GEQ \"A\" (\n for /f \"tokens=%toks% delims=.-/ \" %%i in ('date/t') do (\n set '%%a'=%%i\n set '%%b'=%%j\n set 'yy'=%%k\n )\n )\n )\n if %'yy'% LSS 100 set 'yy'=20%'yy'%\n set Today=%'yy'%-%'mm'%-%'dd'%\n\n ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%\n\n ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]\n set datestring=%V_Year%%V_Month%%V_Day%\n echo %datestring%\n\n :EOF\n"
},
{
"answer_id": 4584820,
"author": "Jeroen Wiert Pluimers",
"author_id": 29290,
"author_profile": "https://Stackoverflow.com/users/29290",
"pm_score": 3,
"selected": false,
"text": ":: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi\n:: Works on any NT/2k machine independent of regional time settings\n::\n:: Gets the time in ISO 8601 24-hour format\n::\n:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.\n:: Since ISO 8601 does not care about AM/PM, we use %time%\n::\n @ECHO off\n SETLOCAL ENABLEEXTENSIONS\n for /f \"tokens=1-4 delims=:,.-/ \" %%i in ('echo %time%') do (\n set 'hh'=%%i\n set 'mm'=%%j\n set 'ss'=%%k\n set 'ff'=%%l)\n ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%\n\n ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]\n set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%\n echo %timestring%\n\n :EOF\n"
},
{
"answer_id": 6348634,
"author": "KChiki",
"author_id": 798300,
"author_profile": "https://Stackoverflow.com/users/798300",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=1-5 delims=/ \" %%d in (\"%date%\") do rename \"decrypted.txt\" %%g-%%e-%%f.txt\n"
},
{
"answer_id": 6707326,
"author": "sudipto roy",
"author_id": 846495,
"author_profile": "https://Stackoverflow.com/users/846495",
"pm_score": 5,
"selected": false,
"text": "echo %Date:~0,3%day\n"
},
{
"answer_id": 7319693,
"author": "V15I0N",
"author_id": 930610,
"author_profile": "https://Stackoverflow.com/users/930610",
"pm_score": 2,
"selected": false,
"text": "rem save the existing format definition\nfor /f \"skip=2 tokens=3\" %%a in ('reg query \"HKCU\\Control Panel\\International\" /v sShortDate') do set FORMAT=%%a\nrem set ISO specific format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:\nrem query the date in the ISO specific format \nset ISODATE=%DATE%\nrem restore previous format definition\nreg add \"HKCU\\Control Panel\\International\" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:\n"
},
{
"answer_id": 16264795,
"author": "John Langstaff",
"author_id": 714326,
"author_profile": "https://Stackoverflow.com/users/714326",
"pm_score": 3,
"selected": false,
"text": "for /f \"tokens=2,3,4,5,6 usebackq delims=:/ \" %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e\n"
},
{
"answer_id": 19799236,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 7,
"selected": false,
"text": "@echo off\npushd \"%temp%\"\nmakecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul\nfor /f \"tokens=3-7\" %%a in ('find /i \"makecab\"^<~.rpt') do (\n set \"current-date=%%e-%%b-%%c\"\n set \"current-time=%%d\"\n set \"weekday=%%a\"\n)\ndel ~.*\npopd\necho %weekday% %current-date% %current-time%\npause\n @echo off\nsetlocal\nfor /f \"skip=8 tokens=2,3,4,5,6,7,8 delims=: \" %%D in ('robocopy /l * \\ \\ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (\n set \"dow=%%D\"\n set \"month=%%E\"\n set \"day=%%F\"\n set \"HH=%%G\"\n set \"MM=%%H\"\n set \"SS=%%I\"\n set \"year=%%J\"\n)\n\necho Day of the week: %dow%\necho Day of the month : %day%\necho Month : %month%\necho hour : %HH%\necho minutes : %MM%\necho seconds : %SS%\necho year : %year%\nendlocal\n .bat @if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment\n\n@echo off\ncscript //E:JScript //nologo \"%~f0\"\nexit /b 0\n*------------------------------------------------------------------------------*/\n\nfunction GetCurrentDate() {\n // Today date time which will used to set as default date.\n var todayDate = new Date();\n todayDate = todayDate.getFullYear() + \"-\" +\n (\"0\" + (todayDate.getMonth() + 1)).slice(-2) + \"-\" +\n (\"0\" + todayDate.getDate()).slice(-2) + \" \" + (\"0\" + todayDate.getHours()).slice(-2) + \":\" +\n (\"0\" + todayDate.getMinutes()).slice(-2);\n\n return todayDate;\n }\n\nWScript.Echo(GetCurrentDate());\n :sub echo(str) :end sub\necho off\n'>nul 2>&1|| copy /Y %windir%\\System32\\doskey.exe %windir%\\System32\\'.exe >nul\n'& echo current date:\n'& cscript /nologo /E:vbscript \"%~f0\"\n'& exit /b\n\n'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.\n'1 = vbLongDate - Returns date: weekday, monthname, year\n'2 = vbShortDate - Returns date: mm/dd/yy\n'3 = vbLongTime - Returns time: hh:mm:ss PM/AM\n'4 = vbShortTime - Return time: hh:mm\n\nWScript.echo Replace(FormatDateTime(Date,1),\", \",\"-\")\n C:\\> powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"\n for /f \"delims=\" %%# in ('powershell get-date -format \"{dd-MMM-yyyy HH:mm}\"') do @set _date=%%#\n @if (@X)==(@Y) @end /****** silent line that start JScript comment ******\n\n@echo off\n::::::::::::::::::::::::::::::::::::\n::: Compile the script ::::\n::::::::::::::::::::::::::::::::::::\nsetlocal\nif exist \"%~n0.exe\" goto :skip_compilation\n\nset \"frm=%SystemRoot%\\Microsoft.NET\\Framework\\\"\n\n:: Searching the latest installed .NET framework\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\v*\"') do (\n if exist \"%%v\\jsc.exe\" (\n rem :: the javascript.net compiler\n set \"jsc=%%~dpsnfxv\\jsc.exe\"\n goto :break_loop\n )\n)\necho jsc.exe not found && exit /b 0\n:break_loop\n\n\ncall %jsc% /nologo /out:\"%~n0.exe\" \"%~dpsfnx0\"\n::::::::::::::::::::::::::::::::::::\n::: End of compilation ::::\n::::::::::::::::::::::::::::::::::::\n:skip_compilation\n\n\"%~n0.exe\"\n\nexit /b 0\n\n\n****** End of JScript comment ******/\nimport System;\nimport System.IO;\n\nvar dt=DateTime.Now;\nConsole.WriteLine(dt.ToString(\"yyyy-MM-dd hh:mm:ss\"));\n @echo off\nsetlocal\ndel /q /f %temp%\\timestampfile_*\n\nLogman.exe stop ts-CPU 1>nul 2>&1\nLogman.exe delete ts-CPU 1>nul 2>&1\n\nLogman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c \"\\Processor(_Total)\\%% Processor Time\" -o %temp%\\timestampfile_ >nul\nLogman.exe start ts-CPU 1>nul 2>&1\n\nLogman.exe stop ts-CPU >nul 2>&1\nLogman.exe delete ts-CPU >nul 2>&1\nfor /f \"tokens=2 delims=_.\" %%t in ('dir /b %temp%\\timestampfile_*^&del /q/f %temp%\\timestampfile_*') do set timestamp=%%t\n\necho %timestamp%\necho MM: %timestamp:~0,2%\necho dd: %timestamp:~2,2%\necho hh: %timestamp:~4,2%\necho mm: %timestamp:~6,2%\n\nendlocal\nexit /b 0\n for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in (\"%%#\") do @set %%@\necho %day%\necho %DayOfWeek%\necho %hour%\necho %minute%\necho %month%\necho %quarter%\necho %second%\necho %weekinmonth%\necho %year%\n @echo off\nsetlocal\n\n:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance\n::if defined USERDOMAIN_roamingprofile (set \"v=v4\") else (set \"v=\")\n\nfor /f \"tokens=4 delims=. \" %%# in ('ver') do if %%# GTR 5 (set \"v=v4\") else (\"v=\")\nset \"mon=\"\nfor /f \"skip=2 delims=,\" %%# in ('typeperf \"\\UDP%v%\\*\" -si 0 -sc 1') do (\n if not defined mon (\n for /f \"tokens=1-7 delims=.:/ \" %%a in (%%#) do (\n set mon=%%a\n set date=%%b\n set year=%%c\n set hour=%%d\n set minute=%%e\n set sec=%%f\n set ms=%%g\n )\n )\n)\necho %year%.%mon%.%date%\necho %hour%:%minute%:%sec%.%ms%\nendlocal\n <!-- : Batch portion\n\n@echo off\nsetlocal\n\nfor /f \"delims=\" %%I in ('mshta \"%~f0\"') do set \"now.%%~I\"\n\nrem Display all variables beginning with \"now.\"\nset now.\n\ngoto :EOF\n\nend batch / begin HTA -->\n\n<script>\n resizeTo(0,0)\n var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),\n now = new Date(),\n props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',\n 'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',\n 'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',\n 'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',\n 'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],\n output = [];\n\n for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}\n close(fso.Write(output.join('\\n')));\n</script>\n"
},
{
"answer_id": 21282321,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "wmic :Now -- Gets the current date and time into separate variables\n:: %~1: [out] Year\n:: %~2: [out] Month\n:: %~3: [out] Day\n:: %~4: [out] Hour\n:: %~5: [out] Minute\n:: %~6: [out] Second\n setlocal\n for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t\n endlocal & (\n if \"%~1\" neq \"\" set %~1=%T:~0,4%\n if \"%~2\" neq \"\" set %~2=%T:~4,2%\n if \"%~3\" neq \"\" set %~3=%T:~6,2%\n if \"%~4\" neq \"\" set %~4=%T:~8,2%\n if \"%~5\" neq \"\" set %~5=%T:~10,2%\n if \"%~6\" neq \"\" set %~6=%T:~12,2%\n )\ngoto:eof\n call:Now Y M D H N S\necho %Y%-%M%-%D% %H%:%N%:%S%\n 2014-01-22 12:51:53\n call:Now Y M"
},
{
"answer_id": 25714111,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 5,
"selected": false,
"text": "@echo off\nfor /f \"tokens=2 delims==\" %%a in ('wmic OS Get localdatetime /value') do set \"dt=%%a\"\nset \"YY=%dt:~2,2%\" & set \"YYYY=%dt:~0,4%\" & set \"MM=%dt:~4,2%\" & set \"DD=%dt:~6,2%\"\nset \"HH=%dt:~8,2%\" & set \"Min=%dt:~10,2%\" & set \"Sec=%dt:~12,2%\"\n\nset \"datestamp=%YYYY%%MM%%DD%\" & set \"timestamp=%HH%%Min%%Sec%\" & set \"fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%\"\necho datestamp: \"%datestamp%\"\necho timestamp: \"%timestamp%\"\necho fullstamp: \"%fullstamp%\"\npause\n"
},
{
"answer_id": 27012486,
"author": "gdelfino",
"author_id": 93947,
"author_profile": "https://Stackoverflow.com/users/93947",
"pm_score": 3,
"selected": false,
"text": "PowerShell -Command \"get-date\"\n"
},
{
"answer_id": 38905219,
"author": "bvj",
"author_id": 241296,
"author_profile": "https://Stackoverflow.com/users/241296",
"pm_score": -1,
"selected": false,
"text": "ECHOTIMESTAMP DTS @ECHO off\n\nCALL :ECHOTIMESTAMP\nGOTO END\n\n:TIMESTAMP\nSETLOCAL EnableDelayedExpansion\n SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!\n SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!\n SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!\nENDLOCAL & SET \"%~1=%DTS%\"\nGOTO :EOF\n\n:ECHOTIMESTAMP\nSETLOCAL\n CALL :TIMESTAMP DTS\n ECHO %DTS%\nENDLOCAL\nGOTO :EOF\n\n:END\n\nEXIT /b 0\n"
},
{
"answer_id": 38958529,
"author": "NotepadPlusPlus PRO",
"author_id": 2920692,
"author_profile": "https://Stackoverflow.com/users/2920692",
"pm_score": -1,
"selected": false,
"text": ":: Check your local date format\necho %date%\n\n :: Output is Mon 08/15/2016\n\n:: get day (start index, number of characters)\n:: (index starts with zero)\nset myday=%DATE:~0,4%\necho %myday%\n :: output is Mon \n\n:: get month\nset mymonth=%DATE:~4,2%\necho %mymonth%\n :: output is 08\n\n:: get date \nset mydate=%DATE:~7,2% \necho %mydate%\n :: output is 15\n\n:: get year\nset myyear=%DATE:~10,4%\necho %myyear%\n :: output is 2016\n"
},
{
"answer_id": 38972828,
"author": "Frizz1977",
"author_id": 1794049,
"author_profile": "https://Stackoverflow.com/users/1794049",
"pm_score": -1,
"selected": false,
"text": "SET DATE=%date%\nSET YEAR=%DATE:~0,4%\nSET MONTH=%DATE:~5,2%\nSET DAY=%DATE:~8,2%\nECHO %YEAR%\nECHO %MONTH%\nECHO %DAY%\n\nSET DATE_FRM=%YEAR%-%MONTH%-%DAY% \nECHO %DATE_FRM%\n"
},
{
"answer_id": 43903620,
"author": "Adolfo",
"author_id": 3075331,
"author_profile": "https://Stackoverflow.com/users/3075331",
"pm_score": 2,
"selected": false,
"text": ":: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format\n:: - Sets environment variables %_isotime% and %_now% to current time\n:: - On failure, clears these environment variables\n:: Inspired on -> https://ss64.com/nt/syntax-getdate.html\n:: - (cX) 2017 adolfo.dimare@gmail.com\n:: - http://stackoverflow.com/questions/203090\n@echo off\n\nset _isotime=\nset _now=\n\n:: Check that WMIC.exe is available\nWMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_\n\nif not (%1)==() goto _help\nSetLocal EnableDelayedExpansion\n\n:: Use WMIC.exe to retrieve date and time\nFOR /F \"skip=1 tokens=1-6\" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (\n IF \"%%~L\"==\"\" goto _WMIC_done_\n set _yyyy=%%L\n set _mm=00%%J\n set _dd=00%%G\n set _hour=00%%H\n set _minute=00%%I\n set _second=00%%K\n)\n:_WMIC_done_\n\n:: 1 2 3 4 5 6\n:: %%G %%H %%I %%J %%K %%L\n:: Day Hour Minute Month Second Year\n:: 27 9 35 4 38 2017\n\n:: Remove excess leading zeroes\n set _mm=%_mm:~-2%\n set _dd=%_dd:~-2%\n set _hour=%_hour:~-2%\n set _minute=%_minute:~-2%\n set _second=%_second:~-2%\n:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%\n\n:: Set date/time in ISO 8601 format:\n Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%\n:: -> http://google.com/search?num=100&q=ISO+8601+format\n\nif 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am\nif 1%_hour% LSS 112 goto _skip_12_\n set /a _hour=1%_hour%-12\n set _hour=%_hour:~-2%\n set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm\n :: -> https://ss64.com/nt/if.html\n :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows\n :: 'if () else ()' will NOT set %_now% correctly !?\n:_skip_12_\n\nEndLocal & set _isotime=%_isotime% & set _now=%_now%\ngoto _out\n\n:_WMIC_MISSING_\necho.\necho WMIC.exe command not available\necho - WMIC.exe needs Administrator privileges to run in Windows\necho - Usually the path to WMIC.exe is \"%windir%\\System32\\wbem\\WMIC.exe\"\n\n:_help\necho.\necho GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format\necho.\necho %%_now%% environment variable set to current date and time\necho %%_isotime%% environment variable to current time in ISO format\necho set _today=%%_isotime:~0,10%%\necho.\n\n:_out\n:: EOF: GetDate.cmd\n"
},
{
"answer_id": 53649000,
"author": "Ed999",
"author_id": 1863462,
"author_profile": "https://Stackoverflow.com/users/1863462",
"pm_score": -1,
"selected": false,
"text": "FOR /F \"tokens=1-3 delims=/\" %%A IN (\"%date%\") DO (SET today=%%C-%%B-%%A)\necho %today%\n"
},
{
"answer_id": 62874781,
"author": "Gerhard",
"author_id": 7818749,
"author_profile": "https://Stackoverflow.com/users/7818749",
"pm_score": 2,
"selected": false,
"text": "Powershell @echo off\nfor /f \"tokens=1-6 delims=-\" %%a in ('PowerShell -Command \"& {Get-Date -format \"yyyy-MM-dd-HH-mm-ss\"}\"') do (\n echo year: %%a\n echo month: %%b\n echo day: %%c\n echo hour: %%d\n echo minute: %%e\n echo second: %%f\n)\n MMM MMMM hh HH"
},
{
"answer_id": 65943831,
"author": "om-ha",
"author_id": 10830091,
"author_profile": "https://Stackoverflow.com/users/10830091",
"pm_score": 0,
"selected": false,
"text": "date.exe date_unxutils.exe bin :: Add binaries to temp path\nIF EXIST bin SET PATH=%PATH%;bin\n\n:: Create UTC Timestamp string in a custom format\n:: Example: 20210128172058\nset timestamp_command='date_unxutils.exe -u +\"%%Y%%m%%d%%H%%M%%S\"'\nFOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i\necho %timestamp%\n"
},
{
"answer_id": 69833816,
"author": "Brendan Harris",
"author_id": 9688181,
"author_profile": "https://Stackoverflow.com/users/9688181",
"pm_score": 0,
"selected": false,
"text": "[int] $day = Get-Date -UFormat %d\n[int] $month = Get-Date -UFormat %m\n[int] $year = Get-Date -UFormat %y\n[String] $date = \"$($day)$($month)$($year)\"\n$time = Get-Date -UFormat %R\n$time -replace ‘[:]’,”\"\n$fileFolderName = $date + time\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
203,113
|
<p>I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.</p>
<p>Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.</p>
<p>I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?</p>
<p>EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.</p>
<p>Here is my code (Rev 2.0, now with optional callbacks):</p>
<pre><code>function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
</code></pre>
<p>and in the method with a dependency:</p>
<pre><code>var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
calbackMethod();
</code></pre>
<p>Any suggestions?</p>
|
[
{
"answer_id": 203139,
"author": "abahgat",
"author_id": 27565,
"author_profile": "https://Stackoverflow.com/users/27565",
"pm_score": 2,
"selected": false,
"text": "$.getScript(url, callback)"
},
{
"answer_id": 204100,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 2,
"selected": false,
"text": "if (iNeedSomeMore){\n Script.load(\"myBigCodeLibrary.js\"); // includes code for myFancyMethod();\n myFancyMethod(); // cool, no need for callbacks!\n}\n var Script = {\n _loadedScripts: [],\n include: function(script){\n // include script only once\n if (this._loadedScripts.include(script)){\n return false;\n }\n // request file synchronous\n var code = new Ajax.Request(script, {\n asynchronous: false, method: \"GET\",\n evalJS: false, evalJSON: false\n }).transport.responseText;\n // eval code on global level\n if (Prototype.Browser.IE) {\n window.execScript(code);\n } else if (Prototype.Browser.WebKit){\n $$(\"head\").first().insert(Object.extend(\n new Element(\"script\", {type: \"text/javascript\"}), {text: code}\n ));\n } else {\n window.eval(code);\n }\n // remember included script\n this._loadedScripts.push(script);\n }\n};\n"
},
{
"answer_id": 15978307,
"author": "stamat",
"author_id": 1909864,
"author_profile": "https://Stackoverflow.com/users/1909864",
"pm_score": 0,
"selected": false,
"text": "// ----- USAGE -----\n\nrequire('ivar.util.string');\nrequire('ivar.net.*');\nrequire('ivar/util/array.js');\nrequire('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');\n\nready(function(){\n //do something when required scripts are loaded\n});\n\n //--------------------\n\nvar _rmod = _rmod || {}; //require module namespace\n_rmod.LOADED = false;\n_rmod.on_ready_fn_stack = [];\n_rmod.libpath = '';\n_rmod.imported = {};\n_rmod.loading = {\n scripts: {},\n length: 0\n};\n\n_rmod.findScriptPath = function(script_name) {\n var script_elems = document.getElementsByTagName('script');\n for (var i = 0; i < script_elems.length; i++) {\n if (script_elems[i].src.endsWith(script_name)) {\n var href = window.location.href;\n href = href.substring(0, href.lastIndexOf('/'));\n var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);\n return url.substring(href.length+1, url.length);\n }\n }\n return '';\n};\n\n_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library\n\n\n_rmod.injectScript = function(script_name, uri, callback, prepare) {\n\n if(!prepare)\n prepare(script_name, uri);\n\n var script_elem = document.createElement('script');\n script_elem.type = 'text/javascript';\n script_elem.title = script_name;\n script_elem.src = uri;\n script_elem.async = true;\n script_elem.defer = false;\n\n if(!callback)\n script_elem.onload = function() {\n callback(script_name, uri);\n };\n\n document.getElementsByTagName('head')[0].appendChild(script_elem);\n};\n\n_rmod.requirePrepare = function(script_name, uri) {\n _rmod.loading.scripts[script_name] = uri;\n _rmod.loading.length++;\n};\n\n_rmod.requireCallback = function(script_name, uri) {\n _rmod.loading.length--;\n delete _rmod.loading.scripts[script_name];\n _rmod.imported[script_name] = uri;\n\n if(_rmod.loading.length == 0)\n _rmod.onReady();\n};\n\n_rmod.onReady = function() {\n if (!_rmod.LOADED) {\n for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){\n _rmod.on_ready_fn_stack[i]();\n });\n _rmod.LOADED = true;\n }\n};\n\n_.rmod = namespaceToUri = function(script_name, url) {\n var np = script_name.split('.');\n if (np.getLast() === '*') {\n np.pop();\n np.push('_all');\n }\n\n if(!url)\n url = '';\n\n script_name = np.join('.');\n return url + np.join('/')+'.js';\n};\n\n//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.\nvar require = function(script_name) {\n var uri = '';\n if (script_name.indexOf('/') > -1) {\n uri = script_name;\n var lastSlash = uri.lastIndexOf('/');\n script_name = uri.substring(lastSlash+1, uri.length);\n } else {\n uri = _rmod.namespaceToUri(script_name, ivar._private.libpath);\n }\n\n if (!_rmod.loading.scripts.hasOwnProperty(script_name) \n && !_rmod.imported.hasOwnProperty(script_name)) {\n _rmod.injectScript(script_name, uri, \n _rmod.requireCallback, \n _rmod.requirePrepare);\n }\n};\n\nvar ready = function(fn) {\n _rmod.on_ready_fn_stack.push(fn);\n};\n"
},
{
"answer_id": 18819017,
"author": "Aditya M P",
"author_id": 443219,
"author_profile": "https://Stackoverflow.com/users/443219",
"pm_score": 0,
"selected": false,
"text": "fileUsedOccasionally.js"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
203,126
|
<p>Here is an example of polymorphism from <a href="http://www.cplusplus.com/doc/tutorial/polymorphism.html" rel="noreferrer">http://www.cplusplus.com/doc/tutorial/polymorphism.html</a> (edited for readability):</p>
<pre><code>// abstract base class
#include <iostream>
using namespace std;
class Polygon {
protected:
int width;
int height;
public:
void set_values(int a, int b) { width = a; height = b; }
virtual int area(void) =0;
};
class Rectangle: public Polygon {
public:
int area(void) { return width * height; }
};
class Triangle: public Polygon {
public:
int area(void) { return width * height / 2; }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << endl; // outputs 20
cout << ppoly2->area() << endl; // outputs 10
return 0;
}
</code></pre>
<p>My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon * ppoly1 = ▭" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this?</p>
<pre><code>cout << ((Polygon *)0x12345678)->area() << endl;
</code></pre>
<p>Assuming that you're allowed to access that random area of memory.</p>
<p>I would test this out but I can't on the computer I'm on at the moment.</p>
<p>(I hope I'm not missing something obvious...)</p>
|
[
{
"answer_id": 203136,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "vptr vtbl vtbl vptr vtbl Polygon Rectangle Triangle vtbl area ppoly1 vptr Rectangle vtbl ppoly2 Triangle vtbl"
},
{
"answer_id": 203167,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "cout << ((Polygon *)0x12345678)->area() << endl;\n Polygon *obj = dynamic_cast<Polygon *>(0x12345678)->area();\nASSERT(obj != NULL);\n\ncout << obj->area() << endl;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
203,147
|
<p>Here's another C#/.NET question based merely on curiousity more than an immediate <em>need</em> ...</p>
<p>If you had a <code>Socket</code> instance and you wanted to wrap it in the higher-level <code>TcpClient</code> class, is that possible and how would you do it?</p>
<p>Conversely if you have an instance of <code>TcpClient</code>, is it possible to get the underlying <code>Socket</code>?</p>
|
[
{
"answer_id": 203153,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 2,
"selected": false,
"text": "tcpClientInstance.Client"
},
{
"answer_id": 203160,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 6,
"selected": true,
"text": "Socket socket = ...;\nTcpClient client = new TcpClient();\nclient.Client = socket;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
203,151
|
<p>I have a report that uses a TChart that I am maintaining. One of the TLineSeries that gets added automatically gets assigned the color clWhite, which is too close to the background (clBtnFace). </p>
<p>If I change it, then the next series that gets added takes clWhite. So short of going back and changing it after all the other series are created, is there some way to tell the TChart that I don't want any of my series to be clWhite?</p>
<p>When a series is added to the TChart the TChart assigns it a color. I want it to not assign clWhite.</p>
|
[
{
"answer_id": 203236,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 2,
"selected": false,
"text": "procedure TForm1.setColors(aChart: TChart; aColorArray: array of TColor);\nvar\n chi : Integer;\n coi : Integer;\nbegin\n coi := low(aColorArray);\n for chi := 0 to aChart.SeriesList.Count - 1 do begin\n aChart.SeriesList[chi].Color := aColorArray[coi];\n inc(coi);\n if coi > high(aColorArray) then\n coi := low(aColorArray);\n end;\nend;\n\nprocedure TForm1.FormShow(Sender: TObject);\nvar\n ca : array of TColor;\nbegin\n setLength(ca, 3);\n ca[0] := clRed;\n ca[1] := clBlue;\n ca[2] := clGreen;\n setColors(Chart1, ca);\nend;\n"
},
{
"answer_id": 203365,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 4,
"selected": true,
"text": "SetDefaultColorPalette; // Make sure we start with the default\nColorPalette[4] := $007FFF; // Change White to Orange\ntry\n // add series to the chart\nfinally\n SetDefaultColorPalette; // Set it back to Default\nend;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255/"
] |
203,161
|
<p>Im just writing a small Ajax framework for re-usability in small projects and i've hit a problem. Basically i get a '<code>NS_ERROR_ILLEGAL_VALUE</code>' error while sending the request and i've no idea what is happening.</p>
<p>The HTML Page
(trimmed but shows the error)</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var COMPLETE = 4;
var OK = 200;
function GetXMLHttpRequestObject()
{
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest)
{
if(typeof XMLHttpRequest != 'undefined')
{
try
{
XMLHttpRequestObject = new XMLHttpRequest();
}
catch (e)
{
XMLHttpRequestObject = false;
}
}
}
else if (window.ActiveXObject)
{
try
{
XMLHttpRequestObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try
{
XMLHttpRequestObject = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e)
{
XMLHttpRequestObject = false;
}
}
}
else
{
XMLHttpRequestObject = false;
}
return XMLHttpRequestObject;
}
//The Main Ajax Object
function AjaxRequest(p_RequestMethod, p_DestinationURL)
{
this.XMLHttpRequestObject = GetXMLHttpRequestObject();
this.RequestedMethod = p_RequestMethod;
this.DestinationURL = p_DestinationURL;
this.XMLHttpRequestObject.open(this.RequestMethod, this.DestinationURL);
this.OnStateChange = function(Callback)
{
this.XMLHttpRequestObject.onreadystatechange = Callback;
}
this.Send = function(p_Content)
{
this.XMLHttpRequestObject.send(p_Content);
}
this.GetState()
{
return this.XMLHttpRequestObject.readyState;
}
this.GetResponseText = function()
{
return this.XMLHttpRequestObject.responseText;
}
this.GetResponseStatus = function()
{
return this.XMLHttpRequestObject.status;
}
this.GetResponseStatusText = function()
{
return this.XMLHttpRequestObject.statusText;
}
}
var Request;
function GetData()
{
Request = new AjaxRequest('POST', 'http://www.kalekold.net/ajax/Ajax.php');
Request.OnStateChange = StateChange;
Request.Send();
}
function StateChange()
{
window.alert("State: " + Request.GetState());
window.alert("Response: " + Request.GetResponseStatus());
window.alert("Response Text: " + Request.GetResponseStatusText());
if(Request.GetState() == COMPLETE && Request.GetResponseStatus() == OK)
{
Result = Request.GetResponseText();
window.alert(Result);
}
}
</script>
</head>
<body>
<form>
<textarea name="TextArea" rows="10" cols="80"></textarea><br />
<input type="button" value="Load" onClick="GetData();">
</form>
</body>
</html>
</code></pre>
<p>The PHP File:</p>
<pre><code><?php
$XML = <<< PROLOG
<?xml version="1.0" encoding="iso-8859-1"?>
PROLOG;
$XML .= "<results>";
$XML .= "<result>";
$XML .= "<FirstName>Gary</FirstName>";
$XML .= "<SecondName>Willoughby</SecondName>";
$XML .= "<Age>35</Age>";
$XML .= "</result>";
$XML .= "<result>";
$XML .= "<FirstName>Sara</FirstName>";
$XML .= "<SecondName>Gostick</SecondName>";
$XML .= "<Age>35</Age>";
$XML .= "</result>";
$XML .= "</results>";
header("Content-Type: text/xml");
echo $XML;
?>
</code></pre>
<p>The full error:</p>
<pre><code>uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: http://www.kalekold.net/ajax/ :: AjaxRequest :: line 63" data: no]
Line 0
</code></pre>
<p>I just can't see where it's going wrong, any ideas?</p>
|
[
{
"answer_id": 204048,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "XMLHttpRequestObject.responseText XMLHttpRequestObject.status"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
203,171
|
<p>How can I include a bookmarklet in a Markdown parsed document? Is there any "tag" for markdown that basically says "don't parse this"??</p>
<p>For example you could have something like:</p>
<pre><code><a href="javascript:function my_bookmarklet()
{alert('Hello World');}
my_bookmarklet();">Hello</a>
</code></pre>
<p>But if I try to past the javascript from that into a link in markdown like this: </p>
<pre><code>[Hello World!](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();)
</code></pre>
<p>You get a messed up link, like below.</p>
<p>[Hello World!](javascript:function my_bookmarklet(){alert('Hello World');}my_bookmarklet();)</p>
<p>Is there anyway around this?</p>
<p>And no, I'm not trying to put malicious bookmarklets in SO or anything, but I want to use markdown for my site and would like to post some bookmarklets I wrote.</p>
<p>Edit: I thought I had the answer...but now it seems I don't quite have it.</p>
<p>This seems to work great in WMD and showdown, but in the Markdown.php editor, it does not. Anyone have experience with Markdown.php specifically?</p>
|
[
{
"answer_id": 203179,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 4,
"selected": true,
"text": "<a href=\"javascript:function my_bookmarklet()\n {alert('Hello World');}\n my_bookmarklet();\">Hello</a>\n [Hello](javascript:function my_bookmarklet(\\){alert('Hello World'\\);}my_bookmarklet(\\);)\n"
},
{
"answer_id": 8686841,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 3,
"selected": false,
"text": "[Hello World!][1]\n[1]:javascript:alert('Hello World')\n"
},
{
"answer_id": 49807294,
"author": "Michael S",
"author_id": 4904320,
"author_profile": "https://Stackoverflow.com/users/4904320",
"pm_score": 2,
"selected": false,
"text": " [Hello World](javascript:%28function%28%29%7Balert%28%22Hello%20World%22%29%7D%29%28%29%3B)\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
203,172
|
<p>Doxygen is a bit slow - it takes about a couple of minutes to process my whole project, so for small incremental changes this is longer than actually building the rest of my code. There are thousands of files without any documentation so I guess it is spending most of its time processing them. Is there any way to get it to skip files without any documentation?</p>
<p>What about getting it to only process changed files?</p>
|
[
{
"answer_id": 672043,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "SEARCH_INCLUDES"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
203,174
|
<p>I have a new app I'll be working on where I have to generate a Word document that contains tables, graphs, a table of contents and text. What's a good API to use for this? How sure are you that it supports graphs, ToCs, and tables? What are some hidden gotcha's in using them?</p>
<p>Some clarifications:</p>
<ul>
<li>I can't output a PDF, they want a Word doc.</li>
<li>They're using MS Word 2003 (or 2007), not OpenOffice</li>
<li>Application is running on *nix app-server</li>
</ul>
<p>It'd be nice if I could start with a template doc and just fill in some spaces with tables, graphs, etc.</p>
<p>Edit: Several good answers below, each with their own faults as far as my current situation. Hard to pick a "final answer" from them. Think I'll leave it open, and hope for better solutions to be created.</p>
<p>Edit: The OpenOffice UNO project does seem to be closest to what I asked for. While POI is certainly more mainstream, it's too immature for what I want.</p>
|
[
{
"answer_id": 3332031,
"author": "Leonardo",
"author_id": 401906,
"author_profile": "https://Stackoverflow.com/users/401906",
"pm_score": 3,
"selected": false,
"text": "IDocument myDoc = new Document2004();\nmyDoc.getBody().addEle(new Heading1(\"Heading01\"));\nmyDoc.getBody().addEle(new Paragraph(\"This is a paragraph...\")\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824/"
] |
203,180
|
<p>Say I have my sources in my src/ tree (and possibly in my test/ tree). Say I would like to compile only <em>part</em> of that tree. The reasons why I might want to do that are various. Just as an example, I might want to create the smallest possible jar (without including certain classes), or I might want the fastest compile time for what I am compiling. I absolutely want to compile all the dependencies, though!</p>
<p>This can be easily achieved from the command line with:</p>
<pre><code>javac -d build/ -cp whatever -sourcepath src src/path/to/MyClass.java
</code></pre>
<p>Now, how can you do that with ant? The javac ant <a href="http://ant.apache.org/manual/Tasks/javac.html" rel="noreferrer">task compiles everything</a>:</p>
<blockquote>
<p>The source and destination directory
will be recursively scanned for Java
source files to compile.</p>
</blockquote>
<p>One can use the <code>excludes</code> and <code>includes</code> parameters, but they are problematic for this purpose. In fact, it seems that one has to explicitly setup all the <code>includes</code> (not automatic dependency lookup), and <strong>even worst</strong> that <a href="http://ant.apache.org/manual/dirtasks.html#patternset" rel="noreferrer">excludes has priority on includes</a>:</p>
<blockquote>
<p>When both inclusion and exclusion are
used, only files/directories that
match at least one of the include
patterns and don't match <em>any</em> of the
exclude patterns are used.</p>
</blockquote>
<p>Thus, you cannot use </p>
<pre><code><javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"
excludes="**/*.java" includes="src/path/to/MyClass.java" />
</code></pre>
<p>Because it will not compile anything :-(</p>
<p>Is there any way of achieving that simple command line <code>javac</code> with ant?</p>
<hr>
<p>EDITED: Thank you for your answer, Sadie, I'm accepting it, because it does work in the way I was wondering in this question. But I have a couple of comments (too long to be in the comment field of your answer):</p>
<p>1) I did read the documentation (see links above), but it's unclear that with just <code>includes</code> you are actually also excluding everything else</p>
<p>2) When you just <code>includes</code> ant logs something like</p>
<pre><code>[javac] Compiling 1 source file to /my/path/to/build
</code></pre>
<p>even if the dependencies make it compiling (much) more than just one source file.</p>
|
[
{
"answer_id": 203552,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": true,
"text": "<javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\"\n includes=\"src/path/to/MyClass.java\" />\n <javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\">\n <include name=\"src/path/to/MyClass.java\"/>\n <include name=\"src/path/to/AnotherClass.java\"/>\n</javac>\n <jar jarfile=\"${outlib}/something.jar\">\n <fileset dir=\"${build.dir}\">\n <include name='src/path/to/classes' />\n </fileset>\n</jar>\n"
},
{
"answer_id": 17261455,
"author": "Ankit",
"author_id": 2513729,
"author_profile": "https://Stackoverflow.com/users/2513729",
"pm_score": 0,
"selected": false,
"text": "<property name=\"includeFileList\" value=\"<name of java class>.java\"/>\n\n<javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\"\n target=\"1.6\" debug=\"true\" includes=\"${includeFileList}\"/>\n"
},
{
"answer_id": 31367984,
"author": "Tor P",
"author_id": 1218054,
"author_profile": "https://Stackoverflow.com/users/1218054",
"pm_score": 2,
"selected": false,
"text": "<javac> <fileset> <filename name=\"**/MyClass.java\"/> <javac srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"classpath\">\n <filename name=\"**/path/to/MyClass.java\"/>\n</javac>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] |
203,189
|
<p>I am intercepting Win32 API calls a native dll or exe is doing from C# using some kind of hooking. In this particular case I am interested in DrawText() in user32.dll. It is declared like this in Win32 API:</p>
<pre><code>INT WINAPI DrawTextW(HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags)
</code></pre>
<p>The LPRECT struct has the following signature (also in Win32 API):</p>
<pre><code>typedef struct tagRECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT LPRECT;
</code></pre>
<p>LONG is a typedef for 32bit integers on 32bit systems (don't know about 64bit systems, it is irrelevant at this point because I am on 32bit Windows). To be able to access the members of this struct I declared it in my C# code...</p>
<pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RECT
{
public Int32 left;
public Int32 top;
public Int32 right;
public Int32 bottom;
}
</code></pre>
<p>... and wrote the signature of P/Invoke using this RECT struct:</p>
<pre><code>[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
static extern IntPtr DrawText(IntPtr HDC, String str, Int32 count, ref RECT rect, UInt32 flags, IntPtr dtp);
</code></pre>
<p>Since structs are value types in C# as opposed to being reference types like in C/C++, the ref modifier is necessary here.</p>
<p>However when I use <code>rect.top rect.left</code> etc, they almost always return 0. I know for a fact that this is incorrect. But after googling countless hours and trying a lot of different things, I couldn't make this simple stuff work.</p>
<p>Things I've tried:</p>
<ul>
<li>Using different primitives for RECT members (int, long, short, UInt32...). Actually it is kinda obvious that this is not a type problem because in any case I should see some garbled numbers, not 0.</li>
<li>Removing ref modifier. This is also stupid (desperate times, desperate measures) because rect.left correctly returns the pointer to rect instead of its value.</li>
<li>Tried <code>unsafe</code> code blocks. Didn't work but I may have made a mistake in the implementation (I don't remember what I've done). Besides this approach is generally reserved for tricky pointer situations in COM and Win32, it is overkill for my case anyway.</li>
<li>Tried adding <code>[MarshallAs]</code> before the members of RECT. Made no difference.</li>
<li>Played around with <code>Pack</code> values. No difference.</li>
</ul>
<p>I am fairly sure that I'm missing something very easy and straightforward but I have no idea what it is...</p>
<p>Any help is appreciated. Thank you.</p>
|
[
{
"answer_id": 203239,
"author": "Werg38",
"author_id": 27569,
"author_profile": "https://Stackoverflow.com/users/27569",
"pm_score": 2,
"selected": false,
"text": "[MarshallAs] [MarshalAs(UnmanagedType.Struct)]"
},
{
"answer_id": 203999,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "\n[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct tagRECT {\n\n /// LONG->int\n public int left;\n\n /// LONG->int\n public int top;\n\n /// LONG->int\n public int right;\n\n /// LONG->int\n public int bottom;\n}\n\npublic partial class NativeMethods {\n\n /// Return Type: int\n ///hdc: HDC->HDC__*\n ///lpchText: LPCWSTR->WCHAR*\n ///cchText: int\n ///lprc: LPRECT->tagRECT*\n ///format: UINT->unsigned int\n [System.Runtime.InteropServices.DllImportAttribute(\"user32.dll\", EntryPoint=\"DrawTextW\")]\npublic static extern int DrawTextW([System.Runtime.InteropServices.InAttribute()] System.IntPtr hdc, [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder lpchText, int cchText, ref tagRECT lprc, uint format) ;\n\n}\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
203,194
|
<p>I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using <code>jQuery.getJSON()</code>.</p>
<p>Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until <code>jQuery.getJSON()</code> executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until <code>jQuery.getJSON()</code> ran).</p>
<p>The only way I can think of out of this problem is to somehow specify the name of my function to <code>jQuery.getJSON()</code> instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.</p>
|
[
{
"answer_id": 205164,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 0,
"selected": false,
"text": "window.fixed_callback = function(data){\n alert(data.title);\n};\n\n$(function() {\n $.getScript(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&tagmode=any&format=json&jsoncallback=fixed_callback\", function(data) {\n alert('done'); } );\n});\n"
},
{
"answer_id": 205350,
"author": "Greg Borenstein",
"author_id": 10419,
"author_profile": "https://Stackoverflow.com/users/10419",
"pm_score": 3,
"selected": true,
"text": "jQuery.getScript jQuery.getScript _=12344567 jQuery.Ajax jQuery.ajax({\n url: fbookUrl,\n dataType: \"script\",\n type: \"GET\",\n cache: true,\n callback: null,\n data: null\n});\n fbookUrl callback=myFunction dataType: \"script\" cache: true"
},
{
"answer_id": 6044685,
"author": "eloycm",
"author_id": 467923,
"author_profile": "https://Stackoverflow.com/users/467923",
"pm_score": 2,
"selected": false,
"text": "jQuery.ajax({\n url: fbookUrl,\n dataType: \"jsonp\",\n type: \"GET\",\n cache: true,\n jsonp: false,\n jsonpCallback: \"MyFunctionName\" //insert here your function name\n});"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419/"
] |
203,195
|
<p>Is there a Registry setting that I can look for to determine whether or not the Visual C++ redistributable is installed, whether standalone or as part of Visual Studio 2008? I know that I could launch the VC++ 2008 redistributable installer and let it handle the detection, but it would look cleaner if I can check for it and not bother launching the installer if the redistributable is already on the system.</p>
<p>It's no biggie if there is no setting to search for, as this is just for the preliminary installers that we have for the new version of our software. We won't need it for the new Windows Installer-based installers that we are working on that will replace the old tech ones and will use the merge modules.</p>
|
[
{
"answer_id": 203268,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "if (LoadLibrary(L\"msvcrt80.dll\")!=NULL)\n{\n // it is installed\n}\n"
},
{
"answer_id": 203825,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 2,
"selected": false,
"text": "$WINDIR\\WinSxS\\x86_Microsoft.VC90.CRT_*"
},
{
"answer_id": 734726,
"author": "lImbus",
"author_id": 32490,
"author_profile": "https://Stackoverflow.com/users/32490",
"pm_score": 3,
"selected": false,
"text": "$WINDIR\\WinSxS\\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.30729*"
},
{
"answer_id": 804801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "BOOL IsVC2008RedistInstalled(LPCTSTR pLogFile)\n{\n TCHAR szLogEntry[256];\n memset(szLogEntry, '0', sizeof(szLogEntry));\n HKEY hKey;\n LONG lErr;\n\n TCHAR csid[256];\n _stprintf( csid, _T(\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"));\n lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, csid, 0, KEY_QUERY_VALUE, &hKey);\n if (lErr == ERROR_SUCCESS)\n {\n _stprintf(szLogEntry, _T(\"VC2008 Redistributable was installed before.\\n\"));\n toFile(pLogFile, szLogEntry);\n return TRUE;\n }\n else\n {\n _stprintf(szLogEntry, _T(\"VC2008 Redistributable was not installed before. %ld\\n\"), lErr);\n toFile(pLogFile, szLogEntry);\n return FALSE;\n }\n}\n"
},
{
"answer_id": 2880309,
"author": "user346856",
"author_id": 346856,
"author_profile": "https://Stackoverflow.com/users/346856",
"pm_score": 4,
"selected": false,
"text": "* VC 8.0 (x86) - {A49F249F-0C91-497F-86DF-B2585E8E76B7}\n* VC 8.0 (x64) - {6E8E85E8-CE4B-4FF5-91F7-04999C9FAE6A}\n* VC 8.0 (ia64) - {03ED71EA-F531-4927-AABD-1C31BCE8E187}\n * VC 8.0 SP1 (x86) - {7299052B-02A4-4627-81F2-1818DA5D550D}\n* VC 8.0 SP1 (x64) - {071C9B48-7C32-4621-A0AC-3F809523288F}\n* VC 8.0 SP1 (ia64) - {0F8FB34E-675E-42ED-850B-29D98C2ECE08}\n * VC 8.0 SP1 ATL Patch (x86) - {837B34E3-7C30-493C-8F6A-2B0F04E2912C}\n* VC 8.0 SP1 ATL Patch (x64) - {6CE5BAE9-D3CA-4B99-891A-1DC6C118A5FC}\n* VC 8.0 SP1 ATL Patch (ia64) - {85025851-A784-46D8-950D-05CB3CA43A13}\n * VC 9.0 (x86) - {FF66E9F6-83E7-3A3E-AF14-8DE9A809A6A4}\n* VC 9.0 (x64) - {350AA351-21FA-3270-8B7A-835434E766AD}\n* VC 9.0 (ia64) - {2B547B43-DB50-3139-9EBE-37D419E0F5FA} \n * VC 9.0 SP1 (x86) - {9A25302D-30C0-39D9-BD6F-21E6EC160475}\n* VC 9.0 SP1 (x64) - {8220EEFE-38CD-377E-8595-13398D740ACE}\n* VC 9.0 SP1 (ia64) - {5827ECE1-AEB0-328E-B813-6FC68622C1F9}\n * VC 9.0 SP1 ATL (x86) - {1F1C2DFC-2D24-3E06-BCB8-725134ADF989}\n* VC 9.0 SP1 ATL (x64) - {4B6C7001-C7D6-3710-913E-5BC23FCE91E6}\n* VC 9.0 SP1 ATL (ia64) - {977AD349-C2A8-39DD-9273-285C08987C7B}\n"
},
{
"answer_id": 7619859,
"author": "kenjiuno",
"author_id": 974413,
"author_profile": "https://Stackoverflow.com/users/974413",
"pm_score": 3,
"selected": false,
"text": "* VC 8.0 SP1 MFCLOC Patch (x86) - {710F4C1C-CC18-4C49-8CBF-51240C89A1A2}\n* VC 8.0 SP1 MFCLOC Patch (x64) - {AD8A2FA1-06E7-4B0D-927D-6E54B3D31028}\n* VC 8.0 SP1 MFCLOC Patch (ia64) - {C2F60BDA-462A-4A72-8E4D-CA431A56E9EA}\n"
},
{
"answer_id": 19970167,
"author": "Aaronontheweb",
"author_id": 377476,
"author_profile": "https://Stackoverflow.com/users/377476",
"pm_score": 2,
"selected": false,
"text": " wcout << _T(\"Checking for the availability of VC++ runtimes..\") << endl;\n wcout << _T(\"----------- Visual C++ 2008 (VC++9) -----------\") << endl;\n wcout << _T(\"Visual C++ 2008 (x86) ? \") << (IsVC2008Installed_x86() ? _T(\"true\") : _T(\"false\")) << endl;\n wcout << _T(\"Visual C++ 2008 (x64) ? \") << (IsVC2008Installed_x64() ? _T(\"true\") : _T(\"false\")) << endl;\n wcout << _T(\"Visual C++ 2008 SP1 (x86) ? \") << (IsVC2008SP1Installed_x86() ? _T(\"true\") : _T(\"false\")) << endl;\n wcout << _T(\"Visual C++ 2008 SP1 (x64) ? \") << (IsVC2008SP1Installed_x64() ? _T(\"true\") : _T(\"false\")) << endl;\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21255/"
] |
203,198
|
<p>I have a bit of code where I am looping through all the select boxes on a page and binding a <code>.hover</code> event to them to do a bit of twiddling with their width on <code>mouse on/off</code>.</p>
<p>This happens on page ready and works just fine.</p>
<p>The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.</p>
<p>I have found this plugin (<a href="http://brandonaaron.net/docs/livequery/#getting-started" rel="noreferrer">jQuery Live Query Plugin</a>), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.</p>
|
[
{
"answer_id": 203220,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "var mouseOverHandler = function() {\n // Do stuff\n};\nvar mouseOutHandler = function () {\n // Do stuff\n};\n\n$(function() {\n // On the document load, apply to existing elements\n $('select').hover(mouseOverHandler, mouseOutHandler);\n});\n\n// This next part would be in the callback from your Ajax call\n$(\"<select></select>\")\n .append( /* Your <option>s */ )\n .hover(mouseOverHandler, mouseOutHandler)\n .appendTo( /* Wherever you need the select box */ )\n;\n"
},
{
"answer_id": 203227,
"author": "Greg Borenstein",
"author_id": 10419,
"author_profile": "https://Stackoverflow.com/users/10419",
"pm_score": 6,
"selected": false,
"text": "function addCallbacks(eles){\n eles.hover(function(){alert(\"gotcha!\")});\n}\n\n$(document).ready(function(){\n addCallbacks($(\".myEles\"))\n});\n\n// ... add elements ...\naddCallbacks($(\".myNewElements\"))\n"
},
{
"answer_id": 1207393,
"author": "dev.e.loper",
"author_id": 37759,
"author_profile": "https://Stackoverflow.com/users/37759",
"pm_score": 12,
"selected": true,
"text": "jQuery.fn.on $(staticAncestors).on(eventName, dynamicChild, function() {});\n staticAncestors dynamicChild live() $(selector).live( eventName, function(){} );\n live() on() live() $(selector).live( eventName, function(){} );\n on() $(document).on( eventName, selector, function(){} );\n dosomething document document $(document).on('mouseover mouseout', '.dosomething', function(){\n // what you want to happen when mouseover and mouseout \n // occurs on elements that match '.dosomething'\n});\n $('.buttons').on('click', 'button', function(){\n // do something here\n});\n <div class=\"buttons\">\n <!-- <button>s that are generated dynamically and added here -->\n</div>\n"
},
{
"answer_id": 5384561,
"author": "user670265",
"author_id": 670265,
"author_profile": "https://Stackoverflow.com/users/670265",
"pm_score": 5,
"selected": false,
"text": ".live() .bind() .live() .hover"
},
{
"answer_id": 8586344,
"author": "Fazi",
"author_id": 1063991,
"author_profile": "https://Stackoverflow.com/users/1063991",
"pm_score": 5,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>Untitled Document</title>\n </head>\n\n <body>\n <script src=\"http://code.jquery.com/jquery-latest.js\"></script>\n <script src=\"http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js\"></script>\n\n <input type=\"button\" id=\"theButton\" value=\"Click\" />\n <script type=\"text/javascript\">\n $(document).ready(function()\n {\n $('.FOO').live(\"click\", function (){alert(\"It Works!\")});\n var $dialog = $('<div></div>').html('<div id=\"container\"><input type =\"button\" id=\"CUSTOM\" value=\"click\"/>This dialog will show every time!</div>').dialog({\n autoOpen: false,\n tite: 'Basic Dialog'\n });\n $('#theButton').click(function()\n {\n $dialog.dialog('open');\n return('false');\n });\n $('#CUSTOM').click(function(){\n //$('#container').append('<input type=\"button\" value=\"clickmee\" class=\"FOO\" /></br>');\n var button = document.createElement(\"input\");\n button.setAttribute('class','FOO');\n button.setAttribute('type','button');\n button.setAttribute('value','CLICKMEE');\n $('#container').append(button);\n });\n /* $('#FOO').click(function(){\n alert(\"It Works!\");\n }); */\n });\n </script>\n </body>\n</html>\n"
},
{
"answer_id": 18144022,
"author": "Ronen Rabinovici",
"author_id": 1806956,
"author_profile": "https://Stackoverflow.com/users/1806956",
"pm_score": 9,
"selected": false,
"text": "jQuery.fn.on .on() #dataTable tbody tr $(\"#dataTable tbody tr\").on(\"click\", function(event){\n console.log($(this).text());\n});\n $(\"#dataTable tbody\").on(\"click\", \"tr\", function(event){\n console.log($(this).text());\n});\n tbody tbody tr tbody"
},
{
"answer_id": 27373951,
"author": "Ram Patra",
"author_id": 1385441,
"author_profile": "https://Stackoverflow.com/users/1385441",
"pm_score": 8,
"selected": false,
"text": "document.addEventListener('click', function (e) {\n if (hasClass(e.target, 'bu')) {\n // .bu clicked\n // Do your thing\n } else if (hasClass(e.target, 'test')) {\n // .test clicked\n // Do your other thing\n }\n}, false);\n hasClass function hasClass(elem, className) {\n return elem.className.split(' ').indexOf(className) > -1;\n}\n hasClass function hasClass(elem, className) {\n return elem.classList.contains(className);\n}\n function hasClass(elem, className) {\n return elem.classList.contains(className);\n}\n\ndocument.addEventListener('click', function(e) {\n if (hasClass(e.target, 'bu')) {\n alert('bu');\n document.querySelector('.bu').innerHTML = '<div class=\"bu\">Bu<div class=\"tu\">Tu</div></div>';\n } else if (hasClass(e.target, 'test')) {\n alert('test');\n } else if (hasClass(e.target, 'tu')) {\n alert('tu');\n }\n\n}, false); .test,\n.bu,\n.tu {\n border: 1px solid gray;\n padding: 10px;\n margin: 10px;\n} <div class=\"test\">Test\n <div class=\"bu\">Bu</div>test\n</div>"
},
{
"answer_id": 32999007,
"author": "Martin Da Rosa",
"author_id": 2911545,
"author_profile": "https://Stackoverflow.com/users/2911545",
"pm_score": 5,
"selected": false,
"text": "var myElement = $('<button/>', {\n text: 'Go to Google!'\n});\n\nmyElement.bind( 'click', goToGoogle);\nmyElement.append('body');\n\n\nfunction goToGoogle(event){\n window.location.replace(\"http://www.google.com\");\n}\n"
},
{
"answer_id": 33843105,
"author": "Vatsal",
"author_id": 4249059,
"author_profile": "https://Stackoverflow.com/users/4249059",
"pm_score": 5,
"selected": false,
"text": "$(document).on(\"click\", 'selector', function() {\n // Your code here\n});\n"
},
{
"answer_id": 34351670,
"author": "Ankit Kathiriya",
"author_id": 4286710,
"author_profile": "https://Stackoverflow.com/users/4286710",
"pm_score": 4,
"selected": false,
"text": "$(document).ready(function(){\n //Particular Parent chield click\n $(\".buttons\").on(\"click\",\"button\",function(){\n alert(\"Clicked\");\n }); \n \n //Dynamic event bind on button class \n $(document).on(\"click\",\".button\",function(){\n alert(\"Dymamic Clicked\");\n });\n $(\"input\").addClass(\"button\"); \n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n<div class=\"buttons\">\n <input type=\"button\" value=\"1\">\n <button>2</button>\n <input type=\"text\">\n <button>3</button> \n <input type=\"button\" value=\"5\"> \n </div>\n<button>6</button>"
},
{
"answer_id": 34937304,
"author": "MadeInDreams",
"author_id": 144015,
"author_profile": "https://Stackoverflow.com/users/144015",
"pm_score": 5,
"selected": false,
"text": "$(document.body).on('click','.element', function(e) { });\n $(document.body).on('click','.element *', function(e) { });\n * $(document.body).on('click','.#element_id > element', function(e) { });\n"
},
{
"answer_id": 36230887,
"author": "Aslan Kaya",
"author_id": 1478851,
"author_profile": "https://Stackoverflow.com/users/1478851",
"pm_score": 4,
"selected": false,
"text": "<div class=\"container\">\n <ul class=\"select\">\n <li> First</li>\n <li>Second</li>\n </ul>\n</div>\n ul li select $(document).ready(function(e) {\n $('.container').on( 'click',\".select\", function(e) {\n alert(\"CLICKED\");\n });\n });\n"
},
{
"answer_id": 38115401,
"author": "Rohit Suthar",
"author_id": 1732454,
"author_profile": "https://Stackoverflow.com/users/1732454",
"pm_score": 5,
"selected": false,
"text": "$(document).on( 'click', '.click-activity', function () { ... });\n"
},
{
"answer_id": 38901509,
"author": "Mensur Grišević",
"author_id": 2938302,
"author_profile": "https://Stackoverflow.com/users/2938302",
"pm_score": 4,
"selected": false,
"text": "$('.buttons').on('click', 'button', function(){\n // your magic goes here\n});\n $('.buttons').delegate('button', 'click', function() {\n // your magic goes here\n});\n"
},
{
"answer_id": 40884178,
"author": "Kalpesh Patel",
"author_id": 1044026,
"author_profile": "https://Stackoverflow.com/users/1044026",
"pm_score": 3,
"selected": false,
"text": ".on() .live()"
},
{
"answer_id": 43224244,
"author": "guest271314",
"author_id": 2801559,
"author_profile": "https://Stackoverflow.com/users/2801559",
"pm_score": 4,
"selected": false,
"text": "jQuery(html, attributes) jQuery.fn function handleDynamicElementEvent(event) {\n console.log(event.type, this.value)\n}\n// create and attach event to dynamic element\njQuery(\"<select>\", {\n html: $.map(Array(3), function(_, index) {\n return new Option(index, index)\n }),\n on: {\n change: handleDynamicElementEvent\n }\n })\n .appendTo(\"body\"); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\">\n</script>"
},
{
"answer_id": 43480940,
"author": "Prasad De Silva",
"author_id": 3128521,
"author_profile": "https://Stackoverflow.com/users/3128521",
"pm_score": 3,
"selected": false,
"text": "// creating a dynamic element (container div)\nvar $div = $(\"<div>\", {id: 'myid1', class: 'myclass'});\n\n//creating a dynamic button\n var $btn = $(\"<button>\", { type: 'button', text: 'Click me', class: 'btn' });\n\n// binding the event\n $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {\n console.log('clicked');\n });\n\n// append dynamic button to the dynamic container\n$div.append($btn);\n\n// add the dynamically created element(s) to a static element\n$(\"#box\").append($div);\n"
},
{
"answer_id": 46251110,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "var body = $(\"body\");\nvar btns = $(\"button\");\nvar btnB = $(\"<button>B</button>\");\n// `<button>B</button>` is not yet in the document.\n// Thus, `$(\"button\")` gives `[<button>A</button>]`.\n// Only `<button>A</button>` gets a click listener.\nbtns.on(\"click\", function () {\n console.log(this);\n});\n// Too late for `<button>B</button>`...\nbody.append(btnB); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<button>A</button> var body = $(\"body\");\nvar btnB = $(\"<button>B</button>\");\nvar btnC = $(\"<button>C</button>\");\n// Listen to all clicks and\n// check if the source element\n// is a `<button></button>`.\nbody.on(\"click\", function (ev) {\n if ($(ev.target).is(\"button\")) {\n console.log(ev.target);\n }\n});\n// Now you can add any number\n// of `<button></button>`.\nbody.append(btnB);\nbody.append(btnC); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<button>A</button> var i = 11;\nvar body = $(\"body\");\nbody.on(\"click\", \"button\", function () {\n var letter = (i++).toString(36).toUpperCase();\n body.append($(\"<button>\" + letter + \"</button>\"));\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<button>A</button>"
},
{
"answer_id": 46452083,
"author": "Fakhrul Hasan",
"author_id": 4524167,
"author_profile": "https://Stackoverflow.com/users/4524167",
"pm_score": 0,
"selected": false,
"text": "<html>\n <head>\n <title>HTML Document</title>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js\"></script>\n </head>\n\n <body>\n <div id=\"hover-id\">\n Hello World\n </div>\n\n <script>\n jQuery(document).ready(function($){\n $(document).on('mouseover', '#hover-id', function(){\n $(this).css('color','yellowgreen');\n });\n\n $(document).on('mouseout', '#hover-id', function(){\n $(this).css('color','black');\n });\n });\n </script>\n </body>\n</html>\n"
},
{
"answer_id": 50402087,
"author": "Evhz",
"author_id": 5476782,
"author_profile": "https://Stackoverflow.com/users/5476782",
"pm_score": -1,
"selected": false,
"text": "$.bind $.unbind const sendAction = function(e){ ... }\n// bind the click\n$('body').on('click', 'button.send', sendAction );\n\n// unbind the click\n$('body').on('click', 'button.send', function(){} );\n"
},
{
"answer_id": 50752513,
"author": "truongnm",
"author_id": 3280050,
"author_profile": "https://Stackoverflow.com/users/3280050",
"pm_score": 4,
"selected": false,
"text": "$(document).on(\"click\", \"selector\", function() {\n // Your code here\n});\n"
},
{
"answer_id": 50752666,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 3,
"selected": false,
"text": "document var iterations = 4;\nvar button;\nvar body = document.querySelector(\"body\");\n\nfor (var i = 0; i < iterations; i++) {\n button = document.createElement(\"button\");\n button.classList.add(\"my-button\");\n button.appendChild(document.createTextNode(i));\n button.addEventListener(\"click\", myButtonWasClicked);\n body.appendChild(button);\n}\n\nfunction myButtonWasClicked(e) {\n console.log(e.target); //access to this specific button\n}"
},
{
"answer_id": 50856235,
"author": "Mustkeem K",
"author_id": 9266400,
"author_profile": "https://Stackoverflow.com/users/9266400",
"pm_score": 5,
"selected": false,
"text": "$('.wrapper-class').on(\"click\", '.selector-class', function() {\n // Your code here\n});\n <div class=\"wrapper-class\">\n <button class=\"selector-class\">\n Click Me!\n </button>\n</div> \n selector selector"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27580/"
] |
203,199
|
<p>I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?</p>
|
[
{
"answer_id": 203205,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 2,
"selected": false,
"text": "result = confirm('Yes or no question here.')\n"
},
{
"answer_id": 203210,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 0,
"selected": false,
"text": "alert(\"This box has an OK button.\");\n"
},
{
"answer_id": 203213,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 4,
"selected": true,
"text": "confirm alert window.showModalDialog(url,name,params)\n window.open(url,name,params)\n modal=yes params"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] |
203,207
|
<p>I got a program with a fscanf like this:</p>
<p>fscanf(stdin, "%d %d,....</p>
<p>I got many fscanf and files that I'd like to test, the files are like this</p>
<p>10485770 15 51200000
-2 10
10 10485760 10485760
10 10485760 10485760
10 10485760 10485760</p>
<p>Well my question is how can I tell to the program or the compiler to take the inputs not from the keyboard, but from those files. These programs are benchmarks and in the files I got the inputs, I'm sure there is a way to do this automatic because in some case there are many inputs. Thank you in advance.</p>
|
[
{
"answer_id": 203216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "freopen( \"somefile.txt\", \"r\", stdin );\n"
},
{
"answer_id": 203218,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 2,
"selected": false,
"text": "$ type input_file\n10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760\n10485760\n$ my_program.exe < input_file\n $ cat input_file\n10485770 15 51200000 -2 10 10 10485760 10485760 10 10485760 10485760 10 10485760\n10485760\n$ ./my_program < input_file\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
203,246
|
<p>What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?</p>
<p>I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.</p>
|
[
{
"answer_id": 203289,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 5,
"selected": true,
"text": "class Program\n{\n\n private static volatile bool _s_stop = false;\n\n public static void Main(string[] args)\n {\n Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n while (!_s_stop)\n {\n /* put real logic here */\n Console.WriteLine(\"still running at {0}\", DateTime.Now);\n Thread.Sleep(3000);\n }\n Console.WriteLine(\"Graceful shut down code here...\");\n\n //don't leave this... demonstration purposes only...\n Console.ReadLine();\n }\n\n static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)\n {\n //you have 2 options here, leave e.Cancel set to false and just handle any\n //graceful shutdown that you can while in here, or set a flag to notify the other\n //thread at the next check that it's to shut down. I'll do the 2nd option\n e.Cancel = true;\n _s_stop = true;\n Console.WriteLine(\"CancelKeyPress fired...\");\n }\n\n}\n"
},
{
"answer_id": 1083356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "_s_stop"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
203,257
|
<p>How can my app get a list of the True Type Fonts that are available on Linux. </p>
<p>Is there a standard directory where they are stored across different distributions? Or some other standard way to locate them?</p>
|
[
{
"answer_id": 1285647,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " PangoFontFamily **families;\n\n ...\n\n pango_context_list_families (\n gtk_widget_get_pango_context (GTK_WIDGET (notebook)),\n &families, &fontCount);\n\n printf(\"%d fonts found\\n\", fontCount);\n for(i=0; i<fontCount; i++)\n {\n printf(\"[%s]\\n\", pango_font_family_get_name (families[i]));\n }\n"
},
{
"answer_id": 11561342,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "fontmatrix"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/203257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
203,288
|
<p>I'm a PHP developer who knows a little bit of Ruby. I want to learn Ruby on Rails, but most of the resources I've come across treat RoR functionality as "magic" -- i.e., it has a certain internal consistency, but don't bother asking how it works in terms of Ruby, MySQL, etc.</p>
<p>Anyway, I want a deep understanding of how RoR works, the design decisions that went into building it, etc. In particular I'm interested in ActiveRecord, but really I'm looking for the whole package.</p>
<p>Any books / sites / advice welcome.</p>
|
[
{
"answer_id": 217050,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "method_missing __call __callstatic"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25068/"
] |
203,294
|
<p>I have two NSURLConnections. The second one depends on the content of the first, so handling the data received from the connection will be different for the two connections. </p>
<p>I'm just picking up Objective-C and I would like to know what the proper way to implement the delegates is.</p>
<p>Right now I'm using: </p>
<pre><code>NSURL *url=[NSURL URLWithString:feedURL];
NSURLRequest *urlR=[[[NSURLRequest alloc] initWithURL:url] autorelease];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:urlR delegate:self];
</code></pre>
<p>I don't want to use self as the delegate, how do I define two connections with different delegates?</p>
<pre><code>NSURLConnection *c1 = [[NSURLConnection alloc] initWithRequest:url delegate:handle1];
NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:handle2];
</code></pre>
<p>How would do i create handle1 and handle2 as implementations? Or interfaces? I don't really get how you would do this. </p>
<p>Any help would be awesome.</p>
<p>Thanks,
Brian Gianforcaro</p>
|
[
{
"answer_id": 206430,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 4,
"selected": false,
"text": "@interface DownloadDelegate : NSObject \n- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;\n@end\n\n@implementation DownloadDelegate\n- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {\n}\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {\n}\n@end\n DownloadDelegate *dd = [DownloadDelegate alloc];\nNSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:dd];\n"
},
{
"answer_id": 207307,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 3,
"selected": true,
"text": " DownloadDelegate *dd = [DownloadDelegate alloc];\n DownloadDelegate *dd = [[DownloadDelegate alloc] init];\n"
},
{
"answer_id": 1843673,
"author": "mml",
"author_id": 224066,
"author_profile": "https://Stackoverflow.com/users/224066",
"pm_score": 0,
"selected": false,
"text": "jsondelegate = [[JSonDelegate alloc]initWithCaller:self andSelector:@selector(jsonDone:)]\notherdelegate = [[OtherDelegate] initWithCaller:self andSelector:@selector(otherDone:)]\n if(self.jsonString && self.otherData){\n continueProcessing\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
] |
203,302
|
<p>I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the 'previous' and 'subsequent' items in the table?</p>
<p>It is not possible to simply add (or subtract) a value, as the dates do not have a regular gap between them. </p>
<p>One possible application would be 'previous/next' links in a photo album or blog web application, where the underlying data is in a SQL table.</p>
<p>I think there are two possible cases:</p>
<p><strong>Firstly</strong> where each date is unique:</p>
<p>Sample data:</p>
<pre><code>1,3,8,19,67,45
</code></pre>
<p>What query (or queries) would give 3 and 19 when supplied 8 as the parameter? (or the rows 3,8,19). Note that there are not always three rows to be returned - at the ends of the sequence one would be missing.</p>
<p><strong>Secondly</strong>, if there is a separate unique key to order the elements by, what is the query to return the set 'surrounding' a date? The order expected is by date then key.</p>
<p>Sample data:</p>
<pre><code>(key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8
</code></pre>
<p>What query for '8' returns the set:</p>
<pre><code>2:3,3:8,4:8,16:8,5:19
</code></pre>
<p>or what query generates the table:</p>
<pre><code>key date prev-key next-key
1 1 null 2
2 3 1 3
3 8 2 4
4 8 3 16
5 19 16 10
10 19 5 11
11 67 10 15
15 45 11 null
16 8 4 5
</code></pre>
<p>The table order is not important - just the next-key and prev-key fields.</p>
<hr>
<p>Both TheSoftwareJedi and Cade Roux have solutions that work for the data sets I posted last night. For the second question, both seem to fail for this dataset:</p>
<pre><code>(key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8
</code></pre>
<p>The order expected is by date then key, so one expected result might be: </p>
<pre><code>2:3,3:8,4:8,16:8,5:19
</code></pre>
<p>and another:</p>
<pre><code>key date prev-key next-key
1 1 null 2
2 3 1 3
3 8 2 4
4 8 3 16
5 19 16 10
10 19 5 11
11 67 10 15
15 45 11 null
16 8 4 5
</code></pre>
<p>The table order is not important - just the next-key and prev-key fields.</p>
|
[
{
"answer_id": 203310,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 2,
"selected": false,
"text": "select min(a)\nfrom theTable\nwhere a > 8\n\nselect max(a)\nfrom theTable\nwhere a < 8\n select * \n from theTable\n where date = 8\n\n union all\n\n select *\n from theTable\n where key = (select min(key) \n from theTable\n where key > (select max(key)\n from theTable\n where date = 8)\n )\n\n union all\n\n select *\n from theTable\n where key = (select max(key) \n from theTable\n where key < (select min(key)\n from theTable\n where date = 8)\n )\n\n order by key\n"
},
{
"answer_id": 203351,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": false,
"text": "/*\nCREATE TABLE [dbo].[stackoverflow_203302](\n [val] [int] NOT NULL\n) ON [PRIMARY]\n*/\n @val SELECT cur.val, MAX(prv.val) AS prv_val, MIN(nxt.val) AS nxt_val\nFROM stackoverflow_203302 AS cur\nLEFT JOIN stackoverflow_203302 AS prv\n ON cur.val > prv.val\nLEFT JOIN stackoverflow_203302 AS nxt\n ON cur.val < nxt.val\nWHERE cur.val = @val\nGROUP BY cur.val\n val prv_val nxt_val\n----------- ----------- -----------\n1 NULL 3\n3 1 8\n8 3 19\n19 8 45\n45 19 67\n67 45 NULL\n /*\nCREATE TABLE [dbo].[stackoverflow_203302](\n [ky] [int] NOT NULL,\n [val] [int] NOT NULL,\n CONSTRAINT [PK_stackoverflow_203302] PRIMARY KEY CLUSTERED (\n [ky] ASC\n )\n)\n*/\n\nSELECT cur.ky AS cur_ky\n ,cur.val AS cur_val\n ,prv.ky AS prv_ky\n ,prv.val AS prv_val\n ,nxt.ky AS nxt_ky\n ,nxt.val as nxt_val\nFROM (\n SELECT cur.ky, MAX(prv.ky) AS prv_ky, MIN(nxt.ky) AS nxt_ky\n FROM stackoverflow_203302 AS cur\n LEFT JOIN stackoverflow_203302 AS prv\n ON cur.ky > prv.ky\n LEFT JOIN stackoverflow_203302 AS nxt\n ON cur.ky < nxt.ky\n GROUP BY cur.ky\n) AS ordering\nINNER JOIN stackoverflow_203302 as cur\n ON cur.ky = ordering.ky\nLEFT JOIN stackoverflow_203302 as prv\n ON prv.ky = ordering.prv_ky\nLEFT JOIN stackoverflow_203302 as nxt\n ON nxt.ky = ordering.nxt_ky\n cur_ky cur_val prv_ky prv_val nxt_ky nxt_val\n----------- ----------- ----------- ----------- ----------- -----------\n1 1 NULL NULL 2 3\n2 3 1 1 3 8\n3 8 2 3 4 19\n4 19 3 8 5 67\n5 67 4 19 6 45\n6 45 5 67 NULL NULL\n"
},
{
"answer_id": 203385,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 1,
"selected": false,
"text": "SELECT 'next' AS direction, MIN(date_field) AS date_key\nFROM table_name\n WHERE date_field > current_date\nGROUP BY 1 -- necessity for group by varies from DBMS to DBMS in this context\nUNION\nSELECT 'prev' AS direction, MAX(date_field) AS date_key\n FROM table_name\n WHERE date_field < current_date\nGROUP BY 1\nORDER BY 1 DESC;\n direction date_key\n--------- --------\nprev 3\nnext 19\n"
},
{
"answer_id": 203451,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP 3 * FROM YourTable\nWHERE Col >= (SELECT MAX(Col) FROM YourTable b WHERE Col < @Parameter)\nORDER BY Col\n"
},
{
"answer_id": 204397,
"author": "John McAleely",
"author_id": 10019,
"author_profile": "https://Stackoverflow.com/users/10019",
"pm_score": 2,
"selected": true,
"text": "select date from test where date = 8\nunion all\nselect max(date) from test where date < 8\nunion all\nselect min(date) from test where date > 8\norder by date;\n (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8,17:3,18:1\n select * from test2 where date = 8\nunion all\nselect * from (select * from test2\n where date = (select max(date) from test2 \n where date < 8)) \n where key = (select max(key) from test2 \n where date = (select max(date) from test2 \n where date < 8))\nunion all\nselect * from (select * from test2\n where date = (select min(date) from test2 \n where date > 8)) \n where key = (select min(key) from test2 \n where date = (select min(date) from test2 \n where date > 8))\norder by date,key;\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10019/"
] |
203,316
|
<p>I have a table in my database which stores a tree structure. Here are the relevant fields:</p>
<pre><code>mytree (id, parentid, otherfields...)
</code></pre>
<p>I want to find all the leaf nodes (that is, any record whose <code>id</code> is not another record's <code>parentid</code>)</p>
<p>I've tried this:</p>
<pre><code>SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`)
</code></pre>
<p>But that returned an empty set. Strangely, removing the "NOT" returns the set of all the non-leaf nodes.</p>
<p>Can anyone see where I'm going wrong?</p>
<p><em>Update:</em> Thanks for the answers folks, they all have been correct and worked for me. I've accepted Daniel's since it also explains why my query didn't work (the NULL thing).</p>
|
[
{
"answer_id": 203323,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": false,
"text": "select a.*\nfrom mytree a left outer join\n mytree b on a.id = b.parentid\nwhere b.parentid is null\n"
},
{
"answer_id": 203329,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": true,
"text": "NULL SELECT * FROM `mytree` WHERE `id` NOT IN (\n SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL)\n"
},
{
"answer_id": 203331,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM mytree AS t1\nLEFT JOIN mytree AS t2 ON t1.id=t2.parentid\nWHERE t2.parentid IS NULL\n"
},
{
"answer_id": 203352,
"author": "fatbuddha",
"author_id": 28034,
"author_profile": "https://Stackoverflow.com/users/28034",
"pm_score": 1,
"selected": false,
"text": "Select * from mytree where id not in (Select distinct parentid from mytree where parentid is not null)\n"
},
{
"answer_id": 32957298,
"author": "Sunny srivastav",
"author_id": 5411480,
"author_profile": "https://Stackoverflow.com/users/5411480",
"pm_score": -1,
"selected": false,
"text": "memberid MemberID joiningposition packagetype\nRPM00000 NULL Root free\nRPM71572 RPM00000 Left Royal\nRPM323768 RPM00000 Right Royal\nRPM715790 RPM71572 Left free\nRPM323769 RPM71572 Right free\nRPM715987 RPM323768 Left free\nRPM323985 RPM323768 Right free\nRPM733333 RPM323985 Right free\nRPM324444 RPM715987 *emphasized text*Right Royal\n ALTER procedure [dbo].[sunnypro]\nas\nDECLARE @pId varchar(40) = 'RPM00000';\nDeclare @Id int\nset @Id=(select id from registration where childid=@pId) \nbegin\n\n\n\n\n-- Recursive CTE\n WITH R AS\n (\n\n\n\nSELECT \n\n BU.DateofJoing,\n BU.childid,\n BU.joiningposition,\n BU.packagetype\n FROM registration AS BU\n WHERE\n BU.MemberID = @pId and\n BU.joiningposition IN ('Left', 'Right')\n or BU.packagetype in('Royal','Platinum','Majestic')\n and BU.Id>@id\n UNION All\n\n-- Recursive part\nSELECT\n\n BU.DateofJoing,\n BU.childid,\n R.joiningposition,\n BU.packagetype\n\n\n FROM R\n JOIN registration AS BU\n ON BU.MemberID = R.childid\n WHERE\n BU.joiningposition IN ('Left', 'Right') and\n BU.packagetype in('Royal','Platinum','Majestic')\n and BU.Id>@id\n)\n\nINSERT INTO Wallatpayout\n (childid\n ,packagetype\n\n ,joiningposition\n ,DateofJoing\n ,Total)\n\n-- Final groups of nodes found\nSELECT top 3\n\nR.childid,\nR.packagetype,\nR.joiningposition,\nR.DateofJoing,\nTotal = COUNT_BIG(*)\nFROM R where R.packagetype in('Royal','Platinum','Majestic')\nGROUP BY R.childid,\nR.joiningposition,\nR.DateofJoing,\nR.packagetype\nOPTION (MAXRECURSION 0);\nend\n"
},
{
"answer_id": 71867168,
"author": "Rakib Hossain",
"author_id": 4929725,
"author_profile": "https://Stackoverflow.com/users/4929725",
"pm_score": 0,
"selected": false,
"text": "select *\nfrom `mytree `\nwhere not exists (select *\n from `mytree ` as `nodes`\n where `categories`.`id` = `nodes`.`parent`)\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
203,333
|
<p>What is the equivalent of the extended procedure 'xp_dirscan' in SQL Server 2005?</p>
|
[
{
"answer_id": 203374,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 0,
"selected": false,
"text": "xp_dirscan xp_cmdshell"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385/"
] |
203,336
|
<p>How would one create a Singleton class using PHP5 classes?</p>
|
[
{
"answer_id": 203359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "/**\n * Singleton class\n *\n */\nfinal class UserFactory\n{\n private static $inst = null;\n\n // Prevent cloning and de-serializing\n private function __clone(){}\n private function __wakeup(){}\n\n\n /**\n * Call this method to get singleton\n *\n * @return UserFactory\n */\n public static function Instance()\n {\n if ($inst === null) {\n $inst = new UserFactory();\n }\n return $inst;\n }\n \n /**\n * Private ctor so nobody else can instantiate it\n *\n */\n private function __construct()\n {\n \n }\n}\n $fact = UserFactory::Instance();\n$fact2 = UserFactory::Instance();\n $fact == $fact2; $fact = new UserFactory()\n static $inst = null;"
},
{
"answer_id": 203919,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 5,
"selected": false,
"text": "private function __clone() {}\n $inst1=UserFactory::Instance(); // to stick with the example provided above\n$inst2=clone $inst1;\n $inst1 $inst2"
},
{
"answer_id": 1939269,
"author": "selfawaresoup",
"author_id": 235308,
"author_profile": "https://Stackoverflow.com/users/235308",
"pm_score": 7,
"selected": false,
"text": "class Singleton\n{\n protected static $instance = null;\n\n protected function __construct()\n {\n //Thou shalt not construct that which is unconstructable!\n }\n\n protected function __clone()\n {\n //Me not like clones! Me smash clones!\n }\n\n public static function getInstance()\n {\n if (!isset(static::$instance)) {\n static::$instance = new static;\n }\n return static::$instance;\n }\n}\n class Foobar extends Singleton {};\n$foo = Foobar::getInstance();\n"
},
{
"answer_id": 3245620,
"author": "RobertPitt",
"author_id": 353790,
"author_profile": "https://Stackoverflow.com/users/353790",
"pm_score": 3,
"selected": false,
"text": "SingleTonBase abstract class SingletonBase\n{\n private static $storage = array();\n\n public static function Singleton($class)\n {\n if(in_array($class,self::$storage))\n {\n return self::$storage[$class];\n }\n return self::$storage[$class] = new $class();\n }\n public static function storage()\n {\n return self::$storage;\n }\n}\n public static function Singleton()\n{\n return SingletonBase::Singleton(get_class());\n}\n include 'libraries/SingletonBase.resource.php';\n\nclass Database\n{\n //Add that singleton function.\n public static function Singleton()\n {\n return SingletonBase::Singleton(get_class());\n }\n\n public function run()\n {\n echo 'running...';\n }\n}\n\n$Database = Database::Singleton();\n\n$Database->run();\n"
},
{
"answer_id": 8905139,
"author": "hungneox",
"author_id": 237107,
"author_profile": "https://Stackoverflow.com/users/237107",
"pm_score": 3,
"selected": false,
"text": "protected static $_instance;\n\npublic static function getInstance()\n{\n if(is_null(self::$_instance))\n {\n self::$_instance = new self();\n }\n return self::$_instance;\n}\n"
},
{
"answer_id": 13716841,
"author": "rizon",
"author_id": 794822,
"author_profile": "https://Stackoverflow.com/users/794822",
"pm_score": 3,
"selected": false,
"text": "class Database{\n\n //variable to hold db connection\n private $db;\n //note we used static variable,beacuse an instance cannot be used to refer this\n public static $instance;\n\n //note constructor is private so that classcannot be instantiated\n private function __construct(){\n //code connect to database \n\n } \n\n //to prevent loop hole in PHP so that the class cannot be cloned\n private function __clone() {}\n\n //used static function so that, this can be called from other classes\n public static function getInstance(){\n\n if( !(self::$instance instanceof self) ){\n self::$instance = new self(); \n }\n return self::$instance;\n }\n\n\n public function query($sql){\n //code to run the query\n }\n\n }\n\n\nAccess the method getInstance using\n$db = Singleton::getInstance();\n$db->query();\n"
},
{
"answer_id": 14511989,
"author": "user2009125",
"author_id": 2009125,
"author_profile": "https://Stackoverflow.com/users/2009125",
"pm_score": 2,
"selected": false,
"text": "class EncodeHTMLEntities {\n\n private static $instance = null;//stores the instance of self\n private $r = null;//array of chars elligalbe for replacement\n\n private function __clone(){\n }//disable cloning, no reason to clone\n\n private function __construct()\n {\n $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);\n $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);\n $this->r = array_diff($allEntities, $specialEntities);\n }\n\n public static function replace($string)\n {\n if(!(self::$instance instanceof self) ){\n self::$instance = new self();\n }\n return strtr($string, self::$instance->r);\n }\n}\n//test one million encodings of a string\n$start = microtime(true);\nfor($x=0; $x<1000000; $x++){\n $dump = EncodeHTMLEntities::replace(\"Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)\");\n}\n$end = microtime(true);\necho \"Run time: \".($end-$start).\" seconds using singleton\\n\";\n//now repeat the same without using singleton\n$start = microtime(true);\nfor($x=0; $x<1000000; $x++){\n $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);\n $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);\n $r = array_diff($allEntities, $specialEntities);\n $dump = strtr(\"Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)\", $r);\n}\n$end = microtime(true);\necho \"Run time: \".($end-$start).\" seconds without using singleton\";\n"
},
{
"answer_id": 14645766,
"author": "bboydev",
"author_id": 1578690,
"author_profile": "https://Stackoverflow.com/users/1578690",
"pm_score": -1,
"selected": false,
"text": "class Singleton{\n\n private static $data;\n\n function __construct(){\n if ($this::$data == null){\n $this->makeSingleton();\n }\n echo \"<br/>\".$this::$data;\n }\n\n private function makeSingleton(){\n $this::$data = rand(0, 100);\n }\n\n public function change($new_val){\n $this::$data = $new_val;\n }\n\n public function printme(){\n echo \"<br/>\".$this::$data;\n }\n\n}\n\n\n$a = new Singleton();\n$b = new Singleton();\n$c = new Singleton();\n\n$a->change(-2);\n$a->printme();\n$b->printme();\n\n$d = new Singleton();\n$d->printme();\n"
},
{
"answer_id": 15870364,
"author": "mpartel",
"author_id": 965979,
"author_profile": "https://Stackoverflow.com/users/965979",
"pm_score": 7,
"selected": false,
"text": "class Singleton\n{\n private static $instances = array();\n protected function __construct() {}\n protected function __clone() {}\n public function __wakeup()\n {\n throw new Exception(\"Cannot unserialize singleton\");\n }\n\n public static function getInstance()\n {\n $cls = get_called_class(); // late-static-bound class name\n if (!isset(self::$instances[$cls])) {\n self::$instances[$cls] = new static;\n }\n return self::$instances[$cls];\n }\n}\n class Foo extends Singleton {}\nclass Bar extends Singleton {}\n\necho get_class(Foo::getInstance()) . \"\\n\";\necho get_class(Bar::getInstance()) . \"\\n\";\n"
},
{
"answer_id": 16624144,
"author": "jose segura",
"author_id": 2396760,
"author_profile": "https://Stackoverflow.com/users/2396760",
"pm_score": 4,
"selected": false,
"text": "<?php\n/**\n * Singleton patter in php\n **/\ntrait SingletonTrait {\n protected static $inst = null;\n\n /**\n * call this method to get instance\n **/\n public static function getInstance(){\n if (static::$inst === null){\n static::$inst = new static();\n }\n return static::$inst;\n }\n\n /**\n * protected to prevent clonning \n **/\n protected function __clone(){\n }\n\n /**\n * protected so no one else can instance it \n **/\n protected function __construct(){\n }\n}\n /**\n * example of class definitions using SingletonTrait\n */\nclass DBFactory {\n /**\n * we are adding the trait here \n **/\n use SingletonTrait;\n\n /**\n * This class will have a single db connection as an example\n **/\n protected $db;\n\n\n /**\n * as an example we will create a PDO connection\n **/\n protected function __construct(){\n $this->db = \n new PDO('mysql:dbname=foodb;port=3305;host=127.0.0.1','foouser','foopass');\n }\n}\nclass DBFactoryChild extends DBFactory {\n /**\n * we repeating the inst so that it will differentiate it\n * from UserFactory singleton\n **/\n protected static $inst = null;\n}\n\n\n/**\n * example of instanciating the classes\n */\n$uf0 = DBFactoryChild::getInstance();\nvar_dump($uf0);\n$uf1 = DBFactory::getInstance();\nvar_dump($uf1);\necho $uf0 === $uf1;\n object(DBFactoryChild)#1 (0) {\n}\nobject(DBFactory)#2 (0) {\n}\n protected static $inst = null;\n object(DBFactoryChild)#1 (0) {\n}\nobject(DBFactoryChild)#1 (0) {\n}\n"
},
{
"answer_id": 19259931,
"author": "Joseph Crawford",
"author_id": 1827986,
"author_profile": "https://Stackoverflow.com/users/1827986",
"pm_score": 0,
"selected": false,
"text": "/**\n * Singleton class\n *\n */\nfinal class UserFactory\n{\n private static $_instance = null;\n\n /**\n * Private constructor\n *\n */\n private function __construct() {}\n\n /**\n * Private clone method\n *\n */\n private function __clone() {}\n\n /**\n * Call this method to get singleton\n *\n * @return UserFactory\n */\n public static function getInstance()\n {\n if (self::$_instance === null) {\n self::$_instance = new UserFactory();\n }\n return self::$_instance;\n }\n}\n $user_factory = UserFactory::getInstance();\n $user_factory = UserFactory::$_instance;\n\nclass SecondUserFactory extends UserFactory { }\n"
},
{
"answer_id": 19959264,
"author": "Mário Kapusta",
"author_id": 2076112,
"author_profile": "https://Stackoverflow.com/users/2076112",
"pm_score": 0,
"selected": false,
"text": "class Singleton {\n\n private static $instance;\n private $count = 0;\n\n protected function __construct(){\n\n }\n\n public static function singleton(){\n\n if (!isset(self::$instance)) {\n\n self::$instance = new Singleton;\n\n }\n\n return self::$instance;\n\n }\n\n public function increment()\n {\n return $this->count++;\n }\n\n protected function __clone(){\n\n }\n\n protected function __wakeup(){\n\n }\n\n} \n"
},
{
"answer_id": 23998306,
"author": "Eric Anderson",
"author_id": 120067,
"author_profile": "https://Stackoverflow.com/users/120067",
"pm_score": 0,
"selected": false,
"text": "<?php\ntrait Singleton {\n\n # Single point of entry for creating a new instance. For a given\n # class always returns the same instance.\n public static function instance(){\n static $instances = array();\n $class = get_called_class();\n if( !isset($instances[$class]) ) $instances[$class] = new $class();\n return $instances[$class];\n }\n\n # Kill traditional methods of creating new instances\n protected function __clone() {}\n protected function __construct() {}\n}\n"
},
{
"answer_id": 27361638,
"author": "sunil rajput",
"author_id": 1071262,
"author_profile": "https://Stackoverflow.com/users/1071262",
"pm_score": 0,
"selected": false,
"text": " class Database { \n public static $instance; \n public static function getInstance(){ \n if(!isset(Database::$instance) ) { \n Database::$instance = new Database(); \n } \n return Database::$instance; \n } \n private function __cunstruct() { \n /* private and cant create multiple objects */ \n } \n public function getQuery(){ \n return \"Test Query Data\"; \n } \n } \n $dbObj = Database::getInstance(); \n $dbObj2 = Database::getInstance(); \n var_dump($dbObj); \n var_dump($dbObj2); \n\n\n/* \nAfter execution you will get following output: \n\nobject(Database)[1] \nobject(Database)[1] \n\n*/ \n"
},
{
"answer_id": 34342568,
"author": "Krzysztof Przygoda",
"author_id": 2254935,
"author_profile": "https://Stackoverflow.com/users/2254935",
"pm_score": 1,
"selected": false,
"text": "__construct() protected new __clone() private clone __wakeup() private unserialize() getInstance() static class Singleton"
},
{
"answer_id": 34563986,
"author": "Surendra Kumar Ahir",
"author_id": 4773669,
"author_profile": "https://Stackoverflow.com/users/4773669",
"pm_score": 0,
"selected": false,
"text": "class Database{\n public static $instance;\n public static function getInstance(){\n if(!isset(Database::$instance)){\n Database::$instance=new Database();\n\n return Database::$instance;\n }\n\n }\n\n $db=Database::getInstance();\n $db2=Database::getInstance();\n $db3=Database::getInstance();\n\n var_dump($db);\n var_dump($db2);\n var_dump($db3);\n object(Database)[1]\n object(Database)[1]\n object(Database)[1]\n"
},
{
"answer_id": 37800033,
"author": "Abraham Tugalov",
"author_id": 3684575,
"author_profile": "https://Stackoverflow.com/users/3684575",
"pm_score": 5,
"selected": false,
"text": "<?php\n\n/**\n * Singleton Pattern.\n * \n * Modern implementation.\n */\nclass Singleton\n{\n /**\n * Call this method to get singleton\n */\n public static function instance()\n {\n static $instance = false;\n if( $instance === false )\n {\n // Late static binding (PHP 5.3+)\n $instance = new static();\n }\n\n return $instance;\n }\n\n /**\n * Make constructor private, so nobody can call \"new Class\".\n */\n private function __construct() {}\n\n /**\n * Make clone magic method private, so nobody can clone instance.\n */\n private function __clone() {}\n\n /**\n * Make sleep magic method private, so nobody can serialize instance.\n */\n private function __sleep() {}\n\n /**\n * Make wakeup magic method private, so nobody can unserialize instance.\n */\n private function __wakeup() {}\n\n}\n <?php\n\n/**\n * Database.\n *\n * Inherited from Singleton, so it's now got singleton behavior.\n */\nclass Database extends Singleton {\n\n protected $label;\n\n /**\n * Example of that singleton is working correctly.\n */\n public function setLabel($label)\n {\n $this->label = $label;\n }\n\n public function getLabel()\n {\n return $this->label;\n }\n\n}\n\n// create first instance\n$database = Database::instance();\n$database->setLabel('Abraham');\necho $database->getLabel() . PHP_EOL;\n\n// now try to create other instance as well\n$other_db = Database::instance();\necho $other_db->getLabel() . PHP_EOL; // Abraham\n\n$other_db->setLabel('Priler');\necho $database->getLabel() . PHP_EOL; // Priler\necho $other_db->getLabel() . PHP_EOL; // Priler\n"
},
{
"answer_id": 39729914,
"author": "DevWL",
"author_id": 2179965,
"author_profile": "https://Stackoverflow.com/users/2179965",
"pm_score": 3,
"selected": false,
"text": "<?php\nnamespace wl;\n\n\n/**\n * @author DevWL\n * @dosc allows only one instance for each extending class.\n * it acts a litle bit as registry from the SingletonClassVendor abstract class point of view\n * but it provides a valid singleton behaviour for its children classes\n * Be aware, the singleton pattern is consider to be an anti-pattern\n * mostly because it can be hard to debug and it comes with some limitations.\n * In most cases you do not need to use singleton pattern\n * so take a longer moment to think about it before you use it.\n */\nabstract class SingletonClassVendor\n{\n /**\n * holds an single instance of the child class\n *\n * @var array of objects\n */\n protected static $instance = [];\n\n /**\n * @desc provides a single slot to hold an instance interchanble between all child classes.\n * @return object\n */\n public static final function getInstance(){\n $class = get_called_class(); // or get_class(new static());\n if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){\n self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class\n echo \"new \". $class . PHP_EOL; // remove this line after testing\n return self::$instance[$class]; // remove this line after testing\n }\n echo \"old \". $class . PHP_EOL; // remove this line after testing\n return static::$instance[$class];\n }\n\n /**\n * Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly \"new Class()\".\n */\n abstract protected function __construct();\n\n /**\n * Make clone magic method private, so nobody can clone instance.\n */\n private function __clone() {}\n\n /**\n * Make sleep magic method private, so nobody can serialize instance.\n */\n private function __sleep() {}\n\n /**\n * Make wakeup magic method private, so nobody can unserialize instance.\n */\n private function __wakeup() {}\n\n}\n /**\n * EXAMPLE\n */\n\n/**\n * @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton\n * __constructor must be set to protected becaouse: \n * 1 to allow instansiation from parent class \n * 2 to prevent direct instanciation of object with \"new\" keword.\n * 3 to meet requierments of SingletonClassVendor abstract class\n */\nclass Database extends SingletonClassVendor\n{\n public $type = \"SomeClass\";\n protected function __construct(){\n echo \"DDDDDDDDD\". PHP_EOL; // remove this line after testing\n }\n}\n\n\n/**\n * @example 2 - Config ...\n */\nclass Config extends SingletonClassVendor\n{\n public $name = \"Config\";\n protected function __construct(){\n echo \"CCCCCCCCCC\" . PHP_EOL; // remove this line after testing\n }\n}\n /**\n * TESTING\n */\n$bd1 = Database::getInstance(); // new\n$bd2 = Database::getInstance(); // old\n$bd3 = Config::getInstance(); // new\n$bd4 = Config::getInstance(); // old\n$bd5 = Config::getInstance(); // old\n$bd6 = Database::getInstance(); // old\n$bd7 = Database::getInstance(); // old\n$bd8 = Config::getInstance(); // old\n\necho PHP_EOL.\"COMPARE ALL DATABASE INSTANCES\".PHP_EOL;\nvar_dump($bd1);\necho '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\n\necho PHP_EOL;\n\necho PHP_EOL.\"COMPARE ALL CONFIG INSTANCES\". PHP_EOL;\nvar_dump($bd3);\necho '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\necho '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE\n"
},
{
"answer_id": 41951477,
"author": "Gyaneshwar Pardhi",
"author_id": 565551,
"author_profile": "https://Stackoverflow.com/users/565551",
"pm_score": 1,
"selected": false,
"text": "class SingletonDesignPattern {\n\n //just for demo there will be only one instance\n private static $instanceCount =0;\n\n //create the private instance variable\n private static $myInstance=null;\n\n //make constructor private so no one create object using new Keyword\n private function __construct(){}\n\n //no one clone the object\n private function __clone(){}\n\n //avoid serialazation\n public function __wakeup(){}\n\n //ony one way to create object\n public static function getInstance(){\n\n if(self::$myInstance==null){\n self::$myInstance=new SingletonDesignPattern();\n self::$instanceCount++;\n }\n return self::$myInstance;\n }\n\n public static function getInstanceCount(){\n return self::$instanceCount;\n }\n\n}\n\n//now lets play with singleton design pattern\n\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n$instance = SingletonDesignPattern::getInstance();\n\necho \"number of instances: \".SingletonDesignPattern::getInstanceCount();\n"
},
{
"answer_id": 59662578,
"author": "Dmitry",
"author_id": 3723707,
"author_profile": "https://Stackoverflow.com/users/3723707",
"pm_score": 0,
"selected": false,
"text": "final class Singleton\n{\n private static $instance = null;\n\n private function __construct(){}\n\n private function __clone(){}\n\n private function __wakeup(){}\n\n public static function get_instance()\n {\n if ( static::$instance === null ) {\n static::$instance = new static();\n }\n return static::$instance;\n }\n}\n"
},
{
"answer_id": 70051757,
"author": "Maniruzzaman Akash",
"author_id": 5543577,
"author_profile": "https://Stackoverflow.com/users/5543577",
"pm_score": 0,
"selected": false,
"text": "Singleton trait <?php\n\nnamespace Akash;\n\ntrait Singleton\n{\n /**\n * Singleton Instance\n *\n * @var Singleton\n */\n private static $instance;\n\n /**\n * Private Constructor\n *\n * We can't use the constructor to create an instance of the class\n *\n * @return void\n */\n private function __construct()\n {\n // Don't do anything, we don't want to be initialized\n }\n\n /**\n * Get the singleton instance\n *\n * @return Singleton\n */\n public static function getInstance()\n {\n if (!isset(self::$instance)) {\n self::$instance = new self();\n }\n\n return self::$instance;\n }\n\n /**\n * Private clone method to prevent cloning of the instance of the\n * Singleton instance.\n *\n * @return void\n */\n private function __clone()\n {\n // Don't do anything, we don't want to be cloned\n }\n\n /**\n * Private unserialize method to prevent unserializing of the Singleton\n * instance.\n *\n * @return void\n */\n private function __wakeup()\n {\n // Don't do anything, we don't want to be unserialized\n }\n}\n UserSeeder <?php\n\nclass UserSeeder\n{\n use Singleton;\n\n /**\n * Seed Users\n *\n * @return void\n */\n public function seed()\n {\n echo 'Seeding...';\n }\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26210/"
] |
203,355
|
<p>Does anyone know if there is an API to get the current monitor state (on or off) in Windows (XP/Vista/2000/2003)?</p>
<p>All of my searches seem to indicate there is no real way of doing this. </p>
<p><a href="http://www.promixis.com/forums/archive/index.php/t-1282.html" rel="noreferrer">This thread</a> tries to use <a href="http://msdn.microsoft.com/en-us/library/aa372690(VS.85).aspx" rel="noreferrer">GetDevicePowerState</a> which according to Microsoft's docs does not work for display devices. </p>
<p>In Vista I can listen to <a href="http://msdn.microsoft.com/en-us/library/aa373195(VS.85).aspx" rel="noreferrer">GUID_MONITOR_POWER_ON</a> but I do not seem to get events when the monitor is turned off manually. </p>
<p>In XP I can hook into <code>WM_SYSCOMMAND</code> <code>SC_MONITORPOWER</code>, looking for status 2. This only works for situations where the system triggers the power off. </p>
<p>The WMI <code>Win32_DesktopMonitor</code> class does not seem to help out as well. </p>
<p><strong>Edit</strong>: Here is <a href="http://groups.google.com/group/comp.os.ms-windows.programmer.win32/browse_thread/thread/6d3e0a0828e68b89/d095095f5244bab4?lnk=gst&q=GetDevicePowerState++monitor#d095095f5244bab4" rel="noreferrer">a discussion</a> on comp.os.ms-windows.programmer.win32 indicating there is no reliable way of doing this. </p>
<p>Anyone else have any other ideas? </p>
|
[
{
"answer_id": 204453,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 5,
"selected": true,
"text": "\\\\.\\LCD"
},
{
"answer_id": 613300,
"author": "Avram",
"author_id": 61883,
"author_profile": "https://Stackoverflow.com/users/61883",
"pm_score": 3,
"selected": false,
"text": "int main()\n{\n for(;monitorOff()!=1;)\n Sleep(500);\n return 0;\n}//main\n int monitorOff()\n{\n const GUID MonitorClassGuid =\n {0x4d36e96e, 0xe325, 0x11ce, \n {0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}};\n\n list<DevData> monitors;\n ListDeviceClassData(&MonitorClassGuid, monitors);\n\n list<DevData>::iterator it = monitors.begin(),\n it_end = monitors.end();\n for (; it != it_end; ++it)\n {\n const char *off_msg = \"\";\n\n //it->PowerData.PD_PowerStateMapping\n if (it->PowerData.PD_MostRecentPowerState != PowerDeviceD0)\n {\n return 1;\n }\n }//for\n\n return 0;\n}//monitorOff\n"
},
{
"answer_id": 37005017,
"author": "Delphi",
"author_id": 6286001,
"author_profile": "https://Stackoverflow.com/users/6286001",
"pm_score": 1,
"selected": false,
"text": "i := 0\n('Monitor'+IntToStr(i)+': '+IntToStr(Screen.Monitors[i].BoundsRect.Left)+', '+\nIntToStr(Screen.Monitors[i].BoundsRect.Top)+', '+\nIntToStr(Screen.Monitors[i].BoundsRect.Right)+', '+\nIntToStr(Screen.Monitors[i].BoundsRect.Bottom))\n Monitor0: 0, 0, 1600, 900\n Monitor0: 1637792, 4210405, 31266576, 1637696\n Monitor0: 4211194, 40, 1637668, 1637693\n"
},
{
"answer_id": 38241750,
"author": "Emrys Myrooin",
"author_id": 3548191,
"author_profile": "https://Stackoverflow.com/users/3548191",
"pm_score": 1,
"selected": false,
"text": "User32.ddl GetDisplayConfigBufferSizes QueryDisplayConfig PathInfo TargetInfo targetAvailable"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
203,358
|
<p>I want to set a style on the first and last TabItems in a TabControl, and have them updated as the visibility of the TabItems is changed. I can't see a way to do so with triggers.</p>
<p>What we're after looks like this:</p>
<pre>| > > > |</pre>
<p>And the visibility of TabItems are determined by binding.</p>
<p>I do have it working in code. On TabItem visibility changed, enumerate through TabItems until you find the first visible one. Set the style on that one. For all other visible TabItems, set them to the pointy style (so that the previously first visible one is now pointy). Then start from the end until you find a visible TabItem and set the last style on that one. (This also lets us address an issue with TabControl where it will display the content of a non-visible TabItem if none of the visible TabItems are selected.)</p>
<p>There's undoubtably improvements I could make to my method, but I'm not convinced that it IS the right approach.</p>
<p>How would you approach this?</p>
|
[
{
"answer_id": 204455,
"author": "Dave",
"author_id": 28197,
"author_profile": "https://Stackoverflow.com/users/28197",
"pm_score": 1,
"selected": false,
"text": " public Window1()\n {\n InitializeComponent();\n\n this.myTabItem.IsVisibleChanged += new DependencyPropertyChangedEventHandler(myTabItem_IsVisibleChanged);\n }\n\n private void myTabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n myTabControl.Items[0].Style = FindResource(\"MyTabItemStyle\") as Style;\n }\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28074/"
] |
203,377
|
<p>How do you get the max value of an enum?</p>
|
[
{
"answer_id": 203389,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 9,
"selected": true,
"text": "// given this enum:\npublic enum Foo\n{\n Fizz = 3, \n Bar = 1,\n Bang = 2\n}\n\n// this gets Fizz\nvar lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();\n var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();\n"
},
{
"answer_id": 203995,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": false,
"text": "enum Int32.MaxValue enum int Int32 enum enum SomeEnum\n{\n Fizz = 42\n}\n\npublic static void SomeFunc()\n{\n SomeEnum e = (SomeEnum)5;\n}\n"
},
{
"answer_id": 1303417,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 5,
"selected": false,
"text": "ValueType T Enum static void Main(string[] args)\n{\n MyEnum x = GetMaxValue<MyEnum>(); //In newer versions of C# (7.3+)\n MyEnum y = GetMaxValueOld<MyEnum>(); \n}\n\npublic static TEnum GetMaxValue<TEnum>()\n where TEnum : Enum\n{\n return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();\n}\n\n//When C# version is smaller than 7.3, use this:\npublic static TEnum GetMaxValueOld<TEnum>()\n where TEnum : IComparable, IConvertible, IFormattable\n{\n Type type = typeof(TEnum);\n\n if (!type.IsSubclassOf(typeof(Enum)))\n throw new\n InvalidCastException\n (\"Cannot cast '\" + type.FullName + \"' to System.Enum.\");\n\n return (TEnum)Enum.ToObject(type, Enum.GetValues(type).Cast<int>().Last());\n}\n\n\n\nenum MyEnum\n{\n ValueOne,\n ValueTwo\n}\n Public Function GetMaxValue _\n (Of TEnum As {IComparable, IConvertible, IFormattable})() As TEnum\n\n Dim type = GetType(TEnum)\n\n If Not type.IsSubclassOf(GetType([Enum])) Then _\n Throw New InvalidCastException _\n (\"Cannot cast '\" & type.FullName & \"' to System.Enum.\")\n\n Return [Enum].ToObject(type, [Enum].GetValues(type) _\n .Cast(Of Integer).Last)\nEnd Function\n"
},
{
"answer_id": 1376406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "'''''''\n\nEnum MattType\n zerothValue = 0\n firstValue = 1\n secondValue = 2\n thirdValue = 3\nEnd Enum\n\n'''''''\n\nDim iMax As Integer\n\niMax = System.Enum.GetValues(GetType(MattType)).GetUpperBound(0)\n\nMessageBox.Show(iMax.ToString, \"Max MattType Enum Value\")\n\n'''''''\n"
},
{
"answer_id": 1665787,
"author": "Eric Feng",
"author_id": 201457,
"author_profile": "https://Stackoverflow.com/users/201457",
"pm_score": 3,
"selected": false,
"text": " class Program\n {\n enum enum1 { one, two, second, third };\n enum enum2 { s1 = 10, s2 = 8, s3, s4 };\n enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };\n\n static void Main(string[] args)\n {\n TestMaxEnumValue(typeof(enum1));\n TestMaxEnumValue(typeof(enum2));\n TestMaxEnumValue(typeof(enum3));\n }\n\n static void TestMaxEnumValue(Type enumType)\n {\n Enum.GetValues(enumType).Cast<Int32>().ToList().ForEach(item =>\n Console.WriteLine(item.ToString()));\n\n int maxValue = Enum.GetValues(enumType).Cast<int>().Max(); \n Console.WriteLine(\"The max value of {0} is {1}\", enumType.Name, maxValue);\n }\n }\n"
},
{
"answer_id": 1665930,
"author": "Eric Feng",
"author_id": 201457,
"author_profile": "https://Stackoverflow.com/users/201457",
"pm_score": 3,
"selected": false,
"text": "public static class EnumExtension\n{\n public static int Max(this Enum enumType)\n { \n return Enum.GetValues(enumType.GetType()).Cast<int>().Max(); \n }\n}\n\nclass Program\n{\n enum enum1 { one, two, second, third };\n enum enum2 { s1 = 10, s2 = 8, s3, s4 };\n enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };\n\n static void Main(string[] args)\n {\n Console.WriteLine(enum1.one.Max()); \n }\n}\n"
},
{
"answer_id": 2320749,
"author": "Engineer",
"author_id": 279738,
"author_profile": "https://Stackoverflow.com/users/279738",
"pm_score": 2,
"selected": false,
"text": " Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);\n Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();\n"
},
{
"answer_id": 7130448,
"author": "Stephen Hosking",
"author_id": 114044,
"author_profile": "https://Stackoverflow.com/users/114044",
"pm_score": 1,
"selected": false,
"text": "type Foo =\n | Fizz = 3\n | Bang = 2\n\n// Helper function to convert enum to a sequence. This is also useful for iterating.\n// stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c\nlet ToSeq (a : 'A when 'A : enum<'B>) =\n Enum.GetValues(typeof<'A>).Cast<'B>()\n\n// Get the max of Foo\nlet FooMax = ToSeq (Foo()) |> Seq.max \n when 'A : enum<'B>"
},
{
"answer_id": 17618529,
"author": "Karanvir Kang",
"author_id": 1563840,
"author_profile": "https://Stackoverflow.com/users/1563840",
"pm_score": 6,
"selected": false,
"text": "Enum.GetValues(typeof(Foo)).Cast<int>().Max();\n Enum.GetValues(typeof(Foo)).Cast<int>().Min();\n"
},
{
"answer_id": 54275613,
"author": "yvan vander sanden",
"author_id": 2227654,
"author_profile": "https://Stackoverflow.com/users/2227654",
"pm_score": 1,
"selected": false,
"text": "enum Values {\n one,\n two,\n tree,\n End,\n}\n\nfor (Values i = 0; i < Values.End; i++) {\n Console.WriteLine(i);\n}\n\nvar random = new Random();\nConsole.WriteLine(random.Next((int)Values.End));\n"
},
{
"answer_id": 58610374,
"author": "XLars",
"author_id": 2989400,
"author_profile": "https://Stackoverflow.com/users/2989400",
"pm_score": 2,
"selected": false,
"text": "public enum ChannelMessageTypes : byte\n{\n Min = 0x80, // Or could be: Min = NoteOff\n NoteOff = 0x80,\n NoteOn = 0x90,\n PolyKeyPressure = 0xA0,\n ControlChange = 0xB0,\n ProgramChange = 0xC0,\n ChannelAfterTouch = 0xD0,\n PitchBend = 0xE0,\n Max = 0xE0 // Or could be: Max = PitchBend\n}\n\n// I use it like this to check if a ... is a channel message.\nif(... >= ChannelMessageTypes.Min || ... <= ChannelMessages.Max)\n{\n Console.WriteLine(\"Channel message received!\");\n}\n"
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] |
203,382
|
<p>Is there a difference between generating multiple numbers using a single random number generator (RNG) versus generating one number per generator and discarding it? Do both implementations generate numbers which are equally random? Is there a difference between the normal RNGs and the secure RNGs for this?</p>
<p>I have a web application that is supposed to generate a list of random numbers on behalf of clients. That is, the numbers should appear to be random from each client's point of view. Does this mean I need retain a separate random RNG per client session? Or can I share a single RNG across all sessions? Or can I create and discard a RNG on a per-request basis?</p>
<p><strong>UPDATE</strong>: This question is related to <a href="https://stackoverflow.com/questions/471157/is-a-subset-of-a-random-sequence-also-random">Is a subset of a random sequence also random?</a></p>
|
[
{
"answer_id": 203646,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "/dev/random /dev/urandom"
},
{
"answer_id": 203833,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 1,
"selected": false,
"text": ">>="
}
] |
2008/10/15
|
[
"https://Stackoverflow.com/questions/203382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.