qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
22,431
<p>I am looking for information on handling search in different ORMs.</p> <p>Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way.</p> <p>In environment where everything is searchable ORM need to support this feature in two ways:</p> <ul> <li>providing some indexing API on "O" side of ORM</li> <li>providing means for bulk database retrieval on "R" side</li> </ul> <p>Ideal solution would return ready made objects based on searched string. Do you know any good end-to-end solutions that does the job, not necessarily in PHP? If you dealt with similar problem it would be nice to listen what your experience is. Something more than <em>Use Lucene</em> or <em>semantic web is the way</em> oneliners, tho ;-)*</p>
[ { "answer_id": 302878, "author": "lo_fye", "author_id": 3407, "author_profile": "https://Stackoverflow.com/users/3407", "pm_score": 1, "selected": false, "text": "public function save(PropelPDO $con = null)\n{\n if($this->getIsSearchable())\n {\n // update your search index here. Lucene, Sphinx, or otherwise\n }\n\n return parent::save($conn);\n}\n class Search\n{\n protected $_searchableTypes = array('music','video','blog');\n\n public method findAll($search_term)\n {\n $results = array();\n\n foreach($this->_searchableTypes as $type)\n {\n $results[] = $this->findType($type, $search_term);\n }\n\n return $results;\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2169/" ]
22,444
<p>I have this gigantic ugly string:</p> <pre class="lang-none prettyprint-override"><code>J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully </code></pre> <p>I'm trying to extract pieces from it using regex. In this case, I want to grab everything after <code>Project Name</code> up to the part where it says <code>J0000011:</code> (the 11 is going to be a different number every time).</p> <p>Here's the regex I've been playing with:</p> <pre class="lang-none prettyprint-override"><code>Project name:\s+(.*)\s+J[0-9]{7}: </code></pre> <p>The problem is that it doesn't stop until it hits the <strong>J0000020:</strong> at the end.</p> <p>How do I make the regex stop at the first occurrence of <code>J[0-9]{7}</code>?</p>
[ { "answer_id": 22449, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 8, "selected": true, "text": ".* ? Project name:\\s+(.*?)\\s+J[0-9]{7}:\n" }, { "answer_id": 22457, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "Project name:\\s+(\\S*)\\s+J[0-9]{7}:\n \\S" }, { "answer_id": 22480, "author": "Svend", "author_id": 2491, "author_profile": "https://Stackoverflow.com/users/2491", "pm_score": 3, "selected": false, "text": "\".*\" \".*?\" \".\" \".*?\" \".*?\" s string m = Regex.Match(s, @\"Project name: (?<name>.*?) J\\d+\").Groups[\"name\"].Value;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
22,459
<p>I'm getting some strange, intermittent, data aborts (&lt; 5% of the time) in some of my code, when calling <code>memset()</code>. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.</p> <p>I'm using the following code:</p> <pre><code>char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); </code></pre> <p>As you can see, I'm not trying to use memset with a size larger that what's originally allocated with <code>malloc()</code></p> <p>Anyone see what might be wrong with this?</p>
[ { "answer_id": 22473, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 5, "selected": true, "text": "malloc NULL" }, { "answer_id": 22486, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 2, "selected": false, "text": "sprintf snprintf strcat strncat" }, { "answer_id": 22488, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 2, "selected": false, "text": "malloc" }, { "answer_id": 22799, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 1, "selected": false, "text": "wcstombs sprintf EZMPPOST\" \" EZMPTAG \"/\" EZMPVER \" \" TYPETXT EOL" }, { "answer_id": 107431, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "malloc memset calloc" }, { "answer_id": 128706, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 0, "selected": false, "text": " // sizeof(char) is 1 by definition. This memory does not require zero\n // initialisation. If it did, I'd use calloc.\n const int max_msg = 2048;\n char *msg = (char*)malloc(max_msg);\n if(!msg)\n {\n // Allocaton failure\n return;\n }\n // Use snprintf instead of sprintf to avoid buffer overruns\n // we write directly to msg, instead of using a temporary buffer and then calling\n // strcat. This saves CPU time, saves the temporary buffer, and removes the need\n // to zero initialise msg.\n snprintf(msg, max_msg, \"%s %s/%s %s%s\", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);\n\n //Add Data\n size_t len = wcslen(gdevID);\n // No need to zero init this\n char* temp = (char*)malloc(len);\n if(!temp)\n {\n free(msg);\n return;\n }\n wcstombs(temp, gdevID, len);\n // No need to use a temporary buffer - just append directly to the msg, protecting \n // against buffer overruns.\n snprintf(msg + strlen(msg), \n max_msg - strlen(msg), \"%s: %s%s\", \"DeviceID\", temp, EOL);\n free(temp);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
22,474
<p>How do I select all records that contain "LCS" within the title column in sql.</p>
[ { "answer_id": 22476, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 3, "selected": true, "text": "SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';\n" }, { "answer_id": 22489, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "select table_name \nfrom information_schema.columns \nwhere column_name like '%lcs%'\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453046/" ]
22,500
<p>The <a href="http://en.wikipedia.org/wiki/ANSI_C" rel="noreferrer">Wikipedia article on ANSI C</a> says:</p> <blockquote> <p>One of the aims of the ANSI C standardization process was to produce a superset of K&amp;R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style.</p> </blockquote> <p>That makes me think that there are differences. However, I didn't see a comparison between K&amp;R C and ANSI C. Is there such a document? If not, what are the major differences?</p> <p>EDIT: I believe the K&amp;R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore?</p>
[ { "answer_id": 22516, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 4, "selected": false, "text": "int f( p, q, r ) \nint p, float q, double r; \n{ \n // Code goes here \n}\n" }, { "answer_id": 55632, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "f(x)\n{\n return x + 1;\n}\n int f(x)\nint x;\n{\n return x + 1;\n}\n" }, { "answer_id": 15125979, "author": "Nagarjuna Yalamanchili", "author_id": 2117814, "author_profile": "https://Stackoverflow.com/users/2117814", "pm_score": 2, "selected": false, "text": " unsigned long foo (char* fmt, double data)\n {\n /*body of foo */\n }\n" }, { "answer_id": 38214128, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": ">> / %" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
22,503
<p>I have a form view, in the edit template I have two drop downs. Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback. Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2)</p> <p>On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error </p> <blockquote> <p>Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.</p> </blockquote> <p>Here is the drop down list #2:</p> <pre><code>&lt;asp:DropDownList ID="ProjectList" runat="server" SelectedValue='&lt;%# Bind("ConnectToProject_ID","{0:D}") %&gt;' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true"&gt; &lt;asp:ListItem Value="0" Text="{No Master Project}" Selected="True" /&gt; &lt;/asp:DropDownList&gt; </code></pre> <p>And here is the MasterProjectDataSource2:</p> <pre><code>&lt;asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server" SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" &gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID" PropertyName="SelectedValue" Type="Int32" /&gt; &lt;/SelectParameters&gt; &lt;/asp:ObjectDataSource&gt; </code></pre> <p>Any help on how to get this to work would be greatly appriciated.</p>
[ { "answer_id": 183587, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 2, "selected": false, "text": "FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\nddl.SelectedValue = String.Format(\"{0:D}\", ConnectToProject_ID);\n FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\ne.Values[\"ConnectToProject_ID\"] = ddl.SelectedValue;\n FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\ne.NewValues[\"ConnectToProject_ID\"] = ddl.SelectedValue;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2496/" ]
22,509
<p>I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using <a href="http://www.stardeveloper.com/articles/display.html?article=2007110401&amp;page=1" rel="nofollow noreferrer">this implementation</a> (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again.</p> <p>Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not.</p> <p>Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.</p>
[ { "answer_id": 22585, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": true, "text": "%systemroot%\\system32\\inetsrv\\MetaBase.xml Location =\"/LM/W3SVC/Filters/Compression/gzip\" png css js HcFileExtensions aspx HcScriptFileExtensions iisreset" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
22,519
<p>I have a folder in my web server used for the users to upload photos using an ASP page.</p> <p>Is it safe enough to give IUSR write permissions to the folder? Must I secure something else? I am afraid of hackers bypassing the ASP page and uploading content directly to the folder.</p> <p>I'm using ASP classic and IIS6 on Windows 2003 Server. The upload is through HTTP, not FTP.</p> <p>Edit: Changing the question for clarity and changing my answers as comments.</p>
[ { "answer_id": 24401, "author": "chrisofspades", "author_id": 2614, "author_profile": "https://Stackoverflow.com/users/2614", "pm_score": 0, "selected": false, "text": "set fs=Server.CreateObject(\"Scripting.FileSystemObject\")\nset f=fs.GetFile(\"upload.jpg\")\n'image mime types or image/jpeg or image/gif, so just check to see if \"image\" is instr\nif instr(f.type, \"image\") = 0 then\n f.delete\nend if\nset f=nothing\nset fs=nothing\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
22,524
<p>Example: You have a shortcut <code>s</code> to <code>SomeProgram</code> in the current directory.</p> <p>In <code>cmd.exe</code>, you can type <code>s</code> and it will launch the program.</p> <p>In PowerShell, typing <code>s</code> gives:</p> <blockquote> <p><code>The term 's' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.</code></p> </blockquote> <p>If you type <code>s.lnk</code> or <code>SomeProgram</code>, it runs the program just fine.</p> <p>How can I configure PowerShell to execute shortcuts just like programs?</p>
[ { "answer_id": 23687, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 2, "selected": false, "text": "& \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe\" -r | out-null\n" }, { "answer_id": 23694, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 3, "selected": false, "text": ";.LNK PATHEXT ./ PATH $env:path.Split( ';' ) | \n Get-ChildItem -filter *.lnk | \n select @{ Name='Path'; Expression={ $_.FullName } }, \n @{ Name='Name'; Expression={ [IO.Path]::GetFileNameWithoutExtension( $_.Name ) } } | \n where { -not (Get-Alias $_.Name -ea 0) } | \n foreach { Set-Alias $_.Name $_.Path }\n" }, { "answer_id": 65801, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 4, "selected": false, "text": "invoke-item 'Internet Explorer.lnk'\n ii 'internet explorer.lnk'\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
22,528
<p>I would like to have a reference for the pros and cons of using include <strong>files vs objects(classes)</strong> when developing PHP applications.</p> <p>I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others.</p> <p><strong>A Simple Example:</strong></p> <p>Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two)</p> <ol> <li><p><em>Create an authenticate.php file and include it on every page. It holds the logic for authentication.</em></p></li> <li><p><em>Create a user object, which has an authenticate function, reference the object for authentication on every page.</em> </p></li> </ol> <p><strong>Edit</strong> I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow:</p> <p>Includes - Sometimes a function is just easier/shorter/faster to call Objects - Grouping of functionality and properties leads for longer term maintenance.</p> <p><strong>Includes</strong> - Less code to write (no constructor, no class syntax) call me lazy but this is true.</p> <p><strong>Objects</strong> - Force formality and a single approach to functions and creation. </p> <p><strong>Includes</strong> - Easier for a novice to deal with Objects - Harder for novices, but frowned upon by professionals.</p> <p>I look at these factors at the start of a project to decide if I want to do includes or objects. Those are a few pros and cons off the top of my head.</p>
[ { "answer_id": 22551, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "include include __autoload" }, { "answer_id": 22578, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "class Session\n{\n const GUEST = 0;\n const SUBSCRIBER = 1;\n const ADMINISTRATOR = 2;\n\n public static function Type()\n {\n session_start();\n\n // Depending on how you use sessions on\n // your site, you might just check for the\n // existence of PHPSESSID. If you track\n // every visitor with sessions, however, you\n // might want to assign some separate unique\n // number (that you can track in a DB) to\n // authenticated sessions\n if(!$_SESSION['uniqid'])\n {\n return Session::GUEST;\n }\n else\n {\n // For the best security, don't store the\n // user's access permissions in the $_SESSION,\n // but rather check against the DB. This will\n // ensure that recently deleted or downgraded\n // administrators will not be able to make use\n // of a previous session.\n\n return THE_ACCESS_LEVEL_ACCORDING_TO_THE_DB\n }\n } \n}\n\n\n// In your files that need to check for authentication (you\n// could also do this in a controller if you're going MVC\n\nif(!(Session::Type() == Session::ADMINISTRATOR))\n{\n // Redirect them to wherever you want them to go instead,\n // like a log in page or something like that.\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
22,552
<p>I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.</p> <p>I tried this but it just barfs.</p> <pre><code>preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this-&gt;getResultVar('FullMessage'), $atmp ); </code></pre> <p>Is there are way to pass a regex in the above form to preg_match?</p>
[ { "answer_id": 22572, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "preg_match(\"/\n test\n/x\", $foo, $bar);\n" }, { "answer_id": 22574, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "preg_match(\n '/(?x)^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+/'\n , $this->getResultVar('FullMessage'), $atmp);\n preg_match('\n /(?x)^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+/\n ', $this->getResultVar('FullMessage'), $atmp);\n" }, { "answer_id": 22580, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "preg_match('\n ^J[0-9]{7}:\\s+\n (.*?) (?#Extract the Transaction Start Date msg)\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) (?#Extract the Project Name)\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) (?#Extract the Job Name)\n \\s+J[0-9]{7}:\\s+\n ', $this->getResultVar('FullMessage'), $atmp);\n" }, { "answer_id": 22589, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "/x preg_match('/\n ^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+\n /x', $this->getResultVar('FullMessage'), $atmp);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
22,566
<p>How do I get Perl to read the contents of a given directory into an array?</p> <p><a href="https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming" rel="noreferrer">Backticks</a> can do it, but is there some method using 'scandir' or a similar term?</p>
[ { "answer_id": 22573, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 7, "selected": true, "text": "opendir(D, \"/path/to/directory\") || die \"Can't open directory: $!\\n\";\nwhile (my $f = readdir(D)) {\n print \"\\$f = $f\\n\";\n}\nclosedir(D);\n my $d = shift;\n\nopendir(D, \"$d\") || die \"Can't open directory $d: $!\\n\";\nmy @list = readdir(D);\nclosedir(D);\n\nforeach my $f (@list) {\n print \"\\$f = $f\\n\";\n}\n opendir(DIR, $somedir) || die \"Can't open directory $somedir: $!\";\n@dots = grep { (!/^\\./) && -f \"$somedir/$_\" } readdir(DIR);\nclosedir DIR;\n @dots @list = grep !/^\\.\\.?$/, readdir(D);\n" }, { "answer_id": 22663, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 3, "selected": false, "text": "@files = </path/to/directory/*>;\n# To demonstrate:\nprint join(\", \", @files);\n" }, { "answer_id": 22678, "author": "Mickey", "author_id": 1494, "author_profile": "https://Stackoverflow.com/users/1494", "pm_score": 1, "selected": false, "text": "sub copy_directory {\nmy ($source, $dest) = @_;\nmy $start = time;\n\n# get the contents of the directory.\nopendir(D, $source);\nmy @f = readdir(D);\nclosedir(D);\n\n# recurse through the directory structure and copy files.\nforeach my $file (@f) {\n # Setup the full path to the source and dest files.\n my $filename = $source . \"\\\\\" . $file;\n my $destfile = $dest . \"\\\\\" . $file;\n \n # get the file info for the 2 files.\n my $sourceInfo = stat( $filename );\n my $destInfo = stat( $destfile );\n \n # make sure the destinatin directory exists.\n mkdir( $dest, 0777 );\n \n if ($file eq '.' || $file eq '..') {\n } elsif (-d $filename) { # if it's a directory then recurse into it.\n #print \"entering $filename\\n\";\n copy_directory($filename, $destfile); \n } else { \n # Only backup the file if it has been created/modified since the last backup \n if( (not -e $destfile) || ($sourceInfo->mtime > $destInfo->mtime ) ) {\n #print $filename . \" -> \" . $destfile . \"\\n\";\n copy( $filename, $destfile ) or print \"Error copying $filename: $!\\n\";\n } \n } \n}\n\nprint \"$source copied in \" . (time - $start) . \" seconds.\\n\"; \n}\n" }, { "answer_id": 22762, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "use IO::Dir;\n$d = IO::Dir->new(\".\");\nif (defined $d) {\n while (defined($_ = $d->read)) { something($_); }\n $d->rewind;\n while (defined($_ = $d->read)) { something_else($_); }\n undef $d;\n}\n\ntie %dir, 'IO::Dir', \".\";\nforeach (keys %dir) {\n print $_, \" \" , $dir{$_}->size,\"\\n\";\n}\n tie %dir, 'IO::Dir', $directory_name;\nmy @dirs = keys %dir;\n" }, { "answer_id": 22915, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": false, "text": "@files = glob ('/path/to/dir/*');\n" }, { "answer_id": 24436, "author": "trjh", "author_id": 2620, "author_profile": "https://Stackoverflow.com/users/2620", "pm_score": 1, "selected": false, "text": "opendir(DIR, $somedir) || die \"can't opendir $somedir: $!\";\n@dots = grep { (!/^\\./) && -f \"$somedir/$_\" } readdir(DIR);\nclosedir DIR;\n" }, { "answer_id": 38016, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "use DirHandle;\n$d = new DirHandle \".\";\nif (defined $d)\n{\n while (defined($_ = $d->read)) { something($_); }\n $d->rewind;\n while (defined($_ = $d->read)) { something_else($_); }\n undef $d;\n}\n DirHandle opendir() closedir() readdir() rewinddir()" }, { "answer_id": 42334054, "author": "Luke Fowler", "author_id": 2419597, "author_profile": "https://Stackoverflow.com/users/2419597", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy $directory = '/tmp';\n\nopendir (DIR, $directory) or die $!;\n\nwhile (my $file = readdir(DIR)) {\n next if ($file =~ m/^\\./);\n print \"$file\\n\";\n}\n #!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $dir = '/tmp';\n\nopendir(DIR, $dir) or die $!;\n\nmy @dots \n = grep { \n /^\\./ # Begins with a period\n && -f \"$dir/$_\" # and is a file\n} readdir(DIR);\n\n# Loop through the array printing out the filenames\nforeach my $file (@dots) {\n print \"$file\\n\";\n}\n\nclosedir(DIR);\nexit 0;\n\n\nclosedir(DIR);\nexit 0;\n" }, { "answer_id": 67091406, "author": "Shawn", "author_id": 9952196, "author_profile": "https://Stackoverflow.com/users/9952196", "pm_score": 1, "selected": false, "text": "children Path::Tiny use Path::Tiny;\nmy @files = path(\"/path/to/dir\")->children;\n Path::Tiny my @files = map { $_->stringify } path(\"/path/to/dir\")->children;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
22,570
<p>Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index.</p> <p>In this case, merging the function code back into the query seems impractical.</p> <p>I think I am missing something simple here.</p> <p>Here's the function for reference.</p> <pre><code>if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go </code></pre> <p>To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row:</p> <pre><code>where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight </code></pre> <p>[Edit]</p> <p>I'm incorporating @Todd's suggestion:</p> <pre><code>where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 </code></pre> <p>My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort.</p> <p>But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.</p>
[ { "answer_id": 22579, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 3, "selected": false, "text": "where\nyear(date1) = year(date2)\nand month(date1) = month(date2)\nand day(date1) = day(date2)\n" }, { "answer_id": 22592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "where \n datediff(day, date1, date2) = 0\n" }, { "answer_id": 22600, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "select dateadd(d, datediff(d, 0, current_timestamp), 0)\n" }, { "answer_id": 22640, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": false, "text": "WHERE MyDateTime >= @activityDateMidnight \n AND MyDateTime < (@activityDateMidnight + 1)\n" }, { "answer_id": 22656, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 1, "selected": false, "text": "declare @date1 date\ndeclare @date2 date\nset @date1='2008-1-1 10:00'\nset @date2='2008-1-1 22:00'\nif @date1=@date2\n print 'Equal'\nelse\n print 'Not equal'\n select convert(varchar,'2008-08-22 18:11:14.133',102)\n create function MakeDate (@InputDate datetime) returns datetime as\nbegin\n return cast(convert(varchar,@InputDate,102) as datetime);\nend\n Select * from Orders where dbo.MakeDate(OrderDate) = dbo.MakeDate(DeliveryDate)\n" }, { "answer_id": 22662, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 0, "selected": false, "text": "\nSelect *\nfrom mytable\nwhere datepart(dy,date1) = datepart(dy,date2)\nand\nyear(date1) = year(date2) --assuming you want the same year too\n" }, { "answer_id": 22802, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "SELECT @activityDateMidnight = '1/1/2008', @activityDateTZ = 'EST'\n Table: TimeZone\nFields: TimeZone, Offset\nValues: EST, -4\n\n--Multiply by -1, since we're converting EST to GMT.\n--Offsets are to go from GMT to EST.\nSELECT @activityGmtBegin = DATEADD(hh, Offset * -1, @activityDateMidnight)\nFROM TimeZone\nWHERE TimeZone = @activityDateTZ\n SELECT * FROM EventTable\nWHERE \n EventTime >= @activityGmtBegin --1/1/2008 4:00 AM\n AND EventTime < (@activityGmtBegin + 1) --1/2/2008 4:00 AM\n" }, { "answer_id": 23856, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "where t.TheDateINeedToCheck BETWEEN (\n dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, @ActivityDate)\n AND\n dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, (@ActivityDate + 1))\n)\n where v.TheLocalDateINeedToCheck BETWEEN @ActivityDate AND (@ActivityDate + 1)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
22,617
<p>I need to find out how to format numbers as strings. My code is here:</p> <pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm </code></pre> <p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p> <p>Bottom line, what library / function do I need to do this for me?</p>
[ { "answer_id": 22624, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "hours, minutes, seconds = 6, 56, 33\nf'{hours:02}:{minutes:02}:{seconds:02} {\"pm\" if hours > 12 else \"am\"}'\n str.format \"{:02}:{:02}:{:02} {}\".format(hours, minutes, seconds, \"pm\" if hours > 12 else \"am\")\n % \"%02d:%02d:%02d\" % (hours, minutes, seconds)\n time.strftime import time\n\nt = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)\ntime.strftime('%I:%M:%S %p', t)\n" }, { "answer_id": 22630, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "\"%d:%d:d\" % (hours, minutes, seconds)\n" }, { "answer_id": 24962, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": ">>> str(5)\n'5'\n>>> int(8.7)\n8\n" }, { "answer_id": 2550630, "author": "wescpy", "author_id": 305689, "author_profile": "https://Stackoverflow.com/users/305689", "pm_score": 7, "selected": false, "text": "% >>> \"Name: %s, age: %d\" % ('John', 35) \n'Name: John, age: 35' \n>>> i = 45 \n>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) \n'dec: 45/oct: 055/hex: 0X2D' \n>>> \"MM/DD/YY = %02d/%02d/%02d\" % (12, 7, 41) \n'MM/DD/YY = 12/07/41' \n>>> 'Total with tax: $%.2f' % (13.00 * 1.0825) \n'Total with tax: $14.07' \n>>> d = {'web': 'user', 'page': 42} \n>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d \n'http://xxx.yyy.zzz/user/42.html' \n str.format() str.format() >>> \"Name: {0}, age: {1}\".format('John', 35) \n'Name: John, age: 35' \n>>> i = 45 \n>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) \n'dec: 45/oct: 0o55/hex: 0X2D' \n>>> \"MM/DD/YY = {0:02d}/{1:02d}/{2:02d}\".format(12, 7, 41) \n'MM/DD/YY = 12/07/41' \n>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) \n'Total with tax: $14.07' \n>>> d = {'web': 'user', 'page': 42} \n>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) \n'http://xxx.yyy.zzz/user/42.html'\n :-) >>> name, age = 'John', 35\n>>> f'Name: {name}, age: {age}'\n'Name: John, age: 35'\n\n>>> i = 45\n>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'\n'dec: 45/oct: 0o55/hex: 0X2D'\n\n>>> m, d, y = 12, 7, 41\n>>> f\"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}\"\n'MM/DD/YY = 12/07/41'\n\n>>> f'Total with tax: ${13.00 * 1.0825:.2f}'\n'Total with tax: $14.07'\n\n>>> d = {'web': 'user', 'page': 42}\n>>> f\"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html\"\n'http://xxx.yyy.zzz/user/42.html'\n" }, { "answer_id": 26250207, "author": "Varun Chadha", "author_id": 3408904, "author_profile": "https://Stackoverflow.com/users/3408904", "pm_score": 1, "selected": false, "text": "\"%d:%d:d\" % (hours, minutes, seconds)\n" }, { "answer_id": 41352627, "author": "lmiguelvargasf", "author_id": 3705840, "author_profile": "https://Stackoverflow.com/users/3705840", "pm_score": 3, "selected": false, "text": "format() return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)\n return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'\n" }, { "answer_id": 65057124, "author": "Ranjeet R Patil", "author_id": 12415637, "author_profile": "https://Stackoverflow.com/users/12415637", "pm_score": 1, "selected": false, "text": ">>> hours, minutes, seconds = 9, 33, 35\n>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {\"pm\" if hours > 12 else \"am\"}'\n>>> print (time)\n09:33:35 am\n>>> type(time)\n\n<class 'str'>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504/" ]
22,623
<p>What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the <code>Exception</code> object's <code>InnerException</code> and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?</p> <pre><code>try { //some code } catch (Exception ex) { throw ex; } </code></pre> <p>Vs:</p> <pre><code>try { //some code } catch { throw; } </code></pre>
[ { "answer_id": 22628, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 9, "selected": true, "text": "throw; try {\n // something that bombs here\n} catch (Exception ex)\n{\n throw;\n}\n throw ex; throw ex;" }, { "answer_id": 22639, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 5, "selected": false, "text": "throw ex throw" }, { "answer_id": 22648, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "Exception SqlException NullReferenceException InnerExceptions" }, { "answer_id": 22649, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 7, "selected": false, "text": "try{\n} \ncatch(Exception ex){\n throw new MoreDescriptiveException(\"here is what was happening\", ex);\n}\n" }, { "answer_id": 22650, "author": "Kevin Griffin", "author_id": 1226, "author_profile": "https://Stackoverflow.com/users/1226", "pm_score": 2, "selected": false, "text": "try\n{\n //some code\n}\ncatch\n{\n //you should totally do something here, but feel free to rethrow\n //if you need to send the exception up the stack.\n throw;\n}\n" }, { "answer_id": 22673, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 2, "selected": false, "text": "try\n{\n// Dangerous code\n}\nfinally\n{\n// clean up, or do nothing\n}\n" }, { "answer_id": 5653239, "author": "redcalx", "author_id": 15703, "author_profile": "https://Stackoverflow.com/users/15703", "pm_score": 0, "selected": false, "text": " private void foo()\n {\n try\n {\n bar(3);\n bar(2);\n bar(1);\n bar(0);\n }\n catch(DivideByZeroException)\n {\n //log message and rethrow...\n throw;\n }\n }\n\n private void bar(int b)\n {\n int a = 1;\n int c = a/b; // Generate divide by zero exception.\n }\n" }, { "answer_id": 9186501, "author": "notlkk", "author_id": 576300, "author_profile": "https://Stackoverflow.com/users/576300", "pm_score": 3, "selected": false, "text": "static void Main(string[] args)\n{\n try\n {\n TestMe();\n }\n catch (Exception ex)\n {\n string ss = ex.ToString();\n }\n}\n\nstatic void TestMe()\n{\n try\n {\n //here's some code that will generate an exception - line #17\n }\n catch (Exception ex)\n {\n //throw new ApplicationException(ex.ToString());\n throw ex; // line# 22\n }\n}\n" }, { "answer_id": 11284872, "author": "CARLOS LOTH", "author_id": 139042, "author_profile": "https://Stackoverflow.com/users/139042", "pm_score": 5, "selected": false, "text": "throw try\n{\n int i = 0;\n int j = 12 / i; // Line 47\n int k = j + 1;\n}\ncatch\n{\n // do something\n // ...\n throw; // Line 54\n}\n Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.\n at Program.WithThrowIncomplete() in Program.cs:line 54\n at Program.Main(String[] args) in Program.cs:line 106\n private static void PreserveStackTrace(Exception exception)\n{\n MethodInfo preserveStackTrace = typeof(Exception).GetMethod(\"InternalPreserveStackTrace\",\n BindingFlags.Instance | BindingFlags.NonPublic);\n preserveStackTrace.Invoke(exception, null);\n}\n static void PreserveStackTrace (Exception e) \n{ \n var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; \n var mgr = new ObjectManager (null, ctx) ; \n var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; \n\n e.GetObjectData (si, ctx) ; \n mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData \n mgr.DoFixups () ; // ObjectManager calls SetObjectData \n\n // voila, e is unmodified save for _remoteStackTraceString \n} \n protected Exception(\n SerializationInfo info,\n StreamingContext context\n)\n" }, { "answer_id": 40586475, "author": "Mark", "author_id": 6192931, "author_profile": "https://Stackoverflow.com/users/6192931", "pm_score": 4, "selected": false, "text": "ExceptionDispatchInfo.Capture( ex ).Throw() throw throw ExceptionDispatchInfo.Capture( ex ).Throw() void CallingMethod()\n{\n //try\n {\n throw new Exception( \"TEST\" );\n }\n //catch\n {\n // throw;\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n ExceptionDispatchInfo.Capture( ex ).Throw();\n throw; // So the compiler doesn't complain about methods which don't either return or throw.\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch\n {\n throw;\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n throw new Exception( \"RETHROW\", ex );\n }\n}\n CallingMethod throw new Exception( \"TEST\" ) CallingMethod throw throw new Exception( \"TEST\" )" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
22,676
<p>I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.</p> <p>The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows <code>.bat</code> file to download the actual MP3 file. I would prefer to have the entire utility written in Python.</p> <p>I struggled to find a way to actually download the file in Python, thus why I resorted to using <code>wget</code>.</p> <p>So, how do I download the file using Python?</p>
[ { "answer_id": 22682, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 10, "selected": true, "text": "urllib.request.urlopen() import urllib.request\nwith urllib.request.urlopen('http://www.example.com/') as f:\n html = f.read().decode('utf-8')\n urllib2 import urllib2\nresponse = urllib2.urlopen('http://www.example.com/')\nhtml = response.read()\n" }, { "answer_id": 22721, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 7, "selected": false, "text": "import urllib2\nmp3file = urllib2.urlopen(\"http://www.example.com/songs/mp3.mp3\")\nwith open('test.mp3','wb') as output:\n output.write(mp3file.read())\n wb open('test.mp3','wb')" }, { "answer_id": 22723, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 4, "selected": false, "text": "import urllib\nresponse = urllib.urlopen('http://www.example.com/sound.mp3')\nmp3 = response.read()\n import urllib\nmp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()\n" }, { "answer_id": 22776, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 10, "selected": false, "text": "urlretrieve import urllib.request\nurllib.request.urlretrieve(\"http://www.example.com/songs/mp3.mp3\", \"mp3.mp3\")\n import urllib urllib.urlretrieve" }, { "answer_id": 10744565, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 9, "selected": false, "text": ">>> import requests\n>>> \n>>> url = \"http://download.thinkbroadband.com/10MB.zip\"\n>>> r = requests.get(url)\n>>> print len(r.content)\n10485760\n pip install requests tqdm from tqdm import tqdm\nimport requests\n\nurl = \"http://download.thinkbroadband.com/10MB.zip\"\nresponse = requests.get(url, stream=True)\n\nwith open(\"10MB\", \"wb\") as handle:\n for data in tqdm(response.iter_content()):\n handle.write(data)\n" }, { "answer_id": 16518224, "author": "Stan", "author_id": 2357007, "author_profile": "https://Stackoverflow.com/users/2357007", "pm_score": 5, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import ( division, absolute_import, print_function, unicode_literals )\n\nimport sys, os, tempfile, logging\n\nif sys.version_info >= (3,):\n import urllib.request as urllib2\n import urllib.parse as urlparse\nelse:\n import urllib2\n import urlparse\n\ndef download_file(url, dest=None):\n \"\"\" \n Download and save a file specified by url to dest directory,\n \"\"\"\n u = urllib2.urlopen(url)\n\n scheme, netloc, path, query, fragment = urlparse.urlsplit(url)\n filename = os.path.basename(path)\n if not filename:\n filename = 'downloaded.file'\n if dest:\n filename = os.path.join(dest, filename)\n\n with open(filename, 'wb') as f:\n meta = u.info()\n meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all\n meta_length = meta_func(\"Content-Length\")\n file_size = None\n if meta_length:\n file_size = int(meta_length[0])\n print(\"Downloading: {0} Bytes: {1}\".format(url, file_size))\n\n file_size_dl = 0\n block_sz = 8192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n f.write(buffer)\n\n status = \"{0:16}\".format(file_size_dl)\n if file_size:\n status += \" [{0:6.2f}%]\".format(file_size_dl * 100 / file_size)\n status += chr(13)\n print(status, end=\"\")\n print()\n\n return filename\n\nif __name__ == \"__main__\": # Only run if this file is called directly\n print(\"Testing with 10MB download\")\n url = \"http://download.thinkbroadband.com/10MB.zip\"\n filename = download_file(url)\n print(filename)\n" }, { "answer_id": 19011916, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 4, "selected": false, "text": "urlretrieve" }, { "answer_id": 19352848, "author": "JD3", "author_id": 2019895, "author_profile": "https://Stackoverflow.com/users/2019895", "pm_score": 2, "selected": false, "text": " import urllib2,os\n\n url = \"http://download.thinkbroadband.com/10MB.zip\"\n\n file_name = url.split('/')[-1]\n u = urllib2.urlopen(url)\n f = open(file_name, 'wb')\n meta = u.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n print \"Downloading: %s Bytes: %s\" % (file_name, file_size)\n os.system('cls')\n file_size_dl = 0\n block_sz = 8192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n f.write(buffer)\n status = r\"%10d [%3.2f%%]\" % (file_size_dl, file_size_dl * 100. / file_size)\n status = status + chr(8)*(len(status)+1)\n print status,\n\n f.close()\n" }, { "answer_id": 20218209, "author": "Zuko", "author_id": 2114557, "author_profile": "https://Stackoverflow.com/users/2114557", "pm_score": 2, "selected": false, "text": "import urllib\nsock = urllib.urlopen(\"http://diveintopython.org/\")\nhtmlSource = sock.read() \nsock.close() \nprint htmlSource \n" }, { "answer_id": 21363808, "author": "Marcin Cuprjak", "author_id": 2454922, "author_profile": "https://Stackoverflow.com/users/2454922", "pm_score": 3, "selected": false, "text": "def report(blocknr, blocksize, size):\n current = blocknr*blocksize\n sys.stdout.write(\"\\r{0:.2f}%\".format(100.0*current/size))\n\ndef downloadFile(url):\n print \"\\n\",url\n fname = url.split('/')[-1]\n print fname\n urllib.urlretrieve(url, fname, report)\n" }, { "answer_id": 29256384, "author": "Sara Santana", "author_id": 4579638, "author_profile": "https://Stackoverflow.com/users/4579638", "pm_score": 6, "selected": false, "text": "import wget\nwget.download('url')\n" }, { "answer_id": 31857152, "author": "bmaupin", "author_id": 399105, "author_profile": "https://Stackoverflow.com/users/399105", "pm_score": 7, "selected": false, "text": "urllib.request.urlopen import urllib.request\nresponse = urllib.request.urlopen('http://www.example.com/')\nhtml = response.read()\n urllib.request.urlretrieve import urllib.request\nurllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')\n urllib.request.urlretrieve urllib2.urlopen import urllib2\nresponse = urllib2.urlopen('http://www.example.com/')\nhtml = response.read()\n urllib.urlretrieve import urllib\nurllib.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')\n" }, { "answer_id": 33816517, "author": "max", "author_id": 1896222, "author_profile": "https://Stackoverflow.com/users/1896222", "pm_score": 3, "selected": false, "text": "from parallel_sync import wget\nurls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']\nwget.download('/tmp', urls)\n# or a single file:\nwget.download('/tmp', urls[0], filenames='x.zip', extract=True)\n" }, { "answer_id": 39573536, "author": "Jaydev", "author_id": 4269615, "author_profile": "https://Stackoverflow.com/users/4269615", "pm_score": 4, "selected": false, "text": "urllib.urlretrieve ('url_to_file', file_name) urllib2.urlopen('url_to_file') requests.get(url) wget.download('url', file_name) urlopen urlretrieve requests.get" }, { "answer_id": 42764549, "author": "Sphynx-HenryAY", "author_id": 5421147, "author_profile": "https://Stackoverflow.com/users/5421147", "pm_score": 2, "selected": false, "text": "import urllib.request\nurl_request = urllib.request.Request(url, headers=headers)\nurl_connect = urllib.request.urlopen(url_request)\n\n#remember to open file in bytes mode\nwith open(filename, 'wb') as f:\n while True:\n buffer = url_connect.read(buffer_size)\n if not buffer: break\n\n #an integer value of size of written data\n data_wrote = f.write(buffer)\n\n#you could probably use with-open-as manner\nurl_connect.close()\n" }, { "answer_id": 43958201, "author": "imallett", "author_id": 688624, "author_profile": "https://Stackoverflow.com/users/688624", "pm_score": 2, "selected": false, "text": "import sys\ntry:\n import urllib.request\n python3 = True\nexcept ImportError:\n import urllib2\n python3 = False\n\n\ndef progress_callback_simple(downloaded,total):\n sys.stdout.write(\n \"\\r\" +\n (len(str(total))-len(str(downloaded)))*\" \" + str(downloaded) + \"/%d\"%total +\n \" [%3.2f%%]\"%(100.0*float(downloaded)/float(total))\n )\n sys.stdout.flush()\n\ndef download(srcurl, dstfilepath, progress_callback=None, block_size=8192):\n def _download_helper(response, out_file, file_size):\n if progress_callback!=None: progress_callback(0,file_size)\n if block_size == None:\n buffer = response.read()\n out_file.write(buffer)\n\n if progress_callback!=None: progress_callback(file_size,file_size)\n else:\n file_size_dl = 0\n while True:\n buffer = response.read(block_size)\n if not buffer: break\n\n file_size_dl += len(buffer)\n out_file.write(buffer)\n\n if progress_callback!=None: progress_callback(file_size_dl,file_size)\n with open(dstfilepath,\"wb\") as out_file:\n if python3:\n with urllib.request.urlopen(srcurl) as response:\n file_size = int(response.getheader(\"Content-Length\"))\n _download_helper(response,out_file,file_size)\n else:\n response = urllib2.urlopen(srcurl)\n meta = response.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n _download_helper(response,out_file,file_size)\n\nimport traceback\ntry:\n download(\n \"https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip\",\n \"output.zip\",\n progress_callback_simple\n )\nexcept:\n traceback.print_exc()\n input()\n" }, { "answer_id": 44693533, "author": "Akif", "author_id": 950762, "author_profile": "https://Stackoverflow.com/users/950762", "pm_score": 5, "selected": false, "text": "Python 2 & Python 3 six from six.moves import urllib\nurllib.request.urlretrieve(\"http://www.example.com/songs/mp3.mp3\", \"mp3.mp3\")\n" }, { "answer_id": 47098069, "author": "Omer Dagan", "author_id": 1773706, "author_profile": "https://Stackoverflow.com/users/1773706", "pm_score": 3, "selected": false, "text": "urllib wget wget $ python wget_test.py \nurlretrive_test : starting\nurlretrive_test : 6.56\n==============\nwget_no_bar_test : starting\nwget_no_bar_test : 7.20\n==============\nwget_with_bar_test : starting\n100% [......................................................................] 541335552 / 541335552\nwget_with_bar_test : 50.49\n==============\n import wget\nimport urllib\nimport time\nfrom functools import wraps\n\ndef profile(func):\n @wraps(func)\n def inner(*args):\n print func.__name__, \": starting\"\n start = time.time()\n ret = func(*args)\n end = time.time()\n print func.__name__, \": {:.2f}\".format(end - start)\n return ret\n return inner\n\nurl1 = 'http://host.com/500a.iso'\nurl2 = 'http://host.com/500b.iso'\nurl3 = 'http://host.com/500c.iso'\n\ndef do_nothing(*args):\n pass\n\n@profile\ndef urlretrive_test(url):\n return urllib.urlretrieve(url)\n\n@profile\ndef wget_no_bar_test(url):\n return wget.download(url, out='/tmp/', bar=do_nothing)\n\n@profile\ndef wget_with_bar_test(url):\n return wget.download(url, out='/tmp/')\n\nurlretrive_test(url1)\nprint '=============='\ntime.sleep(1)\n\nwget_no_bar_test(url2)\nprint '=============='\ntime.sleep(1)\n\nwget_with_bar_test(url3)\nprint '=============='\ntime.sleep(1)\n urllib" }, { "answer_id": 48691447, "author": "Apurv Agarwal", "author_id": 6712942, "author_profile": "https://Stackoverflow.com/users/6712942", "pm_score": 4, "selected": false, "text": "pip3 install urllib3 shutil\n import urllib.request\nimport shutil\n\nurl = \"http://www.somewebsite.com/something.pdf\"\noutput_file = \"save_this_name.pdf\"\nwith urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n urllib3 urllib" }, { "answer_id": 51738373, "author": "gzerone", "author_id": 1070813, "author_profile": "https://Stackoverflow.com/users/1070813", "pm_score": 2, "selected": false, "text": "import pycurl\n\nFILE_DEST = 'pycurl.html'\nFILE_SRC = 'http://pycurl.io/'\n\nwith open(FILE_DEST, 'wb') as f:\n c = pycurl.Curl()\n c.setopt(c.URL, FILE_SRC)\n c.setopt(c.WRITEDATA, f)\n c.perform()\n c.close()\n" }, { "answer_id": 52077420, "author": "Robin Dinse", "author_id": 5096199, "author_profile": "https://Stackoverflow.com/users/5096199", "pm_score": 3, "selected": false, "text": "subprocess urlretrieve wget -R -nc aria2 import subprocess\nsubprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])\n ! !wget -O example_output_file.html https://example.com\n" }, { "answer_id": 53153505, "author": "H S Umer farooq", "author_id": 6454850, "author_profile": "https://Stackoverflow.com/users/6454850", "pm_score": 5, "selected": false, "text": "import os,requests\ndef download(url):\n get_response = requests.get(url,stream=True)\n file_name = url.split(\"/\")[-1]\n with open(file_name, 'wb') as f:\n for chunk in get_response.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n\ndownload(\"https://example.com/example.jpg\")\n" }, { "answer_id": 60371032, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 3, "selected": false, "text": "python>=3.6 import dload\ndload.save(url)\n dload pip3 install dload\n" }, { "answer_id": 60555820, "author": "gibbone", "author_id": 6332373, "author_profile": "https://Stackoverflow.com/users/6332373", "pm_score": 0, "selected": false, "text": "wget soupget #!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import (division, absolute_import, print_function, unicode_literals)\nimport sys, os, argparse\nfrom bs4 import BeautifulSoup\n\n# --- insert Stan's script here ---\n# if sys.version_info >= (3,): \n#...\n#...\n# def download_file(url, dest=None): \n#...\n#...\n\n# --- new stuff ---\ndef collect_all_url(page_url, extensions):\n \"\"\"\n Recovers all links in page_url checking for all the desired extensions\n \"\"\"\n conn = urllib2.urlopen(page_url)\n html = conn.read()\n soup = BeautifulSoup(html, 'lxml')\n links = soup.find_all('a')\n\n results = [] \n for tag in links:\n link = tag.get('href', None)\n if link is not None: \n for e in extensions:\n if e in link:\n # Fallback for badly defined links\n # checks for missing scheme or netloc\n if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):\n results.append(link)\n else:\n new_url=urlparse.urljoin(page_url,link) \n results.append(new_url)\n return results\n\nif __name__ == \"__main__\": # Only run if this file is called directly\n # Command line arguments\n parser = argparse.ArgumentParser(\n description='Download all files from a webpage.')\n parser.add_argument(\n '-u', '--url', \n help='Page url to request')\n parser.add_argument(\n '-e', '--ext', \n nargs='+',\n help='Extension(s) to find') \n parser.add_argument(\n '-d', '--dest', \n default=None,\n help='Destination where to save the files')\n parser.add_argument(\n '-p', '--par', \n action='store_true', default=False, \n help=\"Turns on parallel download\")\n args = parser.parse_args()\n\n # Recover files to download\n all_links = collect_all_url(args.url, args.ext)\n\n # Download\n if not args.par:\n for l in all_links:\n try:\n filename = download_file(l, args.dest)\n print(l)\n except Exception as e:\n print(\"Error while downloading: {}\".format(e))\n else:\n from multiprocessing.pool import ThreadPool\n results = ThreadPool(10).imap_unordered(\n lambda x: download_file(x, args.dest), all_links)\n for p in results:\n print(p)\n python3 soupget.py -p -e <list of extensions> -d <destination_folder> -u <target_webpage>\n python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics\n" }, { "answer_id": 63876738, "author": "firebfm", "author_id": 3290793, "author_profile": "https://Stackoverflow.com/users/3290793", "pm_score": -1, "selected": false, "text": "from subprocess import call\nurl = \"\"\ncall([\"curl\", {url}, '--output', \"song.mp3\"])\n" }, { "answer_id": 68224842, "author": "Ninja Master", "author_id": 2693349, "author_profile": "https://Stackoverflow.com/users/2693349", "pm_score": 2, "selected": false, "text": ">>> import urllib3\n>>> http = urllib3.PoolManager()\n>>> r = http.request('GET', 'your_url_goes_here')\n>>> r.status\n 200\n>>> r.data\n *****Response Data****\n" }, { "answer_id": 72255053, "author": "uTesla", "author_id": 13962104, "author_profile": "https://Stackoverflow.com/users/13962104", "pm_score": 2, "selected": false, "text": "import requests as req\n\nremote_url = 'http://www.example.com/sound.mp3'\nlocal_file_name = 'sound.mp3'\n\ndata = req.get(remote_url)\n\n# Save file data to local copy\nwith open(local_file_name, 'wb')as file:\n file.write(data.content)\n" }, { "answer_id": 74097971, "author": "thebadgateway", "author_id": 14927325, "author_profile": "https://Stackoverflow.com/users/14927325", "pm_score": 0, "selected": false, "text": "http.client from http import HTTPStatus, client\nfrom shutil import copyfileobj\n\n# using https\nconnection = client.HTTPSConnection(\"www.example.com\")\nwith connection.request(\"GET\", \"/noise.mp3\") as response:\n if response.status == HTTPStatus.OK:\n copyfileobj(response, open(\"noise.mp3\")\n else:\n raise Exception(\"request needs work\")\n HTTPConnection" }, { "answer_id": 74445704, "author": "Mushfirat Mohaimin", "author_id": 15760624, "author_profile": "https://Stackoverflow.com/users/15760624", "pm_score": 0, "selected": false, "text": "keras.utils.get_file from tensorflow import keras\n\npath_to_downloaded_file = keras.utils.get_file(\n fname=\"file name\",\n origin=\"https://www.linktofile.com/link/to/file\",\n extract=True,\n archive_format=\"zip\", # downloaded file format\n cache_dir=\"/\", # cache and extract in current directory\n)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109/" ]
22,696
<p>OK, here is my problem, without being too specific for reasons of being fired for putting company practices on the internet.</p> <p>There are spreadsheets made. These are uploaded to the database. I need to filter out duplicates from uploading. The only way to do this is by making sure that for each and every entry that two fields aren't the same as an entry already in the database. As just becasue one field is the same does not mean its a duplicate. There are two specific fields lets call them FLDA and FLDB that both must match up to an entry in the database already. I can filter by one field already. I'm thinking this has to be a subquery but I'm not sure how to apply it. This is hard to decribe. Just ask if your not sure what I mean.</p>
[ { "answer_id": 24673, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "INSERT INTO ToUpdate ( Field1, Field2 )\nSELECT e.H1, e.H2\nFROM (SELECT * FROM [Sheet1$] IN '' [Excel 8.0;HDR=YES;IMEX=1;database=C:\\Docs\\LTD.xls]) As e\nLEFT JOIN ToUpdate ON (e.H2 = ToUpdate.Field2) AND (e.H1 = ToUpdate.Field1)\nWHERE ToUpdate.Field1 Is Null AND ToUpdate.Field2 Is Null\n" }, { "answer_id": 26101, "author": "kaybenleroll", "author_id": 277, "author_profile": "https://Stackoverflow.com/users/277", "pm_score": 0, "selected": false, "text": "SELECT T1.FLDA, T1.FLDB, T1.FLDC\nFROM Table1 T1, Table1 T2\nWHERE T1.FLDA = T2.FLDA\n AND T1.FLDB = T2.FLDB\n AND T1.FLDC <> T2.FLDC\n" }, { "answer_id": 70187, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 0, "selected": false, "text": "INSERT INTO tblInput\n SELECT XLS.* \n FROM tblInput AS T RIGHT JOIN\n [Excel 8.0;IMEX=1;HDR=Yes;DATABASE=c:\\data.xls;].[Sheet1$] AS XLS \n ON T.FLDA = XLS.FLDA AND T.FLDB = XLS.FLDB\n WHERE ISNULL(T.FLDA) AND ISNULL(T.FLDB);\n" }, { "answer_id": 149430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Select from Table 1 Group by X Having Y, Z, A" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
22,697
<p>What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?</p>
[ { "answer_id": 23048, "author": "Brian Laframboise", "author_id": 1557, "author_profile": "https://Stackoverflow.com/users/1557", "pm_score": 9, "selected": true, "text": "import static org.mockito.Mockito.*;\n\nList mockedList = mock(List.class);\nmockedList.clear();\nverify(mockedList).clear();\n" }, { "answer_id": 92998, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 4, "selected": false, "text": "def request = [isUserInRole: { roleName -> roleName == \"testRole\"}] as HttpServletRequest \n MockFor StubFor" }, { "answer_id": 93675, "author": "Kris Pruden", "author_id": 16977, "author_profile": "https://Stackoverflow.com/users/16977", "pm_score": 4, "selected": false, "text": "import mockit.Mockit;\n\n...\nMockit.redefineMethods(MyClassWithStaticInit.class,\n MyReplacementClass.class);\n...\nclass MyReplacementClass {\n public void $init() {...} // replace default constructor\n public static void $clinit{...} // replace static initializer\n public static void myStatic{...} // replace static method\n // etc...\n}\n import mockit.Expectations;\nimport org.testng.annotations.Test;\n\npublic class ExpecationsTest {\n private MyClass obj;\n\n @Test\n public void testFoo() {\n new Expectations(true) {\n MyClass c;\n {\n obj = c;\n invokeReturning(c.getFoo(\"foo\", false), \"bas\");\n }\n };\n\n assert \"bas\".equals(obj.getFoo(\"foo\", false));\n\n Expectations.assertSatisfied();\n }\n\n public static class MyClass {\n public String getFoo(String str, boolean bool) {\n if (bool) {\n return \"foo\";\n } else {\n return \"bar\";\n }\n }\n }\n}\n" }, { "answer_id": 489089, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 2, "selected": false, "text": "val propSqrt = forAll { (n: Int) => (n >= 0) ==> scala.Math.sqrt(n*n) == n }\n propSqrt.check()" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2030/" ]
22,708
<p>How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?</p> <p>Edit: A language-agnostic algorithm to determine this is the main goal here.</p>
[ { "answer_id": 22715, "author": "Joseph Sturtevant", "author_id": 317, "author_profile": "https://Stackoverflow.com/users/317", "pm_score": 6, "selected": true, "text": "public static string Column(int column)\n{\n column--;\n if (column >= 0 && column < 26)\n return ((char)('A' + column)).ToString();\n else if (column > 25)\n return Column(column / 26) + Column(column % 26 + 1);\n else\n throw new Exception(\"Invalid Column #\" + (column + 1).ToString());\n}\n" }, { "answer_id": 22719, "author": "goric", "author_id": 940, "author_profile": "https://Stackoverflow.com/users/940", "pm_score": -1, "selected": false, "text": "private String GetNthExcelColName(int n)\n{\n String firstLetter = \"\"; \n //if number is under 26, it has a single letter name\n // otherwise, it is 'A' for 27-52, 'B' for 53-78, etc\n if(n > 26)\n {\n //the Converts to double and back to int are just so Floor() can be used\n Double value = Convert.ToDouble((n-1) / 26);\n int firstLetterVal = Convert.ToInt32(Math.Floor(value))-1;\n firstLetter = Convert.ToChar(firstLetterValue + 65).ToString();\n } \n\n //second letter repeats\n int secondLetterValue = (n-1) % 26;\n String secondLetter = Convert.ToChar(secondLetterValue+65).ToString();\n\n return firstLetter + secondLetter;\n}\n" }, { "answer_id": 22738, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 3, "selected": false, "text": "A2 =MID(ADDRESS(1,A2),2,LEN(ADDRESS(1,A2))-3)\n" }, { "answer_id": 22766, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "Public Function GetColumnAddress(nCol As Integer) As String\n\nDim r As Range\n\nSet r = Range(\"A1\").Columns(nCol)\nGetColumnAddress = r.Address\n\nEnd Function\n" }, { "answer_id": 23781, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 4, "selected": false, "text": "function getNthColumnName(int n) {\n let curPower = 1\n while curPower < n {\n set curPower = curPower * 26\n }\n let result = \"\"\n while n > 0 {\n let temp = n / curPower\n let result = result + char(temp)\n set n = n - (curPower * temp)\n set curPower = curPower / 26\n }\n return result\n" }, { "answer_id": 37002, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 1, "selected": false, "text": "Function GetNthExcelColName(n As Integer) As String\n Dim s As String\n s = Cells(1, n).Address\n GetNthExcelColName = Mid(s, 2, InStr(2, s, \"$\") - 2)\nEnd Function\n" }, { "answer_id": 39952, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 0, "selected": false, "text": "Function ConvertNumberToColumnLetter2(ByVal colNum As Long) As String\n Dim i As Long, x As Long\n For i = 6 To 0 Step -1\n x = (1 - 26 ^ (i + 1)) / (-25) - 1 ‘ Geometric Series formula\n If colNum > x Then\n ConvertNumberToColumnLetter2 = ConvertNumberToColumnLetter2 & Chr(((colNum - x - 1)\\ 26 ^ i) Mod 26 + 65)\n End If\n Next i\nEnd Function\n" }, { "answer_id": 50472, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 0, "selected": false, "text": "function IntToExcel(n: Integer); string;\nbegin\n Result := '';\n for i := 2 down to 0 do \n begin\n if ((n div 26^i)) > 0) or (i = 0) then\n Result := Result + Char(Ord('A')+(n div (26^i)) - IIF(i>0;1;0));\n n := n mod (26^i);\n end;\nend;\n" }, { "answer_id": 515791, "author": "Maslow", "author_id": 57883, "author_profile": "https://Stackoverflow.com/users/57883", "pm_score": 1, "selected": false, "text": "Public Function Column(ByVal pColumn As Integer) As String\n pColumn -= 1\n If pColumn >= 0 AndAlso pColumn < 26 Then\n Return ChrW(Asc(\"A\"c) + pColumn).ToString\n ElseIf (pColumn > 25) Then\n Return Column(CInt(math.Floor(pColumn / 26))) + Column((pColumn Mod 26) + 1)\n Else\n stop\n Throw New ArgumentException(\"Invalid column #\" + (pColumn + 1).ToString)\n End If\nEnd Function\n" }, { "answer_id": 2292997, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 1, "selected": false, "text": "function ColNum2Letter(lCol as long) as string\n ColNum2Letter = Split(Cells(1, lCol).Address, \"$\")(0)\nend function\n" }, { "answer_id": 3550070, "author": "Matt Lewis", "author_id": 428667, "author_profile": "https://Stackoverflow.com/users/428667", "pm_score": 2, "selected": false, "text": "IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))\n ZZ AY AZ nY nZ =IF(COLUMN()>26,CHAR(ROUNDDOWN((COLUMN()-1)/26,0)+64)&CHAR(MOD((COLUMN()-1),26)+65),CHAR(COLUMN()+64)\n" }, { "answer_id": 4532562, "author": "Samuel Audet", "author_id": 523744, "author_profile": "https://Stackoverflow.com/users/523744", "pm_score": 5, "selected": false, "text": "String getNthColumnName(int n) {\n String name = \"\";\n while (n > 0) {\n n--;\n name = (char)('A' + n%26) + name;\n n /= 26;\n }\n return name;\n}\n" }, { "answer_id": 4695873, "author": "Craig0409", "author_id": 318875, "author_profile": "https://Stackoverflow.com/users/318875", "pm_score": 3, "selected": false, "text": "Function ColumnLetter(ByVal intColumnNumber)\n Dim sResult\n intColumnNumber = intColumnNumber - 1\n If (intColumnNumber >= 0 And intColumnNumber < 26) Then\n sResult = Chr(65 + intColumnNumber)\n ElseIf (intColumnNumber >= 26) Then\n sResult = ColumnLetter(CLng(intColumnNumber \\ 26)) _\n & ColumnLetter(CLng(intColumnNumber Mod 26 + 1))\n Else\n err.Raise 8, \"Column()\", \"Invalid Column #\" & CStr(intColumnNumber + 1)\n End If\n ColumnLetter = sResult\nEnd Function\n" }, { "answer_id": 10017783, "author": "James Evason", "author_id": 900506, "author_profile": "https://Stackoverflow.com/users/900506", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION [dbo].[GetExcelColRef] \n(\n @col_seq_no int\n)\nRETURNS varchar(5)\nAS\nBEGIN\n\ndeclare @Result varchar(5)\nset @Result = ''\nset @col_seq_no = @col_seq_no - 1\nIf (@col_seq_no >= 0 And @col_seq_no < 26) \nBEGIN\n set @Result = char(65 + @col_seq_no)\nEND\nELSE\nBEGIN\n set @Result = [dbo].[GetExcelColRef] (@col_seq_no / 26) + '' + [dbo].[GetExcelColRef] ((@col_seq_no % 26) + 1)\nEND\nReturn @Result\n\nEND\nGO\n" }, { "answer_id": 12614842, "author": "AndrewD", "author_id": 20151, "author_profile": "https://Stackoverflow.com/users/20151", "pm_score": 0, "selected": false, "text": "; WITH TestData AS ( -- Major change points\n SELECT -1 AS FieldOrdinal\n UNION ALL\n SELECT 0\n UNION ALL\n SELECT 25\n UNION ALL\n SELECT 26\n UNION ALL\n SELECT 701\n UNION ALL\n SELECT 702\n UNION ALL\n SELECT 703\n UNION ALL\n SELECT 16383\n UNION ALL\n SELECT 16384\n)\nSELECT\n FieldOrdinal\n , CASE\n WHEN FieldOrdinal < 0 THEN NULL\n WHEN FieldOrdinal < 26 THEN ''\n WHEN FieldOrdinal < 702 THEN CHAR (65 + FieldOrdinal / 26 - 1)\n WHEN FieldOrdinal < 16384 THEN CHAR (65 + FieldOrdinal / 676 - 1)\n + CHAR (65 + (FieldOrdinal / 26) - (FieldOrdinal / 676) * 26 - 1)\n ELSE NULL\n END\n + CHAR (65 + FieldOrdinal % 26)\n FROM TestData\n ORDER BY FieldOrdinal\n" }, { "answer_id": 13413291, "author": "PatrickDaemen", "author_id": 1829086, "author_profile": "https://Stackoverflow.com/users/1829086", "pm_score": 2, "selected": false, "text": "=MID(ADDRESS(1,colnr),2,LEN(ADDRESS(1,colnr))-3)\n" }, { "answer_id": 13882315, "author": "Jim Drannbauer", "author_id": 1904556, "author_profile": "https://Stackoverflow.com/users/1904556", "pm_score": 2, "selected": false, "text": "def column_name_for(some_int)\n some_int.to_s(26).split('').map {|c| (c.to_i(26) + 64).chr }.join # 703 => \"AAA\"\nend\n" }, { "answer_id": 16959692, "author": "Kent Pawar", "author_id": 985766, "author_profile": "https://Stackoverflow.com/users/985766", "pm_score": 2, "selected": false, "text": "columnNumber=28 Cells(1, columnNumber).Address \"$AB$1\" $ [\"\",\"AB\",\"1\"] Split(Cells(1, columnNumber).Address, \"$\")(1) \"AB\" ' The following VBA function is just one way to convert column number \n' values into their equivalent alphabetical characters:\n\nFunction ConvertToLetter(iCol As Integer) As String\n Dim iAlpha As Integer\n Dim iRemainder As Integer\n iAlpha = Int(iCol / 27)\n iRemainder = iCol - (iAlpha * 26)\n If iAlpha > 0 Then\n ConvertToLetter = Chr(iAlpha + 64)\n End If\n If iRemainder > 0 Then\n ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)\n End If\nEnd Function\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940/" ]
22,720
<p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p> <pre><code>Socket mySocket = new Socket(host,port); </code></pre> <p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p> <pre><code>tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT </code></pre> <p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p> <p>I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.</p> <p>Any advice please?</p> <p>Thanks all</p>
[ { "answer_id": 22803, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": true, "text": "isOutputShutdown() SocketWatcher Thread Socket SocketClosedException" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2362/" ]
22,732
<p>I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.</p> <p><strong>Code</strong></p> <pre><code>function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s </code></pre> <p><strong>Output</strong></p> <pre class="lang-none prettyprint-override"><code>cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 </code></pre>
[ { "answer_id": 22770, "author": "Paul Roub", "author_id": 1324, "author_profile": "https://Stackoverflow.com/users/1324", "pm_score": 7, "selected": true, "text": "$s = CreateAppPoolScript \"name\" \"user\" \"pass\"\n cscript adsutil.vbs CREATE \"w3svc/AppPools/name\" IIsApplicationPool\ncscript adsutil.vbs SET \"w3svc/AppPools/name/WamUserName\" \"user\"\ncscript adsutil.vbs SET \"w3svc/AppPools/name/WamUserPass\" \"pass\"\ncscript adsutil.vbs SET \"w3svc/AppPools/name/AppPoolIdentityType\" 3\n" }, { "answer_id": 40890, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 3, "selected": false, "text": "\" function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)\n{\n # Command to create an IIS application pool\n return @\"\ncscript adsutil.vbs CREATE \"w3svc/AppPools/$AppPoolName\" IIsApplicationPool\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/WamUserName\" \"$AppPoolUser\"\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/WamUserPass\" \"$AppPoolPass\"\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/AppPoolIdentityType\" 3\n\"@\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
22,764
<p>In Ruby 1.8 and earlier,</p> <pre><code>Foo </code></pre> <p>is a constant (a Class, a Module, or another constant). Whereas</p> <pre><code>foo </code></pre> <p>is a variable. The key difference is as follows:</p> <pre><code>module Foo bar = 7 BAZ = 8 end Foo::BAZ # =&gt; 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module </code></pre> <p>That's all well and good, but Ruby 1.9 <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html" rel="nofollow noreferrer">allows UTF-8 source code</a>. So is <code>℃</code> "uppercase" or "lowecase" as far as this is concerned? What about <code>⊂</code> (strict subset) or <code>Ɖfoo</code>?</p> <p>Is there a general rule?</p> <p><em>Later:</em></p> <p>Ruby-core is already considering some of the mathematical operators. For example</p> <pre><code>module Kernel def √(num) ... end def ∑(*args) ... end end </code></pre> <p>would allow</p> <pre><code>x = √2 y = ∑(1, 45, ...) </code></pre> <p>I would love to see</p> <pre><code>my_proc = λ { |...| ... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 </code></pre>
[ { "answer_id": 25592, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "String#upcase String#downcase" }, { "answer_id": 25610, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 1, "selected": false, "text": "my_proc = λ { |...| ... }\n\nx ∈ my_enumerable # same as my_enumerable.include?(x)\n\nmy_infinite_range = (1..∞)\n\nreturn 'foo' if x ≠ y\n\n2.21 ≈ 2.2\n" }, { "answer_id": 1434830, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": true, "text": "/tmp/utf_test.rb # encoding: UTF-8\nλ = 'foo'\nputs λ\n\n# from the command line:\n> ruby -KU /tmp/utf_test.rb\nfoo\n # encoding: UTF-8\nKernel.class_eval do\n alias_method :λ, :lambda\nend\n\n(λ { puts 'hi' }).call\n\n# from the command line:\n> ruby -KU /tmp/utf_test.rb:\nhi\n # encoding: UTF-8\nObject.const_set :λ, 'bar'\n\n# from the command line:\n> ruby -KU /tmp/utf_test.rb:\nutf_test.rb:2:in `const_set': wrong constant name λ (NameError)\n # encoding: UTF-8\nObject.const_set :Λ, 'bar'\n\n# from the command line:\n> ruby -KU /tmp/utf_test.rb:\nutf_test.rb:2:in `const_set': wrong constant name Λ (NameError)\n /^[A-Z]/" }, { "answer_id": 4452015, "author": "Adriano Mitre", "author_id": 525555, "author_profile": "https://Stackoverflow.com/users/525555", "pm_score": 1, "selected": false, "text": "\"á\".upcase\n=> \"á\"\n\"á\" == \"Á\".downcase\n=> false\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
22,801
<p>It's about PHP but I've no doubt many of the same comments will apply to other languages.</p> <p>Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?</p> <pre><code>for ($i = 0; $i &lt; 10; $i++) { # code... } foreach ($array as $index =&gt; $value) { # code... } do { # code... } while ($flag == false); </code></pre>
[ { "answer_id": 22810, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 0, "selected": false, "text": "for while Foreach" }, { "answer_id": 22811, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 0, "selected": false, "text": "while(list($key, $value) = each($array)) {\n while ($row = mysql_fetch_array($result)) {\n" }, { "answer_id": 22844, "author": "JeremiahClark", "author_id": 581, "author_profile": "https://Stackoverflow.com/users/581", "pm_score": 0, "selected": false, "text": "$count = 0;\ndo\n{\n ...\n $count++;\n}\nwhile ($count < 10); \n" }, { "answer_id": 23024, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "for foreach IEnumerator for foreach" }, { "answer_id": 23739, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": " foreach ($array as &$value) {\n" }, { "answer_id": 23835, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 4, "selected": true, "text": "for ($i = 0; $i < 10; $i++)\n{\n # code...\n}\n $i = 0;\nwhile ($i < 10)\n{\n # code...\n $i++\n}\n do\n{\n # code...\n}\nwhile ($flag == false);\n foreach ($array as $index => $value)\n{\n # code...\n}\n while (current($array))\n{\n $index = key($array); // to get key of the current element\n $value = $array[$index]; // to get value of current element\n\n # code ... \n\n next($array); // advance the internal array pointer of $array\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
22,807
<p>Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates?</p> <p>Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.</p> <pre><code>AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101)) &lt;= Convert(datetime, Convert(char(10), GetDate(), 101)) AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101)) &gt;= Convert(datetime, Convert(char(10), GetDate(), 101)) </code></pre>
[ { "answer_id": 22809, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": -1, "selected": false, "text": "ep.EffectiveStartDate BETWEEN @date1 AND @date2\n declare @date1 datetime, @date2 datetime; \nset @date1 = cast('10/1/2000' as datetime) \nset @date2 = cast('10/1/2020' as datetime)\n" }, { "answer_id": 22824, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 1, "selected": false, "text": "set @date2 = '20201001'\n select dateadd(d, datediff(d, 0, CURRENT_TIMESTAMP), 0)\n" }, { "answer_id": 4799464, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 0, "selected": false, "text": "AND DateDiff(Day, 0, GetDate()) + 1 > ep.EffectiveStartDate\nAND DateDiff(Day, 0, GetDate()) < ep.EffectiveEndDate\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2526/" ]
22,814
<p>I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found <a href="http://www.testingreflections.com/node/view/3424" rel="noreferrer">Fridz Onion's ViewState Decoder</a> but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy &amp; paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate?</p>
[ { "answer_id": 10605023, "author": "Sameer Alibhai", "author_id": 2343, "author_profile": "https://Stackoverflow.com/users/2343", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections;\nusing System.Text;\nusing System.IO;\nusing System.Web.UI;\n\n\nnamespace ViewStateArticle.ExtendedPageClasses\n{\n /// <summary>\n /// Parses the view state, constructing a viaully-accessible object graph.\n /// </summary>\n public class ViewStateParser\n {\n // private member variables\n private TextWriter tw;\n private string indentString = \" \";\n\n #region Constructor\n /// <summary>\n /// Creates a new ViewStateParser instance, specifying the TextWriter to emit the output to.\n /// </summary>\n public ViewStateParser(TextWriter writer)\n {\n tw = writer;\n }\n #endregion\n\n #region Methods\n #region ParseViewStateGraph Methods\n /// <summary>\n /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.\n /// </summary>\n /// <param name=\"viewState\">The view state object to start parsing at.</param>\n public virtual void ParseViewStateGraph(object viewState)\n {\n ParseViewStateGraph(viewState, 0, string.Empty); \n }\n\n /// <summary>\n /// Emits a readable version of the view state to the TextWriter passed into the object's constructor.\n /// </summary>\n /// <param name=\"viewStateAsString\">A base-64 encoded representation of the view state to parse.</param>\n public virtual void ParseViewStateGraph(string viewStateAsString)\n {\n // First, deserialize the string into a Triplet\n LosFormatter los = new LosFormatter();\n object viewState = los.Deserialize(viewStateAsString);\n\n ParseViewStateGraph(viewState, 0, string.Empty); \n }\n\n /// <summary>\n /// Recursively parses the view state.\n /// </summary>\n /// <param name=\"node\">The current view state node.</param>\n /// <param name=\"depth\">The \"depth\" of the view state tree.</param>\n /// <param name=\"label\">A label to display in the emitted output next to the current node.</param>\n protected virtual void ParseViewStateGraph(object node, int depth, string label)\n {\n tw.Write(System.Environment.NewLine);\n\n if (node == null)\n {\n tw.Write(String.Concat(Indent(depth), label, \"NODE IS NULL\"));\n } \n else if (node is Triplet)\n {\n tw.Write(String.Concat(Indent(depth), label, \"TRIPLET\"));\n ParseViewStateGraph(((Triplet) node).First, depth+1, \"First: \");\n ParseViewStateGraph(((Triplet) node).Second, depth+1, \"Second: \");\n ParseViewStateGraph(((Triplet) node).Third, depth+1, \"Third: \");\n }\n else if (node is Pair)\n {\n tw.Write(String.Concat(Indent(depth), label, \"PAIR\"));\n ParseViewStateGraph(((Pair) node).First, depth+1, \"First: \");\n ParseViewStateGraph(((Pair) node).Second, depth+1, \"Second: \");\n }\n else if (node is ArrayList)\n {\n tw.Write(String.Concat(Indent(depth), label, \"ARRAYLIST\"));\n\n // display array values\n for (int i = 0; i < ((ArrayList) node).Count; i++)\n ParseViewStateGraph(((ArrayList) node)[i], depth+1, String.Format(\"({0}) \", i));\n }\n else if (node.GetType().IsArray)\n {\n tw.Write(String.Concat(Indent(depth), label, \"ARRAY \"));\n tw.Write(String.Concat(\"(\", node.GetType().ToString(), \")\"));\n IEnumerator e = ((Array) node).GetEnumerator();\n int count = 0;\n while (e.MoveNext())\n ParseViewStateGraph(e.Current, depth+1, String.Format(\"({0}) \", count++));\n }\n else if (node.GetType().IsPrimitive || node is string)\n {\n tw.Write(String.Concat(Indent(depth), label));\n tw.Write(node.ToString() + \" (\" + node.GetType().ToString() + \")\");\n }\n else\n {\n tw.Write(String.Concat(Indent(depth), label, \"OTHER - \"));\n tw.Write(node.GetType().ToString());\n }\n }\n #endregion\n\n /// <summary>\n /// Returns a string containing the <see cref=\"IndentString\"/> property value a specified number of times.\n /// </summary>\n /// <param name=\"depth\">The number of times to repeat the <see cref=\"IndentString\"/> property.</param>\n /// <returns>A string containing the <see cref=\"IndentString\"/> property value a specified number of times.</returns>\n protected virtual string Indent(int depth)\n {\n StringBuilder sb = new StringBuilder(IndentString.Length * depth);\n for (int i = 0; i < depth; i++)\n sb.Append(IndentString);\n\n return sb.ToString();\n }\n #endregion\n\n #region Properties\n /// <summary>\n /// Specifies the indentation to use for each level when displaying the object graph.\n /// </summary>\n /// <value>A string value; the default is three blank spaces.</value>\n public string IndentString\n {\n get\n {\n return indentString;\n }\n set\n {\n indentString = value;\n }\n }\n #endregion\n }\n}\n private void btnParse_Click(object sender, System.EventArgs e)\n {\n // parse the viewState\n StringWriter writer = new StringWriter();\n ViewStateParser p = new ViewStateParser(writer);\n\n p.ParseViewStateGraph(txtViewState.Text);\n ltlViewState.Text = writer.ToString();\n }\n" }, { "answer_id": 17371001, "author": "Basil", "author_id": 2208657, "author_profile": "https://Stackoverflow.com/users/2208657", "pm_score": 2, "selected": false, "text": "public static StateBag LoadViewState(string viewState)\n {\n System.Web.UI.Page converterPage = new System.Web.UI.Page();\n HiddenFieldPageStatePersister persister = new HiddenFieldPageStatePersister(new Page());\n Type utilClass = typeof(System.Web.UI.BaseParser).Assembly.GetType(\"System.Web.UI.Util\");\n if (utilClass != null && persister != null)\n {\n MethodInfo method = utilClass.GetMethod(\"DeserializeWithAssert\", BindingFlags.NonPublic | BindingFlags.Static);\n if (method != null)\n {\n PropertyInfo formatterProperty = persister.GetType().GetProperty(\"StateFormatter\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (formatterProperty != null)\n {\n IStateFormatter formatter = (IStateFormatter)formatterProperty.GetValue(persister, null);\n if (formatter != null)\n {\n FieldInfo pageField = formatter.GetType().GetField(\"_page\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (pageField != null)\n {\n pageField.SetValue(formatter, null);\n try\n {\n Pair pair = (Pair)method.Invoke(null, new object[] { formatter, viewState });\n if (pair != null)\n {\n MethodInfo loadViewState = converterPage.GetType().GetMethod(\"LoadViewStateRecursive\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (loadViewState != null)\n {\n FieldInfo postback = converterPage.GetType().GetField(\"_isCrossPagePostBack\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (postback != null)\n {\n postback.SetValue(converterPage, true);\n }\n FieldInfo namevalue = converterPage.GetType().GetField(\"_requestValueCollection\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (namevalue != null)\n {\n namevalue.SetValue(converterPage, new NameValueCollection());\n }\n loadViewState.Invoke(converterPage, new object[] { ((Pair)((Pair)pair.First).Second) });\n FieldInfo viewStateField = typeof(Control).GetField(\"_viewState\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (viewStateField != null)\n {\n return (StateBag)viewStateField.GetValue(converterPage);\n }\n }\n }\n }\n catch (Exception ex)\n {\n if (ex != null)\n {\n\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n" }, { "answer_id": 63395981, "author": "henrry", "author_id": 12780274, "author_profile": "https://Stackoverflow.com/users/12780274", "pm_score": 2, "selected": false, "text": "pip install viewstate >>> from viewstate import ViewState\n>>> base64_encoded_viewstate = '/wEPBQVhYmNkZQ9nAgE='\n>>> vs = ViewState(base64_encoded_viewstate)\n>>> vs.decode()\n('abcde', (True, 1))\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
22,816
<p>I know the following libraries for drawing charts in an SWT/Eclipse RCP application:</p> <ul> <li><a href="http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html" rel="noreferrer">Eclipse BIRT Chart Engine</a> (Links to an article on how to use it)</li> <li><a href="http://www.jfree.org/jfreechart/" rel="noreferrer">JFreeChart</a></li> </ul> <p>Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...</p>
[ { "answer_id": 43112, "author": "Ryan P", "author_id": 1539, "author_profile": "https://Stackoverflow.com/users/1539", "pm_score": 5, "selected": true, "text": "Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);\nFrame frame = SWT_AWT.new_Frame(comp);\nJFreeChart chart = createChart();\nChartPanel chartPanel = new ChartPanel(chart);\nframe.add(chartPanel);\n" }, { "answer_id": 32049679, "author": "Stefan", "author_id": 2876079, "author_profile": "https://Stackoverflow.com/users/2876079", "pm_score": 1, "selected": false, "text": "package org.treez.results.chartist;\n\nimport java.net.URL;\n\nimport javafx.application.Application;\nimport javafx.concurrent.Worker;\nimport javafx.geometry.HPos;\nimport javafx.geometry.VPos;\nimport javafx.scene.Scene;\nimport javafx.scene.layout.Region;\nimport javafx.scene.paint.Color;\nimport javafx.scene.web.WebEngine;\nimport javafx.scene.web.WebView;\nimport javafx.stage.Stage;\nimport netscape.javascript.JSObject;\n\npublic class WebViewSample extends Application {\n\n private Scene scene;\n\n @Override\n public void start(Stage stage) {\n // create the scene\n stage.setTitle(\"Web View\");\n Browser browser = new Browser();\n scene = new Scene(browser, 750, 500, Color.web(\"#666970\"));\n stage.setScene(scene);\n stage.show();\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n}\n\nclass Browser extends Region {\n\n final WebView browser = new WebView();\n\n final WebEngine webEngine = browser.getEngine();\n\n public Browser() {\n\n //add the web view to the scene\n getChildren().add(browser);\n\n //add finished listener\n webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {\n if (newState == Worker.State.SUCCEEDED) {\n executeJavaScript();\n }\n });\n\n // load the web page\n URL url = WebViewSample.class.getResource(\"chartist.html\");\n String urlPath = url.toExternalForm();\n webEngine.load(urlPath);\n\n }\n\n private void executeJavaScript() {\n\n String script = \"var chartist = new Chartist.Line(\" + \"'#chart',\" + \" \" + \"{\"\n + \" labels: [1, 2, 3, 4, 5, 6, 7, 8],\" + \"series: [\" + \" [5, 9, 7, 8, 5, 3, 5, 44]\" + \"]\" + \"}, \" + \"\"\n + \"{\" + \" low: 0,\" + \" showArea: true\" + \"}\" + \"\" + \");\" + \" var get = function(){return chartist};\";\n\n webEngine.executeScript(script);\n\n Object resultJs = webEngine.executeScript(\"get()\");\n\n //get line\n JSObject line = (JSObject) resultJs;\n String getKeys = \"{var keys = [];for (var key in this) {keys.push(key);} keys;}\";\n JSObject linekeys = (JSObject) line.eval(getKeys);\n\n JSObject options = (JSObject) line.eval(\"this.options\");\n JSObject optionkeys = (JSObject) options.eval(getKeys);\n\n options.eval(\"this.showLine=false\");\n\n }\n\n @Override\n protected void layoutChildren() {\n double w = getWidth();\n double h = getHeight();\n layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);\n }\n\n @Override\n protected double computePrefWidth(double height) {\n return 750;\n }\n\n @Override\n protected double computePrefHeight(double width) {\n return 500;\n }\n}\n <!DOCTYPE html>\n<html>\n<head>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"chartist.min.css\"> \n</head>\n<body>\n <div class=\"ct-chart\" id=\"chart\"></div>\n <script type=\"text/javascript\" src=\"chartist.js\"></script>\n</body>\n</html>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1793/" ]
22,836
<p>In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?</p> <p>I usually just copy the string to a new variable then bind it to the <code>s///</code> regex that does the replacement on the new string, but I was wondering if there is a better way to do this?</p> <pre><code>$newstring = $oldstring; $newstring =~ s/foo/bar/g; </code></pre>
[ { "answer_id": 22896, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 9, "selected": true, "text": "(my $newstring = $oldstring) =~ s/foo/bar/g;\n /r my $newstring = $oldstring =~ s/foo/bar/gr; \n g perldoc perlrequick" }, { "answer_id": 24090, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": false, "text": "(my $newstring = $oldstring) =~ s/foo/bar/g;\n my $newstring = $oldstring;\n$newstring =~ s/foo/bar/g;\n /r use 5.013;\n#...\nmy $newstring = $oldstring =~ s/foo/bar/gr;\n" }, { "answer_id": 55786, "author": "Tim Kennedy", "author_id": 5699, "author_profile": "https://Stackoverflow.com/users/5699", "pm_score": 0, "selected": false, "text": "use strict; my ($newstring = $oldstring) =~ s/foo/bar/;\n Can't declare scalar assignment in \"my\" at script.pl line 7, near \") =~\"\nExecution of script.pl aborted due to compilation errors.\n use strict; use strict; #!/usr/bin/env perl -wT\n\nuse strict;\n\nmy $oldstring = \"foo one foo two foo three\";\nmy $newstring = $oldstring;\n$newstring =~ s/foo/bar/g;\n\nprint \"$oldstring\",\"\\n\";\nprint \"$newstring\",\"\\n\";\n" }, { "answer_id": 62500, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 5, "selected": false, "text": "use strict (my $new = $original) =~ s/foo/bar/;\n" }, { "answer_id": 35829163, "author": "JoGotta", "author_id": 3037683, "author_profile": "https://Stackoverflow.com/users/3037683", "pm_score": 0, "selected": false, "text": "my $oldstring = \"replace donotreplace replace donotreplace replace donotreplace\";\n\nmy $newstring = $oldstring;\n$newstring =~ s/replace/newword/g; # inplace replacement\n\nprint $newstring;\n%: newword donotreplace newword donotreplace newword donotreplace\n" }, { "answer_id": 44172761, "author": "textral", "author_id": 1206102, "author_profile": "https://Stackoverflow.com/users/1206102", "pm_score": 2, "selected": false, "text": "map map my @orig = ('this', 'this sucks', 'what is this?');\nmy @list = map { s/this/that/; $_ } map { $_ } @orig;\n# @orig unmodified\n" }, { "answer_id": 67513243, "author": "ngn999", "author_id": 461293, "author_profile": "https://Stackoverflow.com/users/461293", "pm_score": 0, "selected": false, "text": "sprintf(\"%s\", $oldstring)" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
22,879
<p>I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?</p>
[ { "answer_id": 22908, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 4, "selected": true, "text": "Provider=Microsoft.ACE.OLEDB.12.0;\n Data Source=c:\\path\\to\\myfile.xlsx;\n Extended Properties=\\\"Excel 12.0 Xml;IMEX=1\\\";\n" }, { "answer_id": 677697, "author": "cjk", "author_id": 52201, "author_profile": "https://Stackoverflow.com/users/52201", "pm_score": 1, "selected": false, "text": "HKLM\\Software\\Microsoft\\Jet\\4.0\\Engines\\Excel\\TypeGuessRows \n" }, { "answer_id": 20784334, "author": "Rajans", "author_id": 3136602, "author_profile": "https://Stackoverflow.com/users/3136602", "pm_score": 0, "selected": false, "text": "00022556 '=\" 00022556\"'" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
22,880
<p>Specifically this is regarding when using a client session cookie to identify a session on the server.</p> <p>Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie?</p> <p>And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie?</p> <p>If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?</p>
[ { "answer_id": 6532807, "author": "Nima", "author_id": 822755, "author_profile": "https://Stackoverflow.com/users/822755", "pm_score": -1, "selected": false, "text": "$ip=$_SERVER['REMOTE_ADDER'];\n$_SESSEION['ip']=$ip;\n" }, { "answer_id": 19726572, "author": "Alexandru", "author_id": 2750086, "author_profile": "https://Stackoverflow.com/users/2750086", "pm_score": 4, "selected": false, "text": " //set a token cookie if one not exist\n if(!isset($_COOKIE['user_token'])){\n //generate a random string for cookie value\n $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));\n\n //set a session variable with that random string\n $_SESSION['user_token'] = $cookie_token;\n //set cookie with rand value\n setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);\n }\n\n //set a sesison variable with request of www.example.com\n if(!isset($_SESSION['request'])){\n $_SESSION['request'] = -1;\n }\n //increment $_SESSION['request'] with 1 for each request at www.example.com\n $_SESSION['request']++;\n\n //verify if $_SESSION['user_token'] it's equal with $_COOKIE['user_token'] only for $_SESSION['request'] > 0\n if($_SESSION['request'] > 0){\n\n // if it's equal then regenerete value of token cookie if not then destroy_session\n if($_SESSION['user_token'] === $_COOKIE['user_token']){\n $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));\n\n $_SESSION['user_token'] = $cookie_token;\n\n setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);\n }else{\n //code for session_destroy\n }\n\n }\n\n //prevent session hijaking with browser user agent\n if(!isset($_SESSION['user_agent'])){\n $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];\n }\n\n if($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']){\n die('session hijaking - user agent');\n }\n" }, { "answer_id": 20361967, "author": "theironyis", "author_id": 3063333, "author_profile": "https://Stackoverflow.com/users/3063333", "pm_score": 4, "selected": false, "text": "// Collect this information on every request\n$aip = $_SERVER['REMOTE_ADDR'];\n$bip = $_SERVER['HTTP_X_FORWARDED_FOR'];\n$agent = $_SERVER['HTTP_USER_AGENT'];\nsession_start();\n\n// Do this each time the user successfully logs in.\n$_SESSION['ident'] = hash(\"sha256\", $aip . $bip . $agent);\n\n// Do this every time the client makes a request to the server, after authenticating\n$ident = hash(\"sha256\", $aip . $bip . $agent);\nif ($ident != $_SESSION['ident'])\n{\n end_session();\n header(\"Location: login.php\");\n // add some fancy pants GET/POST var headers for login.php, that lets you\n // know in the login page to notify the user of why they're being challenged\n // for login again, etc.\n}\n" }, { "answer_id": 48724010, "author": "Jzf", "author_id": 2681197, "author_profile": "https://Stackoverflow.com/users/2681197", "pm_score": 2, "selected": false, "text": "@Override\nprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n HttpSession session = request.getSession();\n String sessionKey = (String) session.getAttribute(\"sessionkey\");\n String remoteAddr = request.getRemoteAddr();\n int remotePort = request.getRemotePort();\n String sha256Hex = DigestUtils.sha256Hex(remoteAddr + remotePort);\n if (sessionKey == null || sessionKey.isEmpty()) {\n session.setAttribute(\"sessionkey\", sha256Hex);\n // save mapping to memory to track which user attempted\n Application.userSessionMap.put(sha256Hex, remoteAddr + remotePort);\n } else if (!sha256Hex.equals(sessionKey)) {\n session.invalidate();\n response.getWriter().append(Application.userSessionMap.get(sessionKey));\n response.getWriter().append(\" attempted to hijack session id \").append(request.getRequestedSessionId()); \n response.getWriter().append(\"of user \").append(Application.userSessionMap.get(sha256Hex));\n return;\n }\n response.getWriter().append(\"Valid Session\\n\");\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
22,909
<p>I want to show HTML content inside Flash. Is there some way to do this? I am talking about full blown HTML (with JavaScript if possible).</p>
[ { "answer_id": 22921, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "htmlText" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
22,935
<p>Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file? </p> <p>I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...</p>
[ { "answer_id": 22948, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": true, "text": "SELECT * INTO NewTablenNmeHere\nFROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', \n'Excel 8.0;Database=C:\\testing.xls','SELECT * FROM [Sheet1$]') \n" }, { "answer_id": 22951, "author": "Krantz", "author_id": 2528, "author_profile": "https://Stackoverflow.com/users/2528", "pm_score": 1, "selected": false, "text": "BULK \nINSERT CSVTest\n FROM 'c:\\csvtest.txt'\n WITH\n (\n FIELDTERMINATOR = ',',\n ROWTERMINATOR = '\\n'\n )\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39040/" ]
22,976
<p>I've got a JavaScript "object", built this way:</p> <pre><code>function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; } ... </code></pre> <p>I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? </p> <p>I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. </p> <p>Thanks rp</p>
[ { "answer_id": 22998, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 2, "selected": false, "text": "namespace.foo = function foo() {...}\nnamespace.foo.prototype.getLength = function() { ... }\n (function() {\n function foo() { ... }\n foo.prototype...\n namespace.foo = foo;\n})();\n" }, { "answer_id": 23089, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": true, "text": "if(!MyNamespace) MyNamespace = {};\n\nMyNamespace.foo = function() {\n this.length = 0;\n};\nMyNamespace.foo.prototype.getLength = function() {\n return this.length;\n};\n" }, { "answer_id": 23207, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "var namespace = {\n this.foo: function(){\n ...\n },\n this.foo.prototype.getLength: function(){\n ...\n }\n}\n loadPackage = function(){\n var path = arguments[0];\n for(var i=1; i<arguments.length; i++){\n if(!path[arguments[i]]){\n path[arguments[i]] = {};\n }\n path = path[arguments[i]];\n }\n return path;\n}\n\nloadPackage(this, \"com\", \"google\", \"mail\") = {\n username: \"gundersen\",\n login: function(password){\n ...\n }\n}\nthis.com.google.mail.login(\"mySecretPassword\");\n" }, { "answer_id": 23468, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "if( typeof( rpNameSpace ) == \"undefined\" ) rpNameSpace = {};\n\nrpNameSpace.foo = function() {\n this.length = 613;\n}\nrpNameSpace.foo.prototype.getLength = function() {\n return this.length * 2;\n}\n var x = new rpNameSpace.foo()\n\ndisplay( x.getLength() );\n" }, { "answer_id": 15820688, "author": "Tengiz", "author_id": 523949, "author_profile": "https://Stackoverflow.com/users/523949", "pm_score": -1, "selected": false, "text": "bob.ns.setNs('myApp.myFunctions', { \n say: function(msg) { \n console.log(msg); \n } \n}); \n\n//sub-namespace\nbob.ns.setNs('myApp.myFunctions.mySubFunctions', { \n hello: function(name) { \n myApp.myFunctions.say('Hello, ' + name); \n } \n}); \n\n//call:\nmyApp.myFunctions.mySubFunctions.hello('Bob'); \n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
22,979
<p>I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive.</p> <p>Any ideas?</p>
[ { "answer_id": 451160, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 2, "selected": false, "text": "System.Data.Sql.SqlDataSourceEnumerator" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178/" ]
22,988
<p>I have several "ASP:TextBox" controls on a form (about 20).<br> When the form loads, the text boxes are populated from a database.<br> The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic).<br> All but 1 of the text boxes work as intended.</p> <p>The odd box out, upon postback, does not contain the updated value that the user typed into the box.<br> When debugging the application, it is clear that <code>myTextBox.Text</code> reflects the old, pre-populated value, not the new, user-supplied value.<br> Every other box properly shows their respective user-supplied values.</p> <p>I did find a workaround.<br> My solution was to basically extract the text box's value out of the <code>Request.Form</code> object: <code>Request.Form[myTextBox.UniqueID]</code>, which does contain the user-supplied value.</p> <p>What could be going on, here?<br> As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it.<br> The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET.</p>
[ { "answer_id": 23058, "author": "Jon Erickson", "author_id": 1950, "author_profile": "https://Stackoverflow.com/users/1950", "pm_score": 3, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (!Page.IsPostBack)\n {\n // populate text boxes from database\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/418/" ]
23,027
<p>While setting up CruiseControl, I added a buildpublisher block to the publisher tasks:</p> <pre><code>&lt;buildpublisher&gt; &lt;sourceDir&gt;C:\MyBuild\&lt;/sourceDir&gt; &lt;publishDir&gt;C:\MyBuildPublished\&lt;/publishDir&gt; &lt;alwaysPublish&gt;false&lt;/alwaysPublish&gt; &lt;/buildpublisher&gt; </code></pre> <p>This works, but it copies the entire file contents of the build, I only want to copy the DLL's and .aspx pages, I don't need the source code to get published.</p> <p>Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?</p>
[ { "answer_id": 32681, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 1, "selected": false, "text": "<MSBuild Projects=\"@(VSProjects)\"\n Properties=\"Configuration=$(Configuration)\">\n <Output TaskParameter=\"TargetOutputs\" ItemName=\"BuildTargetOutputs\"/>\n</MSBuild>\n <Copy SourceFiles=\"@(BuildTargetOutputs)\" \n DestinationFolder=\"bin\"\n SkipUnchangedFiles=\"true\" />\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
23,083
<p>In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put <code>this</code> in the window's user data area via <code>SetWindowLong(hwnd, GWL_USERDATA, this)</code>, which allows us to have an MFC-like callback or a tightly integrated <code>WndProc</code>, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?</p>
[ { "answer_id": 23101, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 6, "selected": true, "text": "LONG_PTR SetWindowLongPtr( \n HWND hWnd,\n int nIndex,\n LONG_PTR dwNewLong\n);\n SetWindowLongPtr(hWnd, GWLP_USERDATA, this);\n LONG_PTR GetWindowLongPtr( \n HWND hWnd,\n int nIndex\n);\n LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);\nMyObject* pMyObject = (MyObject*)lpUserData;\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2354/" ]
23,094
<p>What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?</p>
[ { "answer_id": 24334, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": true, "text": "Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));\nResponse.Cache.SetCacheability(HttpCacheability.Public);\nResponse.Cache.SetValidUntilExpires(false);\nResponse.Cache.VaryByParams[\"Category\"] = true;\n\nif (Response.Cache.VaryByParams[\"Category\"])\n{\n //...\n}\n Response.CacheControl = \"No-Cache\";\n Response.ClearHeaders();\nResponse.AppendHeader(\"Cache-Control\", \"no-cache\"); //HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"private\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"no-store\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"must-revalidate\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"max-stale=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Cache-Control\", \"post-check=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Cache-Control\", \"pre-check=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Pragma\", \"no-cache\"); // HTTP 1.1 \nResponse.AppendHeader(\"Keep-Alive\", \"timeout=3, max=993\"); // HTTP 1.1 \nResponse.AppendHeader(\"Expires\", \"Mon, 26 Jul 1997 05:00:00 GMT\"); // HTTP 1.1 \n" }, { "answer_id": 217096, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "Cache-control: must-revalidate" }, { "answer_id": 28466691, "author": "Steven de Salas", "author_id": 448568, "author_profile": "https://Stackoverflow.com/users/448568", "pm_score": 0, "selected": false, "text": "Response.Cache.SetCacheability(HttpCacheability.NoCache | HttpCacheability.Private);\nResponse.Cache.AppendCacheExtension(\"must-revalidate\");\nResponse.Cache.AppendCacheExtension(\"max-age=0\");\nResponse.Cache.SetNoStore();\n Page_Load()" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
23,102
<p>I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site.</p>
[ { "answer_id": 23116, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": false, "text": "bool UserCredentialsOK(User user)\n{\n\n if (user.Name == \"modesty\")\n return false;\n else\n // perform other checks\n} \n" }, { "answer_id": 24142, "author": "Steve M", "author_id": 1693, "author_profile": "https://Stackoverflow.com/users/1693", "pm_score": 2, "selected": false, "text": "$query = \"SELECT field1, field2 FROM table1 WHERE field1 = '\" . myescapefunc($userinput) . \"'\";\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
23,106
<p>What is the best method to parse multiple, discrete, custom XML documents with Java?</p>
[ { "answer_id": 23121, "author": "jcsalterego", "author_id": 1416, "author_profile": "https://Stackoverflow.com/users/1416", "pm_score": 2, "selected": false, "text": "org.xml.sax.XMLReader" }, { "answer_id": 5299265, "author": "Valdis", "author_id": 438990, "author_profile": "https://Stackoverflow.com/users/438990", "pm_score": 2, "selected": false, "text": "import java.net.URL;\n\nimport org.dom4j.Document;\nimport org.dom4j.DocumentException;\nimport org.dom4j.io.SAXReader;\n\npublic class Foo {\n\n public Document parse(URL url) throws DocumentException {\n SAXReader reader = new SAXReader();\n Document document = reader.read(url);\n return document;\n }\n}\n public void get_author(Document document) {\n Node node = document.selectSingleNode( \"//AppealRequestProcessRequest/author\" );\n String author = node.getText();\n return author;\n}\n" }, { "answer_id": 36190454, "author": "vtd-xml-author", "author_id": 129732, "author_profile": "https://Stackoverflow.com/users/129732", "pm_score": 0, "selected": false, "text": "import com.ximpleware.*;\n\npublic class extractValue{\n public static void main(String s[]) throws VTDException, IOException{\n VTDGen vg = new VTDGen();\n if (!vg.parseFile(\"input.xml\", false));\n VTDNav vn = vg.getNav();\n AutoPilot ap = new AutoPilot(vn);\n ap.selectXPath(\"/aa/bb[name='k1']/value\");\n int i=0;\n while ((i=ap.evalXPath())!=-1){\n System.out.println(\" value ===>\"+vn.toString(i));\n } \n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828/" ]
23,124
<p>As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?</p>
[ { "answer_id": 23131, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "<?php\n sleep(10); //sleep for 10 seconds.\n print \"This script has finished.\";\n>\n" }, { "answer_id": 23227, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "System.Threading.Thread.Sleep(timeoutMilliseconds);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272/" ]
23,169
<p>When using Groovy <code>MarkupBuilder</code>, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag <em>"text"</em> to do the output. Is there a better way to write this code?</p> <pre><code>li { text("${type.getAlias()} blah blah ") function1(type.getXYZ()) if (type instanceof Class1) { text(" implements ") ft.getList().each { if (it == '') return text(it) if (!function2(type, it)) text(", ") } } } </code></pre>
[ { "answer_id": 23734, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "void text(n){\n builder.yield n\n}\n" }, { "answer_id": 81815, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "mkp.yield src.p {\n mkp.yield 'Some element that has a '\n strong 'child element'\n mkp.yield ' which seems pretty basic.'\n}\n <p>Some element that has a <strong>child element</strong> which seems pretty basic.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
23,175
<p>This is mostly geared toward desktop application developers. <br />How do I design a caching block which plays nicely with the GC? <br />How do I tell the GC that I have just done a cache sweep and it is time to do a GC? <br />How do I get an accurate measure of when it is time to do a cache sweep?</p> <p>Are there any prebuilt caching schemes which I could borrow some ideas from?</p>
[ { "answer_id": 23734, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "void text(n){\n builder.yield n\n}\n" }, { "answer_id": 81815, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "mkp.yield src.p {\n mkp.yield 'Some element that has a '\n strong 'child element'\n mkp.yield ' which seems pretty basic.'\n}\n <p>Some element that has a <strong>child element</strong> which seems pretty basic.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
23,178
<p>Is there a .NET variable that returns the "All Users" directory?</p>
[ { "answer_id": 23194, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 4, "selected": true, "text": "system.environment System.Environment.GetEnvironmentVariable(\"ALLUSERSPROFILE\")\n" }, { "answer_id": 23202, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 1, "selected": false, "text": "Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
23,190
<p>I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are &quot;cared about.&quot;</p> <p>Example: Consider the following example...</p> <pre> Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. </pre> <p>I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful.</p> <h3>Update:</h3> <p>Just got home. Here is some info to answer your questions:</p> <ol> <li>Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out.</li> <li>@jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).</li> <li>I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a &quot;driver&quot; function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array.</li> <li>The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).</li> </ol> <p>Thanks everyone for your imput.</p>
[ { "answer_id": 23275, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 0, "selected": false, "text": "[1] --> [1,2,3,4,5,6,...]\n[2] --> [1,2,3,4,5,6,...]\n[3] --> [1,2,3,4,5,6,...]\n[4] --> [1,2,3,4,5,6,...]\n[5] --> [1,2,3,4,5,6,...]\n . .\n . .\n . .\n sizeof(array)/sizeof(int) sum( n_matrix, depth )\n running_total = 0\n if depth = 0 then\n foreach element in the array\n running_total += elm\n else \n foreach element in the array\n running_total += sum( elm , depth-1 )\n return running_total\n" }, { "answer_id": 23282, "author": "Marc Reside", "author_id": 1429, "author_profile": "https://Stackoverflow.com/users/1429", "pm_score": 2, "selected": false, "text": "array_care[4][4][4] array_care[4][4][4] input[4][4][4][4][4][4][4][4] int dim[8] = {0,0,0,0,0,0,0,0};\n int increase_index_order[8] = {7,5,4,3,0,6,2,1};\nint i = 0;\n bool terminate=false;\n while (terminate)\n{\narray_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]];\n\nwhile ((dim[increase_index_order[i]] = 3) && (i < 8))\n{\ndim[increase_index_order[i]]=0;\ni++;\n}\n\nif (i < 8) {\ndim[increase_index_order[i]]++; i=0;\n} else {\nterminate=true;\n}\n}\n" }, { "answer_id": 23307, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 0, "selected": false, "text": "x = number_of_dimensions;\nwhile (x > 1)\n{\n switch (x)\n {\n case 20:\n reduce20DimensionArray();\n x--;\n break;\n case 19:\n .....\n }\n}\n" }, { "answer_id": 23442, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <boost/foreach.hpp>\n#include <vector>\n\nint sum(int x) {\n return x;\n}\n\ntemplate <class T, unsigned N>\nint sum(const T (&x)[N]) {\n int r = 0;\n for(int i = 0; i < N; ++i) {\n r += sum(x[i]);\n }\n return r;\n}\n\ntemplate <class T, unsigned N>\nstd::vector<int> reduce(const T (&x)[N]) {\n std::vector<int> result;\n for(int i = 0; i < N; ++i) {\n result.push_back(sum(x[i]));\n }\n return result;\n}\n\nint main() {\n int x[][2][2] = {\n { { 1, 2 }, { 3, 4 } },\n { { 5, 6 }, { 7, 8 } }\n };\n\n BOOST_FOREACH(int v, reduce(x)) {\n std::cout<<v<<\"\\n\";\n }\n}\n" }, { "answer_id": 25002, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 3, "selected": true, "text": "\ndef iter_arr(array):\n sum = 0\n for i in array:\n if type(i) == type(list()):\n sum = sum + iter_arr(i)\n else:\n sum = sum + i\n return sum \n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
23,197
<p>I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.</p> <p>Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative. </p> <p>Anyway, the device file path is of the form: </p> <pre> 1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". </pre> <p>And I'm trying to open it using code, like:</p> <pre><code>// First, open it with minimum permissions, this device may not be ours. // we'll re-open it later in read/write hid_device_ref = CreateFile( device_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); </code></pre> <p>I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.</p>
[ { "answer_id": 23219, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "//Open file on the device\ndeviceHandle = \n CreateFile (deviceDetail->DevicePath, \n GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, \n NULL, OPEN_EXISTING, 0, NULL);\n" }, { "answer_id": 735453, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 1, "selected": false, "text": "HidD_SetFeature HidD_GetFeature" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2146/" ]
23,209
<p>I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:</p> <pre><code>cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl -DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio 9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c </code></pre> <p>The code compiles cleanly. The link command is:</p> <pre><code>link -debug -nologo -machine:IX86 -verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib msvcrt.lib oldnames.lib kernel32.lib winmm.lib [snip large list of dependencies] D:\src\lib\app_main.obj -out:mymain.exe </code></pre> <p>The errors that I'm getting are:</p> <pre><code>app_main.obj : error LNK2019: unresolved external symbol "_\_declspec(dllimport) public: void __thiscall std::locale::facet::_Register(void)" (__imp_?_Register@facet@locale@std@@QAEXXZ) referenced in function "class std::ctype&lt;char&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;char&gt; (class std::locale const &amp;)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype&lt;char&gt;::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype&lt;char&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;char&gt; (class std::locale const &amp;)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype&lt;unsigned short&gt;::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype&lt;unsigned short&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;unsigned short&gt; &gt;(class std::locale const &amp;)" (??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z) mymain.exe : fatal error LNK1120: 3 unresolved externals </code></pre> <p>Notice that these errors are coming from the legacy code, not my code - app_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?</p>
[ { "answer_id": 44886, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 2, "selected": false, "text": "DEFAULTLIB:\"libc\npmtd\" /DEFAULTLI\nB:\"uuid.lib\" /DE\nFAULTLIB:\"uuid.l\nib\" /include:?id\n@?$num_put@DV?$o\nstreambuf_iterat\nor@DU?$char_trai\nts@D@std@@@std@@\n@std@@2V0locale@\n2@A /include:?id\n@?$numpunct@D@st\nd@@2V0locale@2@A\n /DEFAULTLIB:\"LI\nBCMTD\" /DEFAULTL\nIB:\"OLDNAMES\" /E\nDITANDCONTINUE \n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322/" ]
23,216
<p>I can never remember the differences in regular expression syntax used by tools like <a href="http://en.wikipedia.org/wiki/Grep" rel="noreferrer">grep</a> and <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a>, or languages like Python and PHP. Generally, Perl has the most expansive syntax, but I'm often hamstrung by the limitations of even <code>egrep</code> ("extended" <code>grep</code>).</p> <p>Is there a site that lists the differences in a concise and easy-to-read fashion?</p>
[ { "answer_id": 23232, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 4, "selected": false, "text": "grep egrep" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
23,217
<p>I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the <code>javascript:</code> prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:</p> <pre><code>onchange="javascript: myFunction(this)" </code></pre> <p>and</p> <pre><code>onchange="myFunction(this)" </code></pre> <p>?</p>
[ { "answer_id": 23222, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 5, "selected": true, "text": "javascript: href href onclick <a href=\"javascript:someFunction();\">Blah</a>\n <a href=\"\" onclick=\"someFunction();\">Blah</a>\n" }, { "answer_id": 23237, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": false, "text": "javascript: onChange javascript: javascript:myFunction(this) javascript: myFunction(this)" }, { "answer_id": 23239, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 0, "selected": false, "text": "javascript: onevent href" }, { "answer_id": 23242, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 3, "selected": false, "text": "<a href=\"/non-js-version/\" onclick=\"someFunction(); return false\">Blah</a>\n javascript:" }, { "answer_id": 23244, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "<a href=\"non-ajax.html\" onclick=\"niftyAjax(); return false;\">Ajax me</a>\n var b=document.body;\nif(b&&!document.xmlVersion){\n void(z=document.createElement('script'));\n void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');\n void(b.appendChild(z));\n}else{\n location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)\n}\n <a href=\"javascript:var%20b=document.body;if(b&&!document.xmlVersion){void(z=document.createElement('script'));void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');void(b.appendChild(z));}else{location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)}\">Drag this to your bookmarks, or right click and bookmark it!</a>\n" }, { "answer_id": 23342, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B\n" }, { "answer_id": 23466, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "onchange=\"javascript: myFunction(this)\" onchange=\"myFunction(this)\" href=\"javascript: myFunction(this)\"" }, { "answer_id": 32193, "author": "Russell Leggett", "author_id": 2828, "author_profile": "https://Stackoverflow.com/users/2828", "pm_score": 2, "selected": false, "text": "javascript: vbscript javascript: href=\"javascript:...\"" }, { "answer_id": 43001, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "javascript: HREF" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1680/" ]
23,228
<p>Compare</p> <pre><code>String.Format("Hello {0}", "World"); </code></pre> <p>with</p> <pre><code>"Hello {0}".Format("World"); </code></pre> <p>Why did the .Net designers choose a static method over an instance method? What do you think?</p>
[ { "answer_id": 23248, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 1, "selected": false, "text": "String.Format() Int32.Parse() long.TryParse() StringBuilder StringBuilder.AppendFormat()" }, { "answer_id": 23253, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": -1, "selected": false, "text": "String.Format String.Format" }, { "answer_id": 23426, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "\"Hello {0}\".Format(\"World\"); // this makes it sound like Format *modifies* \n // the string, which is not possible as \n // strings are immutable.\n\nstring[] parts = \"Hello World\".Split(' '); // this however sounds right, \n // because it implies that you \n // split an existing string into \n // two *new* strings.\n" }, { "answer_id": 23978, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "public static string F( this string format, params object[] args )\n{\n return String.Format(format, args);\n}\n String.Format(\"Hello {0}\", Name);\n \"Hello {0}\".F(Name);\n" }, { "answer_id": 24018, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "String foo = new String();\n\nfoo.Format(\"test {0}\",1); // Makes it look like foo should be modified by the Format method. \n\nstring newFoo = String.Format(foo, 1); // Indicates that a new string will be returned, and foo will be unaltered.\n" }, { "answer_id": 24024, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 1, "selected": false, "text": "String.Format(\"Foo {0}\", \"Bar\");\n \"Foo {0}\".Format(\"bar\");\n" }, { "answer_id": 24048, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "Format \"Hello {0}\".ToString(\"Orion\");\n" }, { "answer_id": 24084, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "null null String.Format null" }, { "answer_id": 24143, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 6, "selected": true, "text": "\"{0}\".Format(12);\n new String(\"{0}\").Format(12);\n CString csTemp = \"\";\ncsTemp.Format(\"Some string: %s\", szFoo);\n" }, { "answer_id": 24147, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": ".ToString() double test = 1.54d;\n\n//string.Format pattern\nstring.Format(\"This is a test: {0:F1}\", test );\n\n//ToString pattern\n\"This is a test: \" + test.ToString(\"F1\");\n public static string FormatInsert( this string input, params object[] args) {\n return string.Format( input, args );\n}\n\n\"Hello {0}, I have {1} things.\".FormatInsert( \"world\", 3);\n" }, { "answer_id": 27029, "author": "nollidge", "author_id": 2911, "author_profile": "https://Stackoverflow.com/users/2911", "pm_score": 2, "selected": false, "text": "public static class StringExtension\n{\n public static string FormatWith(this string format, params object[] args)\n {\n return String.Format(format, args);\n }\n}\n\npublic class SomeClass\n{\n public string SomeMethod(string name)\n {\n return \"Hello, {0}\".FormatWith(name);\n }\n}\n" }, { "answer_id": 39385, "author": "Kociub", "author_id": 3632, "author_profile": "https://Stackoverflow.com/users/3632", "pm_score": 2, "selected": false, "text": "String.Format printf" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
23,250
<p>I was curious about how other people use the <strong>this</strong> keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:</p> <p>In a constructor:</p> <pre><code>public Light(Vector v) { this.dir = new Vector(v); } </code></pre> <p>Elsewhere</p> <pre><code>public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } </code></pre>
[ { "answer_id": 23264, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 7, "selected": false, "text": "class Vector3\n{\n float x;\n float y;\n float z;\n\n public Vector3(float x, float y, float z)\n {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n}\n" }, { "answer_id": 23267, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 4, "selected": false, "text": "void onChange()\n{\n screen.draw(this);\n}\n" }, { "answer_id": 47397, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 1, "selected": false, "text": "boolean sameValue (SomeNum other) {\n return this.importantValue == other.importantValue;\n} \n" }, { "answer_id": 70058, "author": "Stacker", "author_id": 6574, "author_profile": "https://Stackoverflow.com/users/6574", "pm_score": 1, "selected": false, "text": "A a;\na = a;\n A& A::operator=(const A& a) {\n if (this == &a) return *this;\n\n // we know both sides of the = operator are different, do something...\n\n return *this;\n}\n" }, { "answer_id": 104938, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "this printf print this->printf this" }, { "answer_id": 105015, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 3, "selected": false, "text": "class Example : ICloneable\n{\n private void CallClone()\n {\n object clone = ((ICloneable)this).Clone();\n }\n\n object ICloneable.Clone()\n {\n throw new NotImplementedException();\n }\n}\n" }, { "answer_id": 105016, "author": "Cyberherbalist", "author_id": 16964, "author_profile": "https://Stackoverflow.com/users/16964", "pm_score": 2, "selected": false, "text": "this class MyClass {\n private int _x\n public MyClass() : this(5) {}\n public MyClass(int v) { _x = v;}\n}\n" }, { "answer_id": 107010, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 0, "selected": false, "text": " public void setFoo(int foo) {\n this.foo = foo;\n }\n notifier.addListener(this);\n" }, { "answer_id": 2182664, "author": "David Rodríguez - dribeas", "author_id": 36565, "author_profile": "https://Stackoverflow.com/users/36565", "pm_score": 0, "selected": false, "text": "this template <typename T>\nstruct base {\n void f() {}\n};\n\ntemplate <typename T>\nstruct derived : public base<T>\n{\n void test() {\n //f(); // [1] error\n base<T>::f(); // quite verbose if there is more than one argument, but valid\n this->f(); // f is now an argument dependent symbol\n }\n}\n base<T> f derived f base<T>::f base<T> T this-> base<T> this-> this->f" }, { "answer_id": 2789224, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 2, "selected": false, "text": "class AABB\n{\n // ... members\n bool intersects( AABB other )\n {\n return other.left() < this->right() &&\n this->left() < other.right() &&\n\n // +y increases going down\n other.top() < this->bottom() &&\n this->top() < other.bottom() ;\n }\n} ;\n class AABB\n{\n bool intersects( AABB other )\n {\n return other.left() < right() &&\n left() < other.right() &&\n\n // +y increases going down\n other.top() < bottom() &&\n top() < other.bottom() ;\n }\n} ;\n right() this" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016/" ]
23,277
<p>I've read the Wikipedia articles for both <a href="http://en.wikipedia.org/wiki/Procedural_programming" rel="noreferrer">procedural programming</a> and <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional programming</a>, but I'm still slightly confused. Could someone boil it down to the core?</p>
[ { "answer_id": 23693, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 7, "selected": false, "text": "sub factorial ( UInt:D $n is copy ) returns UInt {\n\n # modify \"outside\" state\n state $call-count++;\n # in this case it is rather pointless as\n # it can't even be accessed from outside\n\n my $result = 1;\n\n loop ( ; $n > 0 ; $n-- ){\n\n $result *= $n;\n\n }\n\n return $result;\n}\n int factorial( int n ){\n\n int result = 1;\n\n for( ; n > 0 ; n-- ){\n result *= n;\n }\n\n return result;\n}\n fac :: Integer -> Integer\n\nfac 0 = 1\nfac n | n > 0 = n * fac (n-1)\n fac n = if n > 0 then n * fac (n-1) else 1\n proto sub factorial ( UInt:D $n ) returns UInt {*}\n\nmulti sub factorial ( 0 ) { 1 }\nmulti sub factorial ( $n ) { $n * samewith $n-1 } # { $n * factorial $n-1 }\n pure int factorial( invariant int n ){\n if( n <= 1 ){\n return 1;\n }else{\n return n * factorial( n-1 );\n }\n}\n sub postfix:< ! > ( UInt:D $n --> UInt )\n is tighter(&infix:<*>)\n { [*] 2 .. $n }\n\nsay 5!; # 120␤\n 2..$n [ OPERATOR ] LIST * --> UInt returns UInt 2 1" }, { "answer_id": 25003, "author": "C Hogg", "author_id": 634, "author_profile": "https://Stackoverflow.com/users/634", "pm_score": 4, "selected": false, "text": "fac n = foldr (*) 1 [1..n]\n" }, { "answer_id": 28339, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 2, "selected": false, "text": "prouduct list = foldr 1 (*) list\n product = foldr 1 (*)\n fac n = foldr 1 (*) [1..n]\n fac n = product [1..n]\n" }, { "answer_id": 53093783, "author": "Nicholas Pipitone", "author_id": 2574612, "author_profile": "https://Stackoverflow.com/users/2574612", "pm_score": 2, "selected": false, "text": "arr_equal(a : [Int], b : [Str]) -> Bool {\n if(a.len != b.len) {\n return false;\n }\n\n bool ret = true;\n for( int i = 0; i < a.len /* Optimized with && ret*/; i++ ) {\n int a_int = a[i];\n int b_int = parseInt(b[i]);\n ret &= a_int == b_int; \n }\n return ret;\n}\n eq = i, j => i == j # This is usually a built-in\ntoInt = i => parseInt(i) # Of course, parseInt === toInt here, but this is for visualization\n\narr_equal(a : [Int], b : [Str]) -> Bool =\n zip(a, b.map(toInt)) # Combines into [Int, Int]\n .map(eq)\n .reduce(true, (i, j) => i && j) # Start with true, and continuously && it with each value\n map filter reduce currying partial && ret .reduce try_fold && ret" }, { "answer_id": 54253067, "author": "Hamza Zubair", "author_id": 5202586, "author_profile": "https://Stackoverflow.com/users/5202586", "pm_score": 6, "selected": false, "text": "num = 1 \ndef function_to_add_one(num):\n num += 1\n return num\n\n\nfunction_to_add_one(num)\nfunction_to_add_one(num)\nfunction_to_add_one(num)\nfunction_to_add_one(num)\nfunction_to_add_one(num)\n\n#Final Output: 2\n num = 1 \ndef procedure_to_add_one():\n global num\n num += 1\n return num\n\n\nprocedure_to_add_one()\nprocedure_to_add_one()\nprocedure_to_add_one()\nprocedure_to_add_one()\nprocedure_to_add_one()\n\n#Final Output: 6\n function_to_add_one procedure_to_add_one" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
23,287
<p>What is the best approach to calculating the largest prime factor of a number?</p> <p>I'm thinking the most efficient would be the following:</p> <ol> <li>Find lowest prime number that divides cleanly</li> <li>Check if result of division is prime</li> <li>If not, find next lowest</li> <li>Go to 2.</li> </ol> <p>I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into?</p> <p>Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed.</p> <p>Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime.</p>
[ { "answer_id": 31235, "author": "palotasb", "author_id": 3063, "author_profile": "https://Stackoverflow.com/users/3063", "pm_score": -1, "selected": false, "text": "N return(N) Sqrt(N) N is divisible by Prime Return(Prime)" }, { "answer_id": 202429, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "n = abs(number);\nresult = 1;\nif (n mod 2 == 0) {\n result = 2;\n while (n mod 2 = 0) n /= 2;\n}\nfor(i=3; i<sqrt(n); i+=2) {\n if (n mod i == 0) {\n result = i;\n while (n mod i = 0) n /= i;\n }\n}\nreturn max(n,result)\n sqrt(n) sqrt(n)" }, { "answer_id": 242274, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 2, "selected": false, "text": "n n n import Control.Monad\n\n-- All the primes\nprimes = 2 : filter (ap (<=) (head . primeFactors)) [3,5..]\n\n-- Gives the prime factors of its argument\nprimeFactors = factor primes\n where factor [] n = []\n factor xs@(p:ps) n =\n if p*p > n then [n]\n else let (d,r) = divMod n p in\n if r == 0 then p : factor xs d\n else factor ps n\n\n-- Gives the largest prime factor of its argument\nlargestFactor = last . primeFactors\n n" }, { "answer_id": 242290, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "102 = 2 x 3 x 17\n712 = 2 x 2 x 2 x 89\n 712 / 2 = 356 .. 356 / 2 = 178 .. 178 / 2 = 89 .. 89 / 89 = 1\n number = 712;\ncurrNum = number; // the value we'll actually be working with\nfor (currFactor in 2 .. number) {\n while (currNum % currFactor == 0) {\n // keep on dividing by this number until we can divide no more!\n currNum = currNum / currFactor // reduce the currNum\n }\n if (currNum == 1) return currFactor; // once it hits 1, we're done.\n}\n" }, { "answer_id": 242331, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": -1, "selected": false, "text": "1) Test = 2 \n2) Current = Number to test \n3) If Current Mod Test = 0 then \n3a) Current = Current Div Test \n3b) Largest = Test\n3c) Goto 3. \n4) Inc(Test) \n5) If Current < Test goto 4\n6) Return Largest\n" }, { "answer_id": 412942, "author": "Kenan Banks", "author_id": 43089, "author_profile": "https://Stackoverflow.com/users/43089", "pm_score": 7, "selected": false, "text": "def prime_factors(n):\n \"\"\"Returns all the prime factors of a positive integer\"\"\"\n factors = []\n d = 2\n while n > 1:\n while n % d == 0:\n factors.append(d)\n n /= d\n d = d + 1\n\n return factors\n\n\npfs = prime_factors(1000)\nlargest_prime_factor = max(pfs) # The largest element in the prime factor list\n O(n) O(sqrt(n)) def prime_factors(n):\n \"\"\"Returns all the prime factors of a positive integer\"\"\"\n factors = []\n d = 2\n while n > 1:\n while n % d == 0:\n factors.append(d)\n n /= d\n d = d + 1\n if d*d > n:\n if n > 1: factors.append(n)\n break\n return factors\n\n\npfs = prime_factors(1000)\nlargest_prime_factor = max(pfs) # The largest element in the prime factor list\n" }, { "answer_id": 830001, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 4, "selected": false, "text": "var largestPrimeFactor;\nif(n mod 2 == 0)\n{\n largestPrimeFactor = 2;\n n = n / 2 while(n mod 2 == 0);\n}\nif(n mod 3 == 0)\n{\n largestPrimeFactor = 3;\n n = n / 3 while(n mod 3 == 0);\n}\n\nmultOfSix = 6;\nwhile(multOfSix - 1 <= n)\n{\n if(n mod (multOfSix - 1) == 0)\n {\n largestPrimeFactor = multOfSix - 1;\n n = n / largestPrimeFactor while(n mod largestPrimeFactor == 0);\n }\n\n if(n mod (multOfSix + 1) == 0)\n {\n largestPrimeFactor = multOfSix + 1;\n n = n / largestPrimeFactor while(n mod largestPrimeFactor == 0);\n }\n multOfSix += 6;\n}\n" }, { "answer_id": 7698513, "author": "Chitransh", "author_id": 985586, "author_profile": "https://Stackoverflow.com/users/985586", "pm_score": -1, "selected": false, "text": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include <time.h>\n\nfactor(long int n)\n{\nlong int i,j;\nwhile(n>=4)\n {\nif(n%2==0) { n=n/2; i=2; }\n\n else\n { i=3;\nj=0;\n while(j==0)\n {\n if(n%i==0)\n {j=1;\n n=n/i;\n }\n i=i+2;\n }\n i-=2;\n }\n }\nreturn i;\n }\n\n void main()\n { \n clock_t start = clock();\n long int n,sp;\n clrscr();\n printf(\"enter value of n\");\n scanf(\"%ld\",&n);\n sp=factor(n);\n printf(\"largest prime factor is %ld\",sp);\n\n printf(\"Time elapsed: %f\\n\", ((double)clock() - start) / CLOCKS_PER_SEC);\n getch();\n }\n" }, { "answer_id": 9473540, "author": "thejosh", "author_id": 1236662, "author_profile": "https://Stackoverflow.com/users/1236662", "pm_score": 2, "selected": false, "text": " public static long largestPrimeFactor(long n) {\n\n // largest composite factor must be smaller than sqrt\n long sqrt = (long)Math.ceil(Math.sqrt((double)n));\n\n long largest = -1;\n\n for(long i = 2; i <= sqrt; i++) {\n if(n % i == 0) {\n long test = largestPrimeFactor(n/i);\n if(test > largest) {\n largest = test;\n }\n }\n }\n\n if(largest != -1) {\n return largest;\n }\n\n // number is prime\n return n;\n } \n" }, { "answer_id": 16595283, "author": "pedram", "author_id": 1615031, "author_profile": "https://Stackoverflow.com/users/1615031", "pm_score": -1, "selected": false, "text": "def primes(n):\n d = 2\n while (n > 1):\n while (n%d==0):\n yield d\n n /= d\n d += 1\n n= 373764623\nmax(primes(n))\n list(primes(n))\n" }, { "answer_id": 21238400, "author": "Seamus Barrett", "author_id": 1297920, "author_profile": "https://Stackoverflow.com/users/1297920", "pm_score": 0, "selected": false, "text": "namespace Problem_Prime\n{\n class Program\n {\n static void Main(string[] args)\n {\n /*\n The prime factors of 13195 are 5, 7, 13 and 29.\n\n What is the largest prime factor of the number 600851475143 ?\n */\n long x = 600851475143;\n long y = 2;\n while (y < x)\n {\n if (x % y == 0)\n {\n // y is a factor of x, but is it prime\n if (IsPrime(y))\n {\n Console.WriteLine(y);\n }\n x /= y;\n }\n\n y++;\n\n }\n Console.WriteLine(y);\n Console.ReadLine();\n }\n static bool IsPrime(long number)\n {\n //check for evenness\n if (number % 2 == 0)\n {\n if (number == 2)\n {\n return true;\n }\n return false;\n }\n //don't need to check past the square root\n long max = (long)Math.Sqrt(number);\n for (int i = 3; i <= max; i += 2)\n {\n if ((number % i) == 0)\n {\n return false;\n }\n }\n return true;\n }\n\n }\n}\n" }, { "answer_id": 22723233, "author": "Paul Vargas", "author_id": 870248, "author_profile": "https://Stackoverflow.com/users/870248", "pm_score": -1, "selected": false, "text": "int public static int[] primeFactors(int value) {\n int[] a = new int[31];\n int i = 0, j;\n int num = value;\n while (num % 2 == 0) {\n a[i++] = 2;\n num /= 2;\n }\n j = 3;\n while (j <= Math.sqrt(num) + 1) {\n if (num % j == 0) {\n a[i++] = j;\n num /= j;\n } else {\n j += 2;\n }\n }\n if (num > 1) {\n a[i++] = num;\n }\n int[] b = Arrays.copyOf(a, i);\n return b;\n}\n long static long[] getFactors(long value) {\n long[] a = new long[63];\n int i = 0;\n long num = value;\n while (num % 2 == 0) {\n a[i++] = 2;\n num /= 2;\n }\n long j = 3;\n while (j <= Math.sqrt(num) + 1) {\n if (num % j == 0) {\n a[i++] = j;\n num /= j;\n } else {\n j += 2;\n }\n }\n if (num > 1) {\n a[i++] = num;\n }\n long[] b = Arrays.copyOf(a, i);\n return b;\n}\n" }, { "answer_id": 23013770, "author": "the_prole", "author_id": 2715384, "author_profile": "https://Stackoverflow.com/users/2715384", "pm_score": 2, "selected": false, "text": " //this method skips unnecessary trial divisions and makes \n //trial division more feasible for finding large primes\n\n public static void main(String[] args) \n {\n long n= 1000000000039L; //this is a large prime number \n long i = 2L;\n int test = 0;\n\n while (n > 1)\n {\n while (n % i == 0)\n {\n n /= i; \n }\n\n i++;\n\n if(i*i > n && n > 1) \n {\n System.out.println(n); //prints n if it's prime\n test = 1;\n break;\n }\n }\n\n if (test == 0) \n System.out.println(i-1); //prints n if it's the largest prime factor\n }\n" }, { "answer_id": 23974478, "author": "Rishabh Prasad", "author_id": 3695673, "author_profile": "https://Stackoverflow.com/users/3695673", "pm_score": 0, "selected": false, "text": "#python implementation\nimport math\nn = 600851475143\ni = 2\nfactors=set([])\nwhile i<math.sqrt(n):\n while n%i==0:\n n=n/i\n factors.add(i)\n i+=1\nfactors.add(n)\nlargest=max(factors)\nprint factors\nprint largest\n" }, { "answer_id": 24714465, "author": "4aRk Kn1gh7", "author_id": 3736555, "author_profile": "https://Stackoverflow.com/users/3736555", "pm_score": 0, "selected": false, "text": "int getLargestPrime(int number) {\n int factor = number; // assumes that the largest prime factor is the number itself\n for (int i = 2; (i*i) <= number; i++) { // iterates to the square root of the number till it finds the first(smallest) factor\n if (number % i == 0) { // checks if the current number(i) is a factor\n factor = max(i, number / i); // stores the larger number among the factors\n break; // breaks the loop on when a factor is found\n }\n }\n if (factor == number) // base case of recursion\n return number;\n return getLargestPrime(factor); // recursively calls itself\n}\n" }, { "answer_id": 33609588, "author": "Jyothir Aditya Singh", "author_id": 4037878, "author_profile": "https://Stackoverflow.com/users/4037878", "pm_score": 1, "selected": false, "text": "def primef(n):\n if n <= 3:\n return n\n if n % 2 == 0:\n return primef(n/2)\n elif n % 3 ==0:\n return primef(n/3)\n else:\n for i in range(5, int((n)**0.5) + 1, 6):\n #print i\n if n % i == 0:\n return primef(n/i)\n if n % (i + 2) == 0:\n return primef(n/(i+2))\n return n\n" }, { "answer_id": 33854720, "author": "penkovsky", "author_id": 558254, "author_profile": "https://Stackoverflow.com/users/558254", "pm_score": 0, "selected": false, "text": "x x f max' x i | i > x = max'\n | x `rem` i == 0 = f i (x `div` i) i -- Divide x by its factor\n | otherwise = f max' x (i + 1) -- Check for the next possible factor\n\ng x = f 2 x 2\n" }, { "answer_id": 36360681, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 3, "selected": false, "text": "'option strict';\n\nfunction largestPrimeFactor(val, divisor = 2) { \n let square = (val) => Math.pow(val, 2);\n\n while ((val % divisor) != 0 && square(divisor) <= val) {\n divisor++;\n }\n\n return square(divisor) <= val\n ? largestPrimeFactor(val / divisor, divisor)\n : val;\n}\n let result = largestPrimeFactor(600851475143);\n" }, { "answer_id": 37829365, "author": "s.n", "author_id": 6195963, "author_profile": "https://Stackoverflow.com/users/6195963", "pm_score": 0, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\n// ------ is_prime ------\n// Determines if the integer accepted is prime or not\nbool is_prime(int n){\n int i,count=0;\n if(n==1 || n==2)\n return true;\n if(n%2==0)\n return false;\n for(i=1;i<=n;i++){\n if(n%i==0)\n count++;\n }\n if(count==2)\n return true;\n else\n return false;\n }\n // ------ nextPrime -------\n // Finds and returns the next prime number\n int nextPrime(int prime){\n bool a = false;\n while (a == false){\n prime++;\n if (is_prime(prime))\n a = true;\n }\n return prime;\n }\n // ----- M A I N ------\n int main(){\n\n int value = 13195;\n int prime = 2;\n bool done = false;\n\n while (done == false){\n if (value%prime == 0){\n value = value/prime;\n if (is_prime(value)){\n done = true;\n }\n } else {\n prime = nextPrime(prime);\n }\n }\n cout << \"Largest prime factor: \" << value << endl;\n }\n" }, { "answer_id": 39263813, "author": "Kalpesh Dusane", "author_id": 6742808, "author_profile": "https://Stackoverflow.com/users/6742808", "pm_score": 1, "selected": false, "text": "def PrimeFactor(n):\n m = n\n while n%2==0:\n n = n//2\n if n == 1: # check if only 2 is largest Prime Factor \n return 2\n i = 3\n sqrt = int(m**(0.5)) # loop till square root of number\n last = 0 # to store last prime Factor i.e. Largest Prime Factor\n while i <= sqrt :\n while n%i == 0:\n n = n//i # reduce the number by dividing it by it's Prime Factor\n last = i\n i+=2\n if n> last: # the remaining number(n) is also Factor of number \n return n\n else:\n return last\nprint(PrimeFactor(int(input()))) \n 10 5 600851475143 6857" }, { "answer_id": 48862397, "author": "Ugnius Malūkas", "author_id": 2122457, "author_profile": "https://Stackoverflow.com/users/2122457", "pm_score": 3, "selected": false, "text": "def largest_prime_factor(number)\n i = 2\n while number > 1\n if number % i == 0\n number /= i;\n else\n i += 1\n end\n end\n return i\nend\n\nlargest_prime_factor(600851475143)\n# => 6857\n" }, { "answer_id": 51410864, "author": "Babar-Baig", "author_id": 2293300, "author_profile": "https://Stackoverflow.com/users/2293300", "pm_score": 0, "selected": false, "text": "public static int getLargestPrime( int number) {\n\n if (number <= 1) return -1;\n\n for (int i = number - 1; i > 1; i--) {\n if (number % i == 0) {\n number = i;\n }\n }\n return number;\n}\n" }, { "answer_id": 52311990, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 0, "selected": false, "text": "#include <bits/stdc++.h>\nusing namespace std;\n#define N 10001 \ntypedef long long ll;\nbool visit[N];\nvector<int> prime;\n\nvoid sieve()\n{\n memset( visit , 0 , sizeof(visit));\n for( int i=2;i<N;i++ )\n {\n if( visit[i] == 0)\n {\n prime.push_back(i);\n for( int j=i*2; j<N; j=j+i )\n {\n visit[j] = 1;\n }\n }\n } \n}\nvoid sol(long long n, vector<int>&prime)\n{\n ll ans = n;\n for(int i=0; i<prime.size() || prime[i]>n; i++)\n {\n while(n%prime[i]==0)\n {\n n=n/prime[i];\n ans = prime[i];\n }\n }\n ans = max(ans, n);\n cout<<ans<<endl;\n}\nint main() \n{\n ll tc, n;\n sieve();\n\n cin>>n;\n sol(n, prime);\n\n return 0;\n}\n" }, { "answer_id": 66403796, "author": "Vikas Gautam", "author_id": 4850220, "author_profile": "https://Stackoverflow.com/users/4850220", "pm_score": 0, "selected": false, "text": "prime? sieve (defn prime? \n ([n]\n (let [oddNums (iterate #(+ % 2) 3)]\n (prime? n (cons 2 oddNums))))\n ([n [i & is]]\n (let [q (quot n i)\n r (mod n i)]\n (cond (< n 2) false\n (zero? r) false\n (> (* i i) n) true\n :else (recur n is)))))\n\n(def primes \n (let [oddNums (iterate #(+ % 2) 3)]\n (lazy-seq (cons 2 (filter prime? oddNums)))))\n\n;; Sieve of Eratosthenes\n(defn sieve\n ([n] \n (sieve primes n))\n ([[i & is :as ps] n]\n (let [q (quot n i)\n r (mod n i)]\n (cond (< n 2) nil\n (zero? r) (lazy-seq (cons i (sieve ps q)))\n (> (* i i) n) (when (> n 1) (lazy-seq [n]))\n :else (recur is n)))))\n\n(defn max-prime-factor [n]\n (last (sieve n)))\n" }, { "answer_id": 68996148, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 1, "selected": false, "text": "O(N^(1/4)) O(N^(1/2)) def is_fermat_probable_prime(n, *, trials = 32):\n # https://en.wikipedia.org/wiki/Fermat_primality_test\n import random\n if n <= 16:\n return n in (2, 3, 5, 7, 11, 13)\n for i in range(trials):\n if pow(random.randint(2, n - 2), n - 1, n) != 1:\n return False\n return True\n\ndef pollard_rho_factor(N, *, trials = 16):\n # https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm\n import random, math\n for j in range(trials):\n i, stage, y, x = 0, 2, 1, random.randint(1, N - 2)\n while True:\n r = math.gcd(N, x - y)\n if r != 1:\n break\n if i == stage:\n y = x\n stage <<= 1\n x = (x * x + 1) % N\n i += 1\n if r != N:\n return [r, N // r]\n return [N] # Pollard-Rho failed\n\ndef trial_division_factor(n, *, limit = None):\n # https://en.wikipedia.org/wiki/Trial_division\n fs = []\n while n & 1 == 0:\n fs.append(2)\n n >>= 1\n d = 3\n while d * d <= n and limit is None or d <= limit:\n q, r = divmod(n, d)\n if r == 0:\n fs.append(d)\n n = q\n else:\n d += 2\n if n > 1:\n fs.append(n)\n return fs\n\ndef factor(n):\n if n <= 1:\n return []\n if is_fermat_probable_prime(n):\n return [n]\n fs = trial_division_factor(n, limit = 1 << 12)\n if len(fs) >= 2:\n return sorted(fs[:-1] + factor(fs[-1]))\n fs = pollard_rho_factor(n)\n if len(fs) >= 2:\n return sorted([e1 for e0 in fs for e1 in factor(e0)])\n return trial_division_factor(n)\n\ndef demo():\n import time, math\n # http://www.math.com/tables/constants/pi.htm\n # pi = 3.\n # 1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825 3421170679\n # 8214808651 3282306647 0938446095 5058223172 5359408128 4811174502 8410270193 8521105559 6446229489 5493038196\n # n = first 190 fractional digits of Pi\n n = 1415926535_8979323846_2643383279_5028841971_6939937510_5820974944_5923078164_0628620899_8628034825_3421170679_8214808651_3282306647_0938446095_5058223172_5359408128_4811174502_8410270193_8521105559_6446229489\n print('Number:', n)\n tb = time.time()\n fs = factor(n)\n print('All Prime Factors:', fs)\n print('Largest Prime Factor:', f'({math.log2(fs[-1]):.02f} bits, {len(str(fs[-1]))} digits)', fs[-1])\n print('Time Elapsed:', round(time.time() - tb, 3), 'sec')\n\nif __name__ == '__main__':\n demo()\n Number: 1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489\nAll Prime Factors: [3, 71, 1063541, 153422959, 332958319, 122356390229851897378935483485536580757336676443481705501726535578690975860555141829117483263572548187951860901335596150415443615382488933330968669408906073630300473]\nLargest Prime Factor: (545.09 bits, 165 digits) 122356390229851897378935483485536580757336676443481705501726535578690975860555141829117483263572548187951860901335596150415443615382488933330968669408906073630300473\nTime Elapsed: 0.593 sec\n" }, { "answer_id": 73180644, "author": "4d30", "author_id": 14868795, "author_profile": "https://Stackoverflow.com/users/14868795", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdbool.h>\n\nbool is_factor(long int t, long int n){\n return ( t%n == 0);\n}\n\nbool is_prime(long int n0, long int n1, bool acc){\n if ( n1 * n1 > n0 || acc < 1 )\n return acc;\n else\n return is_prime(n0, n1+2, acc && (n0%n1 != 0));\n}\n\nint gpf(long int t, long int n, long int acc){\n if (n * n > t)\n return acc;\n if (is_factor(t, n)){\n if (is_prime(n, 3, true))\n return gpf(t, n+2, n);\n else\n return gpf(t, n+2, acc);\n }\n else\n return gpf(t, n+2, acc);\n}\n\nint main(int argc, char ** argv){\n printf(\"%d\\n\", gpf(600851475143, 3, 0));\n return 0;\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1951/" ]
23,372
<p>What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?</p> <p>The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component). </p> <p>Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?</p> <p><strong>Edit:</strong></p> <p><strong><em>John:</em></strong> your solution looks like a lot of engineering :P What I ended up using is following wrapper:</p> <pre><code>package com.sun.lwuit; public class ImageWrapper { private final Image image; public ImageWrapper(final Image lwuitBuffer) { this.image = lwuitBuffer; } public javax.microedition.lcdui.Graphics getGraphics() { return image.getGraphics().getGraphics(); } } </code></pre> <p>Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.</p> <p>And it still looks like a hack :)</p> <p>But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)</p> <p>/JaanusSiim</p>
[ { "answer_id": 86279, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 2, "selected": false, "text": "private Image buffer = null; // keep this\n\nint[] bufferArray = new int[desiredWidth * desiredHeight];\njavax.microedition.lcdui.Image bufferImage = \n Image.createEmptyImage(desiredWidth, desiredHeight);\nthirPartyComponent.paint(bufferImage.getGraphics());\nbufferImage.getRGB(bufferArray,0,1,0,0,desiredWidth, desiredHeight);\nbufferImage = null; //no longer needed\nbuffer = Image.createImage(bufferArray, desiredWidth, desiredHeight);\n g.drawImage(0,0, buffer);\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706/" ]
23,376
<p>Has anyone found a good compression format for MS Sqlserver databases? If so, what do you use and are you pleased with how it performs? </p> <p>My company frequently will compress a database snapshot from one of our clients and download it so we have a local copy for testing and dev purposes. We tried zip in the past, but once the database files crossed the 4Gb boundary we had to use rar (zip is 32-bit only). The problem is rar takes a lot of time to compress, and we don't know if it gives us the best compression ratio either.</p> <p>This isn't a question about the compression utility so much as the compression format. We use WinRar, but are considering 7zip, which supports a number of formats.</p>
[ { "answer_id": 26428, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 1, "selected": false, "text": "cat file | gzip > file.gz" }, { "answer_id": 73290927, "author": "MrCalvin", "author_id": 3175384, "author_profile": "https://Stackoverflow.com/users/3175384", "pm_score": 1, "selected": false, "text": "peazip_portable-8.7.0.WIN64.zip Arc.exe create -m3 --recovery \"c:\\temp\\SQL.bak.arc\" \"c:\\temp\\SQL.bak\"" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2188/" ]
23,397
<p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p> <p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
[ { "answer_id": 23510, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": " from threading import Thread\n \n def separate_computations(x, y):\n print sum(x for i in range(y)) # really expensive multiplication\n \n Thread(target=separate_computations, args=[57, 83]).start()\n\n print \"I'm continuing while that other function runs in another thread!\"\n" }, { "answer_id": 170387, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 3, "selected": false, "text": "fork()" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555/" ]
23,399
<p>I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.</p> <p>I'm using a simple Allow or Deny option for each 'Resource' or screen.</p> <p>We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group.</p> <p>I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance.</p> <p><strong>Option A</strong> The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied.</p> <p>I think this will mean a smaller table, but would queries search the whole table to determine there is no match?</p> <p><strong>Option B</strong> A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table.</p> <p>Thoughts?</p>
[ { "answer_id": 23432, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": true, "text": "UserResources\n-------------\nUserId FK->Users\nResourceId FK->Resources\n if exists (select 1 from UserResources \nwhere UserId = @uid and ResourceId=@rid)\nset @allow=1;\n" }, { "answer_id": 23480, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "User1 is in group1 and group2. \nUser2 is in group1 \nUser3 is in group2 \n Folder1 allows group1 and deny group2. \nUser1 is denied. \nUser2 is allowed. \nUser3 is denied. \n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ]
23,445
<p>I have two collections of the same object, <code>Collection&lt;Foo&gt; oldSet</code> and <code>Collection&lt;Foo&gt; newSet</code>. The required logic is as follow:</p> <ul> <li>if <code>foo</code> is in(*) <code>oldSet</code> but not <code>newSet</code>, call <code>doRemove(foo)</code></li> <li>else if <code>foo</code> is not in <code>oldSet</code> but in <code>newSet</code>, call <code>doAdd(foo)</code></li> <li>else if <code>foo</code> is in both collections but modified, call <code>doUpdate(oldFoo, newFoo)</code></li> <li>else if <code>!foo.activated &amp;&amp; foo.startDate &gt;= now</code>, call <code>doStart(foo)</code></li> <li>else if <code>foo.activated &amp;&amp; foo.endDate &lt;= now</code>, call <code>doEnd(foo)</code></li> </ul> <p>(*) "in" means the unique identifier matches, not necessarily the content.</p> <p>The current (legacy) code does many comparisons to figure out <code>removeSet</code>, <code>addSet</code>, <code>updateSet</code>, <code>startSet</code> and <code>endSet</code>, and then loop to act on each item.</p> <p>The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info:</p> <ul> <li>As far as I know, the <code>oldSet</code> and <code>newSet</code> are actually backed by <code>ArrayList</code></li> <li>Each set contains less than 100 items, most likely max out at 20</li> <li>This code is called frequently (measured in millions/day), although the sets seldom differ</li> </ul> <p>My questions:</p> <ul> <li>If I convert <code>oldSet</code> and <code>newSet</code> into <code>HashMap&lt;Foo&gt;</code> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time &amp; memory performance is loss on the conversion?</li> <li>Would iterating the two sets and perform the appropriate operation be more efficient and concise?</li> </ul>
[ { "answer_id": 23944, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 4, "selected": false, "text": "Collection<Foo> oldSet = ...;\nCollection<Foo> newSet = ...;\n\nprivate Collection difference(Collection a, Collection b) {\n Collection result = a.clone();\n result.removeAll(b)\n return result;\n}\n\nprivate Collection intersection(Collection a, Collection b) {\n Collection result = a.clone();\n result.retainAll(b)\n return result;\n}\n\npublic doWork() {\n // if foo is in(*) oldSet but not newSet, call doRemove(foo)\n Collection removed = difference(oldSet, newSet);\n if (!removed.isEmpty()) {\n loop removed {\n Foo foo = removedIter.next();\n doRemove(foo);\n }\n }\n //else if foo is not in oldSet but in newSet, call doAdd(foo)\n Collection added = difference(newSet, oldSet);\n if (!added.isEmpty()) {\n loop added {\n Foo foo = addedIter.next();\n doAdd(foo);\n }\n }\n\n // else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)\n Collection matched = intersection(oldSet, newSet);\n Comparator comp = new Comparator() {\n int compare(Object o1, Object o2) {\n Foo f1, f2;\n if (o1 instanceof Foo) f1 = (Foo)o1;\n if (o2 instanceof Foo) f2 = (Foo)o2;\n return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;\n }\n\n boolean equals(Object o) {\n // equal to this Comparator..not used\n }\n }\n loop matched {\n Foo foo = matchedIter.next();\n Foo oldFoo = oldSet.get(foo);\n Foo newFoo = newSet.get(foo);\n if (comp.compareTo(oldFoo, newFoo ) != 0) {\n doUpdate(oldFoo, newFoo);\n } else {\n //else if !foo.activated && foo.startDate >= now, call doStart(foo)\n if (!foo.activated && foo.startDate >= now) doStart(foo);\n\n // else if foo.activated && foo.endDate <= now, call doEnd(foo)\n if (foo.activated && foo.endDate <= now) doEnd(foo);\n }\n }\n}\n" }, { "answer_id": 36997, "author": "Bartosz Bierkowski", "author_id": 3666, "author_profile": "https://Stackoverflow.com/users/3666", "pm_score": 2, "selected": false, "text": "/* Main method */\nprivate void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {\n List<Foo> oldList = asSortedList(oldSet);\n List<Foo> newList = asSortedList(newSet);\n\n int oldIndex = 0;\n int newIndex = 0;\n // Iterate over both collections but not always in the same pace\n while( oldIndex < oldList.size() \n && newIndex < newIndex.size()) {\n Foo oldObject = oldList.get(oldIndex);\n Foo newObject = newList.get(newIndex);\n\n // Your logic here\n if(oldObject.getId() < newObject.getId()) {\n doRemove(oldObject);\n oldIndex++;\n } else if( oldObject.getId() > newObject.getId() ) {\n doAdd(newObject);\n newIndex++;\n } else if( oldObject.getId() == newObject.getId() \n && isModified(oldObject, newObject) ) {\n doUpdate(oldObject, newObject);\n oldIndex++;\n newIndex++;\n } else {\n ... \n }\n }// while\n\n // Check if there are any objects left in *oldList* or *newList*\n\n for(; oldIndex < oldList.size(); oldIndex++ ) {\n doRemove( oldList.get(oldIndex) ); \n }// for( oldIndex )\n\n for(; newIndex < newList.size(); newIndex++ ) {\n doAdd( newList.get(newIndex) );\n }// for( newIndex ) \n}// execute( oldSet, newSet )\n\n/** Create sorted list from collection \n If you actually perform any actions on input collections than you should \n always return new instance of list to keep algorithm simple.\n*/\nprivate List<Foo> asSortedList(Collection<Foo> data) {\n List<Foo> resultList;\n if(data instanceof List) {\n resultList = (List<Foo>)data;\n } else {\n resultList = new ArrayList<Foo>(data);\n }\n Collections.sort(resultList)\n return resultList;\n}\n" }, { "answer_id": 4469413, "author": "Lijo Mathew", "author_id": 545907, "author_profile": "https://Stackoverflow.com/users/545907", "pm_score": -1, "selected": false, "text": "Arrays.equals(object[], object[]) Object[] Collection.toArray()" }, { "answer_id": 8638140, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 5, "selected": false, "text": "set1.stream().filter(s -> set2.contains(s)).collect(Collectors.toSet());\n Set<String> intersection = Sets.intersection(set1, set2);\nSet<String> difference = Sets.difference(set1, set2);\nSet<String> symmetricDifference = Sets.symmetricDifference(set1, set2);\nSet<String> union = Sets.union(set1, set2);\n" }, { "answer_id": 35296176, "author": "pooja", "author_id": 1854406, "author_profile": "https://Stackoverflow.com/users/1854406", "pm_score": 0, "selected": false, "text": "public static boolean doCollectionsContainSameElements(\n Collection<Integer> c1, Collection<Integer> c2){\n\n if (c1 == null || c2 == null) {\n return false;\n }\n else if (c1.size() != c2.size()) {\n return false;\n } else { \n return c1.containsAll(c2) && c2.containsAll(c1);\n } \n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2551/" ]
23,446
<p>Have just started using Visual Studio Professional's built-in unit testing features, which as I understand, uses MS Test to run the tests.</p> <p>The .trx file that the tests produce is xml, but was wondering if there was an easy way to convert this file into a more "manager-friendly" format?</p> <p>My ultimate goal is to be able to automate the unit-testing and be able to produce a nice looking document that shows the tests run and how 100% of them passed :)</p>
[ { "answer_id": 289473, "author": "Preet Sangha", "author_id": 30225, "author_profile": "https://Stackoverflow.com/users/30225", "pm_score": 2, "selected": false, "text": "<xsl:stylesheet version=\"2.0\" \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:t=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2006\"\n >\n\n<xsl:template match=\"/\">\n <html>\n <head>\n <style type=\"text/css\">\n h2 {color: sienna}\n p {margin-left: 20px}\n .resultsHdrRow { font-face: arial; padding: 5px }\n .resultsRow { font-face: arial; padding: 5px }\n </style>\n </head>\n <body>\n <h2>Test Results</h2>\n <h3>Summary</h3>\n <ul>\n <li>Tests found: <xsl:value-of select=\"t:TestRun/t:ResultSummary/t:Counters/@total\"/></li>\n <li>Tests executed: <xsl:value-of select=\"t:TestRun/t:ResultSummary/t:Counters/@executed\"/></li>\n <li>Tests passed: <xsl:value-of select=\"t:TestRun/t:ResultSummary/t:Counters/@passed\"/></li>\n <li>Tests Failed: <xsl:value-of select=\"t:TestRun/t:ResultSummary/t:Counters/@failed\"/></li>\n\n </ul>\n <table border=\"1\" width=\"80%\" >\n <tr class=\"resultsHdrRow\">\n <th align=\"left\">Test</th>\n <th align=\"left\">Outcome</th>\n </tr>\n <xsl:for-each select=\"/t:TestRun/t:Results/t:UnitTestResult\" >\n <tr valign=\"top\" class=\"resultsRow\">\n <td width='30%'><xsl:value-of select=\"@testName\"/></td>\n <td width='70%'>\n <Div>Message: <xsl:value-of select=\"t:Output/t:ErrorInfo/t:Message\"/></Div>\n <br/>\n <Div>Stack: <xsl:value-of select=\"t:Output/t:ErrorInfo/t:StackTrace\"/></Div>\n <br/>\n <Div>Console: <xsl:value-of select=\"t:Output/t:StdOut\"/></Div>\n </td>\n </tr>\n </xsl:for-each>\n </table>\n </body>\n </html>\n</xsl:template>\n\n</xsl:stylesheet>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443/" ]
23,448
<p>Has anyone worked with <a href="http://www.google.com.br/url?sa=t&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FDomain-specific_programming_language&amp;ei=QyWvSIXcC4foebjSlHs&amp;usg=AFQjCNFsZOnJm-AGmi5sxai8YI-0Al6wfA&amp;sig2=6nX5EkUmNkEwiSKAkUeyZQ" rel="noreferrer">DSLs (Domain Specific Languages)</a> in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas.</p> <p>I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature.</p>
[ { "answer_id": 31770859, "author": "SemanticBeeng", "author_id": 4032515, "author_profile": "https://Stackoverflow.com/users/4032515", "pm_score": 1, "selected": false, "text": " object Main extends App {\n //Required for doing LocalDate comparisons...a scalaism\n implicit val LocalDateOrdering = scala.math.Ordering.fromLessThan[java.time.LocalDate]{case (a,b) => (a compareTo b) < 0}\n\n //custom contract\n def usd(amount:Double) = Scale(Const(amount),One(\"USD\"))\n def buy(contract:Contract, amount:Double) = And(contract,Give(usd(amount)))\n def sell(contract:Contract, amount:Double) = And(Give(contract),usd(amount))\n def zcb(maturity:LocalDate, notional:Double, currency:String) = When(maturity, Scale(Const(notional),One(currency)))\n def option(contract:Contract) = Or(contract,Zero())\n def europeanCallOption(at:LocalDate, c1:Contract, strike:Double) = When(at, option(buy(c1,strike)))\n def europeanPutOption(at:LocalDate, c1:Contract, strike:Double) = When(at, option(sell(c1,strike)))\n def americanCallOption(at:LocalDate, c1:Contract, strike:Double) = Anytime(at, option(buy(c1,strike)))\n def americanPutOption(at:LocalDate, c1:Contract, strike:Double) = Anytime(at, option(sell(c1,strike)))\n\n //custom observable\n def stock(symbol:String) = Scale(Lookup(symbol),One(\"USD\"))\n val msft = stock(\"MSFT\")\n\n\n //Tests\n val exchangeRates = collection.mutable.Map(\n \"USD\" -> LatticeImplementation.binomialPriceTree(365,1,0),\n \"GBP\" -> LatticeImplementation.binomialPriceTree(365,1.55,.0467),\n \"EUR\" -> LatticeImplementation.binomialPriceTree(365,1.21,.0515)\n )\n val lookup = collection.mutable.Map(\n \"MSFT\" -> LatticeImplementation.binomialPriceTree(365,45.48,.220),\n \"ORCL\" -> LatticeImplementation.binomialPriceTree(365,42.63,.1048),\n \"EBAY\" -> LatticeImplementation.binomialPriceTree(365,53.01,.205)\n )\n val marketData = Environment(\n LatticeImplementation.binomialPriceTree(365,.15,.05), //interest rate (use a universal rate for now)\n exchangeRates, //exchange rates\n lookup\n )\n\n //portfolio test\n val portfolio = Array(\n One(\"USD\")\n ,stock(\"MSFT\")\n ,buy(stock(\"MSFT\"),45)\n ,option(buy(stock(\"MSFT\"),45))\n ,americanCallOption(LocalDate.now().plusDays(5),stock(\"MSFT\"),45)\n )\n\n for(contract <- portfolio){\n println(\"===========\")\n val propt = LatticeImplementation.contractToPROpt(contract)\n val rp = LatticeImplementation.binomialValuation(propt, marketData)\n println(\"Contract: \"+contract)\n println(\"Random Process(for optimization): \"+propt)\n println(\"Present val: \"+rp.startVal())\n println(\"Random Process: \\n\"+rp)\n }\n\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015/" ]
23,511
<p>I'm working with Subversion based on Windows and would like to write an easy utility in .NET for working with the Apache password file. I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash.</p> <p>Can someone describe the MD5Crypt algorithm and password line format?</p>
[ { "answer_id": 23557, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "System.Security.Cryptography.MD5CryptoServiceProvider md5 = new\nSystem.Security.Cryptography.MD5CryptoServiceProvider();\n\nstring hash =BitConverter.ToString((md5.ComputeHash(\nSystem.Text.ASCIIEncoding.Default.GetBytes(stringtohash) ) ));\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954/" ]
23,566
<p>On IIS 6, what does an IIS reset do? </p> <p>Please compare to recycling an app pool and stopping and starting an ASP.NET web site.</p> <p>If you replace a DLL or edit/replace the web.config on an ASP.NET web site is that the same as stopping and starting that web site?</p>
[ { "answer_id": 23573, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "web.config /bin" }, { "answer_id": 23581, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 1, "selected": false, "text": "web.config bin" }, { "answer_id": 23582, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 5, "selected": false, "text": "public partial class Recycle : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n HttpRuntime.UnloadAppDomain();\n }\n}\n" }, { "answer_id": 23584, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 5, "selected": false, "text": "C:\\>iisreset /?\n\nIISRESET.EXE (c) Microsoft Corp. 1998-1999\n\nUsage:\niisreset [computername]\n\n /RESTART Stop and then restart all Internet services.\n /START Start all Internet services.\n /STOP Stop all Internet services.\n /REBOOT Reboot the computer.\n /REBOOTONERROR Reboot the computer if an error occurs when starting,\n stopping, or restarting Internet services.\n /NOFORCE Do not forcefully terminate Internet services if\n attempting to stop them gracefully fails.\n /TIMEOUT:val Specify the timeout value ( in seconds ) to wait for\n a successful stop of Internet services. On expiration\n of this timeout the computer can be rebooted if\n the /REBOOTONERROR parameter is specified.\n The default value is 20s for restart, 60s for stop,\n and 0s for reboot.\n /STATUS Display the status of all Internet services.\n /ENABLE Enable restarting of Internet Services\n on the local system.\n /DISABLE Disable restarting of Internet Services\n on the local system.\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
23,569
<p>How do you calculate the distance between 2 cities? </p>
[ { "answer_id": 23632, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 1, "selected": false, "text": "// Cities are points x0,y0 and x1,y1 in kilometers or miles or Smoots[1]\ndx = x1 - x0;\ndy = y1 - y0;\ndist = sqrt(dx*dx + dy*y);\n dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));\n" }, { "answer_id": 23746, "author": "Josh Brown", "author_id": 2030, "author_profile": "https://Stackoverflow.com/users/2030", "pm_score": 0, "selected": false, "text": "dist = sqrt(dx*dx + dy*dy);\n" }, { "answer_id": 501226, "author": "Marko Tintor", "author_id": 61003, "author_profile": "https://Stackoverflow.com/users/61003", "pm_score": 2, "selected": false, "text": "SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))\n-- computes distance in meters using eliptical model, accurate to the mm\n" }, { "answer_id": 24403838, "author": "Sarath Sadasivan Pillai", "author_id": 1898494, "author_profile": "https://Stackoverflow.com/users/1898494", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python\nimport requests\nfrom sys import argv \ndef get_distance(origin,destination):\n gmap='http://maps.googleapis.com/maps/api/distancematrix/json'\n payload={\"origins\":origin,\"destinations\":destination,\"sensor\":'false' }\n try:\n a=requests.get(gmap,params=payload)\n data = a.json()\n origin = str(data['origin_addresses'][0])\n destination= str(data['destination_addresses'][0])\n distance = data['rows'][0]['elements'][0]['distance']['text']\n return distance,origin,destination\n except Exception,e:\n print \"The %s or %destination does not exists :(\" %(origin,destination)\n exit()\n\nif __name__==\"__main__\":\n if len(argv)<3:\n print \"sorry Check the format\"\n else:\n origin=argv[1]\n destination=argv[2]\n distance,origin,destination=get_distance(origin,destination)\n print \"%s ---> %s : %s\" %(origin,destination,distance)\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141/" ]
23,578
<p>And on top of that, are there cases where one has to use the global assembly cache or where one cannot use it?</p>
[ { "answer_id": 23635, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": false, "text": "AllowPartiallyTrustedCallers [PermissionSet(SecurityAction.Assert, Unrestricted=true)]\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374/" ]
23,603
<p>I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project).<br> As a result, the project would no longer compile with previous versions of the library.</p> <p>So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in.<br> I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically.</p>
[ { "answer_id": 23702, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 2, "selected": false, "text": "/\n /trunk\n /tags\n /branches\n svn copy trunk/ tags/TagName\n" }, { "answer_id": 23816, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "piston update" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112/" ]
23,620
<p>I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.</p> <p>As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko_spellcheck option, which is supposed to fix it, but it doesn't.</p> <p>Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?</p>
[ { "answer_id": 23733, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "gecko_spellcheck tinyMCE.init() tinyMCE.init({\n mode : \"textareas\",\n theme : \"simple\",\n gecko_spellcheck : true\n});\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527/" ]
23,689
<p>Does anyone know of a .NET date/time parser similar to <a href="http://chronic.rubyforge.org/" rel="noreferrer">Chronic for Ruby</a> (handles stuff like "tomorrow" or "3pm next thursday")?</p> <p>Note: I do write Ruby (which is how I know about Chronic) but this project must use .NET.</p>
[ { "answer_id": 23833, "author": "Burton", "author_id": 1493, "author_profile": "https://Stackoverflow.com/users/1493", "pm_score": 2, "selected": false, "text": "Private Function ConvertDateTimeToStringRelativeToNow(ByVal d As DateTime) As String\n Dim diff As TimeSpan = DateTime.Now().Subtract(d)\n If diff.Duration.TotalMinutes < 1 Then Return \"Now\"\n\n Dim str As String\n If diff.Duration.TotalDays > 365 Then\n str = CInt(diff.Duration.TotalDays / 365).ToString() & \" years\"\n ElseIf diff.Duration.TotalDays > 30 Then\n str = CInt(diff.TotalDays / 30).ToString() & \" months\"\n ElseIf diff.Duration.TotalHours > 24 Then\n str = CInt(diff.Duration.TotalHours / 24) & \" days\"\n ElseIf diff.Duration.TotalMinutes > 60 Then\n str = CInt(diff.Duration.TotalMinutes / 60) & \" minutes\"\n Else\n str = CInt(diff.Duration.TotalMinutes).ToString() & \" minutes\"\n End If\n If str.StartsWith(\"1\") Then str = str.SubString(0, str.Length - 1)\n If diff.TotalDays > 0 Then\n str &= \" ago\"\n Else\n str &= \" from now\"\n End If\n Return str\nEnd Function\n" }, { "answer_id": 23842, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": " Chronic.parse('tomorrow')\n #=> Mon Aug 28 12:00:00 PDT 2006\n\n Chronic.parse('monday', :context => :past)\n #=> Mon Aug 21 12:00:00 PDT 2006\n\n Chronic.parse('this tuesday 5:00')\n #=> Tue Aug 29 17:00:00 PDT 2006\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521/" ]
23,715
<p>Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question.</p> <ul> <li>I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the <em>same port</em> (ie, they both run on port 80)?</li> <li>The web servers would <em>not</em> be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com.</li> </ul> <p>I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole. :) </p>
[ { "answer_id": 23732, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 4, "selected": true, "text": "NameVirtualHost *\n<virtualhost *>\n ServerName other.site.com\n\n # assumes CherryPy listens on port 8080\n ProxyPass / http://127.0.0.1:8080/\n ProxyPassReverse / http://127.0.0.1:8080/\n</Virtualhost>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321/" ]
23,755
<p>When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:</p> <pre><code>1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack)</code></pre> <p>Which do you prefer, and why?</p> <p>I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".</p> <p>In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?</p>
[ { "answer_id": 23756, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "needle.find(haystack) haystack.find(needle) haystack.find(needle)" }, { "answer_id": 23769, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 7, "selected": true, "text": "haystack.find(needle, searcher)\n" }, { "answer_id": 23812, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "find(haystack.begin(), haystack.end(), needle)\n" }, { "answer_id": 23840, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 4, "selected": false, "text": "class Haystack : ISearchableThingsOnAFarm {\n ICollection<Hay> myHay;\n ICollection<IStuffSmallEnoughToBeLostInAHaystack> stuffLostInMe;\n\n public ICollection<Hay> Hay {\n get {\n return myHay;\n }\n }\n\n public ICollection<IStuffSmallEnoughToBeLostInAHayStack> LostAndFound {\n get {\n return stuffLostInMe;\n }\n }\n}\n\nclass Needle : IStuffSmallEnoughToBeLostInAHaystack {\n}\n\nclass Farmer {\n Search(Haystack haystack, \n IStuffSmallEnoughToBeLostInAHaystack itemToFind)\n}\n" }, { "answer_id": 23953, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": ".include? haystack.include? needle\n=> returns true if the haystack includes the needle\n in? needle.in? haystack\n=> exactly the same as above\n include? in?" }, { "answer_id": 23957, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "IStuffSmallEnoughToBeLostInAHaystack" }, { "answer_id": 25296, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 1, "selected": false, "text": "haystack.find(needle, searcher) searcher binary_searcher.find(needle, haystack)\nvision_searcher.find(pitchfork, haystack)\nbrute_force_searcher.find(money, wallet)\n haystack.find(needle)" }, { "answer_id": 25428, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 1, "selected": false, "text": "haystack.magnet().filter(needle);\n" }, { "answer_id": 33156, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 1, "selected": false, "text": "class Haystack {//whatever\n };\nclass Needle {//whatever\n }:\nclass Searcher {\n virtual void find() = 0;\n};\n\nclass HaystackSearcher::public Searcher {\npublic:\n HaystackSearcher(Haystack, object)\n virtual void find();\n};\n\nHaystack H;\nNeedle N;\nHaystackSearcher HS(H, N);\nHS.find();\n" }, { "answer_id": 37511, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 2, "selected": false, "text": "needle.findIn(haystack) pattern.findIn(text) haystack.find(needle) words.hasAWordWithPrefix(prefix) searcher.find(needle, haystack)" }, { "answer_id": 49082, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "needle = haystack.findNeedle()\n needle = searcher.findNeedle(haystack)\n" }, { "answer_id": 60803, "author": "user6246", "author_id": 6246, "author_profile": "https://Stackoverflow.com/users/6246", "pm_score": 2, "selected": false, "text": "seeker.find(needle, space) seeker.find(needle, space, strategy) seeker.find(needle, haystack) seeker.find(needle, haystack, strategy) needle.find(space) needle.find(haystack)" }, { "answer_id": 266251, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 1, "selected": false, "text": "Needle needle = (Needle)haystack.searchByName(\"needle\");\n Needle needle = (Needle)haystack.searchWithFilter(new Filter(){\n public boolean isWhatYouNeed(Object obj)\n {\n return obj instanceof Needle;\n }\n});\n Needle needle = (Needle)haystack.searchByPattern(Size.SMALL, \n Sharpness.SHARP, \n Material.METAL);\n" }, { "answer_id": 287382, "author": "Varun Mahajan", "author_id": 6613, "author_profile": "https://Stackoverflow.com/users/6613", "pm_score": 0, "selected": false, "text": "public Interface IToBeSearched\n{}\n\npublic Interface ISearchable\n{\n\n public void Find(IToBeSearched a);\n\n}\n\nClass Needle Implements IToBeSearched\n{}\n\nClass Haystack Implements ISearchable\n{\n\n public void Find(IToBeSearched needle)\n\n {\n\n //Here goes the original coding of find function\n\n }\n\n}\n" }, { "answer_id": 1770119, "author": "Jason Orendorff", "author_id": 94977, "author_profile": "https://Stackoverflow.com/users/94977", "pm_score": 1, "selected": false, "text": "needle = findNeedleIn(haystack);\n SynchronizedHaystackSearcherProxyFactory proxyFactory =\n SynchronizedHaystackSearcherProxyFactory.getInstance();\nStrategyBasedHaystackSearcher searcher =\n new BasicStrategyBasedHaystackSearcher(\n NeedleSeekingStrategies.getMethodicalInstance());\nSynchronizedHaystackSearcherProxy proxy =\n proxyFactory.createSynchronizedHaystackSearcherProxy(searcher);\nSearchableHaystackAdapter searchableHaystack =\n new SearchableHaystackAdapter(haystack);\nFindableSearchResultObject foundObject = null;\nwhile (!HaystackSearcherUtil.isNeedleObject(foundObject)) {\n try {\n foundObject = proxy.find(searchableHaystack);\n } catch (GruesomeInjuryException exc) {\n returnPitchforkToShed(); // sigh, i hate it when this happens\n HaystackSearcherUtil.cleanUp(hay); // XXX fixme not really thread-safe,\n // but we can't just leave this mess\n HaystackSearcherUtil.cleanup(exc.getGruesomeMess()); // bug 510000884\n throw exc; // caller will catch this and get us to a hospital,\n // if it's not already too late\n }\n}\nreturn (Needle) BarnyardObjectProtocolUtil.createSynchronizedFindableSearchResultObjectProxyAdapterUnwrapperForToolInterfaceName(SimpleToolInterfaces.NEEDLE_INTERFACE_NAME).adapt(foundObject.getAdaptable());\n" }, { "answer_id": 11927019, "author": "Display Name", "author_id": 1418097, "author_profile": "https://Stackoverflow.com/users/1418097", "pm_score": 0, "selected": false, "text": "haystack.iterator.findFirst(/* pass here a predicate returning\n true if its argument is a needle that we want */)\n iterator findFirst(fun: T => Boolean) haystack" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
23,763
<p>I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.</p>
[ { "answer_id": 23795, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 3, "selected": false, "text": "Y = 0.3*R + 0.59*G + 0.11*B ((R1+Y)/2,(G1+Y)/2,(B1+Y)/2) (R1,G1,B1)" }, { "answer_id": 27185, "author": "Bernie Perez", "author_id": 1992, "author_profile": "https://Stackoverflow.com/users/1992", "pm_score": 3, "selected": true, "text": "protected LookupOp createColorizeOp(short R1, short G1, short B1) {\n short[] alpha = new short[256];\n short[] red = new short[256];\n short[] green = new short[256];\n short[] blue = new short[256];\n\n int Y = 0.3*R + 0.59*G + 0.11*B\n\n for (short i = 0; i < 256; i++) {\n alpha[i] = i;\n red[i] = (R1 + i*.3)/2;\n green[i] = (G1 + i*.59)/2;\n blue[i] = (B1 + i*.11)/2;\n }\n\n short[][] data = new short[][] {\n red, green, blue, alpha\n };\n\n LookupTable lookupTable = new ShortLookupTable(0, data);\n return new LookupOp(lookupTable, null);\n}\n BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);\nBufferedImage targetImage = colorizeFilter.filter(sourceImage, null);\n" }, { "answer_id": 4720882, "author": "nwodb.com", "author_id": 579450, "author_profile": "https://Stackoverflow.com/users/579450", "pm_score": 1, "selected": false, "text": "public class Colorize {\n\npublic static final int MAX_COLOR = 256;\n\npublic static final float LUMINANCE_RED = 0.2126f;\npublic static final float LUMINANCE_GREEN = 0.7152f;\npublic static final float LUMINANCE_BLUE = 0.0722f;\n\ndouble hue = 180;\ndouble saturation = 50;\ndouble lightness = 0;\n\nint [] lum_red_lookup;\nint [] lum_green_lookup;\nint [] lum_blue_lookup;\n\nint [] final_red_lookup;\nint [] final_green_lookup;\nint [] final_blue_lookup;\n\npublic Colorize( int red, int green, int blue )\n{\n doInit();\n}\n\npublic Colorize( double t_hue, double t_sat, double t_bri )\n{\n hue = t_hue;\n saturation = t_sat;\n lightness = t_bri;\n doInit();\n}\n\npublic Colorize( double t_hue, double t_sat )\n{\n hue = t_hue;\n saturation = t_sat;\n doInit();\n}\n\npublic Colorize( double t_hue )\n{\n hue = t_hue;\n doInit();\n}\n\npublic Colorize()\n{\n doInit();\n}\n\nprivate void doInit()\n{\n lum_red_lookup = new int [MAX_COLOR];\n lum_green_lookup = new int [MAX_COLOR];\n lum_blue_lookup = new int [MAX_COLOR];\n\n double temp_hue = hue / 360f;\n double temp_sat = saturation / 100f;\n\n final_red_lookup = new int [MAX_COLOR];\n final_green_lookup = new int [MAX_COLOR];\n final_blue_lookup = new int [MAX_COLOR];\n\n for( int i = 0; i < MAX_COLOR; ++i )\n {\n lum_red_lookup [i] = ( int )( i * LUMINANCE_RED );\n lum_green_lookup[i] = ( int )( i * LUMINANCE_GREEN );\n lum_blue_lookup [i] = ( int )( i * LUMINANCE_BLUE );\n\n double temp_light = (double)i / 255f;\n\n Color color = new Color( Color.HSBtoRGB( (float)temp_hue, \n (float)temp_sat, \n (float)temp_light ) );\n\n final_red_lookup [i] = ( int )( color.getRed() );\n final_green_lookup[i] = ( int )( color.getGreen() );\n final_blue_lookup [i] = ( int )( color.getBlue() );\n }\n}\n\npublic void doColorize( BufferedImage image )\n{\n int height = image.getHeight();\n int width;\n\n while( height-- != 0 )\n {\n width = image.getWidth();\n\n while( width-- != 0 )\n {\n Color color = new Color( image.getRGB( width, height ) );\n\n int lum = lum_red_lookup [color.getRed ()] +\n lum_green_lookup[color.getGreen()] +\n lum_blue_lookup [color.getBlue ()];\n\n if( lightness > 0 )\n {\n lum = (int)((double)lum * (100f - lightness) / 100f);\n lum += 255f - (100f - lightness) * 255f / 100f;\n }\n else if( lightness < 0 )\n {\n lum = (int)(((double)lum * lightness + 100f) / 100f);\n }\n\n Color final_color = new Color( final_red_lookup[lum],\n final_green_lookup[lum],\n final_blue_lookup[lum],\n color.getAlpha() );\n\n image.setRGB( width, height, final_color.getRGB() );\n\n }\n }\n}\n" }, { "answer_id": 20411373, "author": "0circle0", "author_id": 3072177, "author_profile": "https://Stackoverflow.com/users/3072177", "pm_score": 2, "selected": false, "text": "import java.awt.Color;\nimport java.awt.image.BufferedImage;\n\npublic class Colorizer\n{\n public static final int MAX_COLOR = 256;\n\n public static final float LUMINANCE_RED = 0.2126f;\n public static final float LUMINANCE_GREEN = 0.7152f;\n public static final float LUMINANCE_BLUE = 0.0722f;\n\n double hue = 180;\n double saturation = 50;\n double lightness = 0;\n\n int[] lum_red_lookup;\n int[] lum_green_lookup;\n int[] lum_blue_lookup;\n\n int[] final_red_lookup;\n int[] final_green_lookup;\n int[] final_blue_lookup;\n\n public Colorizer()\n {\n doInit();\n }\n\n public void doHSB(double t_hue, double t_sat, double t_bri, BufferedImage image)\n {\n hue = t_hue;\n saturation = t_sat;\n lightness = t_bri;\n doInit();\n doColorize(image);\n }\n\n private void doInit()\n {\n lum_red_lookup = new int[MAX_COLOR];\n lum_green_lookup = new int[MAX_COLOR];\n lum_blue_lookup = new int[MAX_COLOR];\n\n double temp_hue = hue / 360f;\n double temp_sat = saturation / 100f;\n\n final_red_lookup = new int[MAX_COLOR];\n final_green_lookup = new int[MAX_COLOR];\n final_blue_lookup = new int[MAX_COLOR];\n\n for (int i = 0; i < MAX_COLOR; ++i)\n {\n lum_red_lookup[i] = (int) (i * LUMINANCE_RED);\n lum_green_lookup[i] = (int) (i * LUMINANCE_GREEN);\n lum_blue_lookup[i] = (int) (i * LUMINANCE_BLUE);\n\n double temp_light = (double) i / 255f;\n\n Color color = new Color(Color.HSBtoRGB((float) temp_hue, (float) temp_sat, (float) temp_light));\n\n final_red_lookup[i] = (int) (color.getRed());\n final_green_lookup[i] = (int) (color.getGreen());\n final_blue_lookup[i] = (int) (color.getBlue());\n }\n }\n\n public void doColorize(BufferedImage image)\n {\n int height = image.getHeight();\n int width;\n\n while (height-- != 0)\n {\n width = image.getWidth();\n\n while (width-- != 0)\n {\n Color color = new Color(image.getRGB(width, height), true);\n\n int lum = lum_red_lookup[color.getRed()] + lum_green_lookup[color.getGreen()] + lum_blue_lookup[color.getBlue()];\n\n if (lightness > 0)\n {\n lum = (int) ((double) lum * (100f - lightness) / 100f);\n lum += 255f - (100f - lightness) * 255f / 100f;\n }\n else if (lightness < 0)\n {\n lum = (int) (((double) lum * (lightness + 100f)) / 100f);\n }\n Color final_color = new Color(final_red_lookup[lum], final_green_lookup[lum], final_blue_lookup[lum], color.getAlpha());\n image.setRGB(width, height, final_color.getRGB());\n }\n }\n }\n\n public BufferedImage changeContrast(BufferedImage inImage, float increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n for (int i = 0; i < w; i++)\n {\n for (int j = 0; j < h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n float fr, fg, fb;\n\n r = color.getRed();\n fr = (r - 128) * increasingFactor + 128;\n r = (int) fr;\n r = keep256(r);\n\n g = color.getGreen();\n fg = (g - 128) * increasingFactor + 128;\n g = (int) fg;\n g = keep256(g);\n\n b = color.getBlue();\n fb = (b - 128) * increasingFactor + 128;\n b = (int) fb;\n b = keep256(b);\n\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeGreen(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i < w; i++)\n {\n for (int j = 0; j < h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = color.getRed();\n g = keep256(color.getGreen() + increasingFactor);\n b = color.getBlue();\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeBlue(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i < w; i++)\n {\n for (int j = 0; j < h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = color.getRed();\n g = color.getGreen();\n b = keep256(color.getBlue() + increasingFactor);\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeRed(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i < w; i++)\n {\n for (int j = 0; j < h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = keep256(color.getRed() + increasingFactor);\n g = color.getGreen();\n b = color.getBlue();\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeBrightness(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i < w; i++)\n {\n for (int j = 0; j < h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n\n int r, g, b, a;\n\n r = keep256(color.getRed() + increasingFactor);\n g = keep256(color.getGreen() + increasingFactor);\n b = keep256(color.getBlue() + increasingFactor);\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public int keep256(int i)\n {\n if (i <= 255 && i >= 0)\n return i;\n if (i > 255)\n return 255;\n return 0;\n }\n}\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
23,787
<p>What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.</p> <p>Currently I use code like this:</p> <pre><code>// mObjList is a List&lt;MyObject&gt; MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } </code></pre> <p>or</p> <pre><code>// mObjList is a List&lt;MyObject&gt; bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } } </code></pre>
[ { "answer_id": 23794, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "break T Find<T>(IEnumerable<T> items, Predicate<T> p) {\n foreach (T item in items)\n if (p(item))\n return item;\n\n return null;\n}\n" }, { "answer_id": 23799, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });\n result = mObjList.Find(x => x.ID == magicNumber);\n" }, { "answer_id": 23800, "author": "Todd", "author_id": 2572, "author_profile": "https://Stackoverflow.com/users/2572", "pm_score": 2, "selected": false, "text": "List<MyObject> list = new List<MyObject>();\n\n// populate the list with objects..\n\nreturn list.Find(o => o.Id == myCriteria);\n" }, { "answer_id": 23830, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": " static void Main(string[] args)\n {\n for (int kk = 0; kk < 10; kk++)\n {\n List<int> tmp = new List<int>();\n for (int i = 0; i < 100; i++)\n tmp.Add(i);\n int sum = 0;\n long start = DateTime.Now.Ticks;\n for (int i = 0; i < 1000000; i++)\n sum += tmp.Find(delegate(int x) { return x == 3; });\n Console.WriteLine(\"Anonymous delegates: \" + (DateTime.Now.Ticks - start));\n\n\n start = DateTime.Now.Ticks;\n sum = 0;\n for (int i = 0; i < 1000000; i++)\n {\n int match = 0;\n for (int j = 0; j < tmp.Count; j++)\n {\n if (tmp[j] == 3)\n {\n match = tmp[j];\n break;\n }\n }\n sum += match;\n }\n Console.WriteLine(\"Classic C++ Style: \" + (DateTime.Now.Ticks - start));\n Console.WriteLine();\n }\n }\n Anonymous delegates: 710000\nClassic C++ Style: 340000\n\nAnonymous delegates: 630000\nClassic C++ Style: 320000\n\nAnonymous delegates: 630000\nClassic C++ Style: 330000\n\nAnonymous delegates: 630000\nClassic C++ Style: 320000\n\nAnonymous delegates: 610000\nClassic C++ Style: 340000\n\nAnonymous delegates: 630000\nClassic C++ Style: 330000\n\nAnonymous delegates: 650000\nClassic C++ Style: 330000\n\nAnonymous delegates: 620000\nClassic C++ Style: 330000\n\nAnonymous delegates: 620000\nClassic C++ Style: 340000\n\nAnonymous delegates: 620000\nClassic C++ Style: 400000\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
23,802
<p>I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. </p> <p>Currently, I'm just using <a href="http://php.net/manual/en/function.include-once.php" rel="nofollow noreferrer">include_once</a> to include the classes I access directly. Each of those would <code>include_once</code> the classes that they access. </p> <p>I've looked into using the <code>__autoload</code> function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. <strong><em>Also, I'm not sure how this effects classes with the same name in different namespaces.</em></strong> </p> <p><strong>Is there an easier way to handle this?</strong> </p> <p>Or is PHP just not suited to "<strong>enterprisey</strong>" type applications with lots of different objects all located in separate files that can be in many different directories.</p>
[ { "answer_id": 23805, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "__autoload __autoload" }, { "answer_id": 23806, "author": "JasonMichael", "author_id": 1935, "author_profile": "https://Stackoverflow.com/users/1935", "pm_score": 0, "selected": false, "text": "__autoload" }, { "answer_id": 23829, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 2, "selected": false, "text": "spl_autoload_register('load_controllers');\nspl_autoload_register('load_models');\n\nfunction load_models($class){\n if( !file_exists(\"models/$class.php\") )\n return false;\n\n include \"models/$class.php\";\n return true;\n}\nfunction load_controllers($class){\n if( !file_exists(\"controllers/$class.php\") )\n return false;\n\n include \"controllers/$class.php\";\n return true;\n}\n" }, { "answer_id": 23872, "author": "Brock Boland", "author_id": 2185, "author_profile": "https://Stackoverflow.com/users/2185", "pm_score": 0, "selected": false, "text": "classes/User.php classes/User.class.php classes/Model/User.php classes User classes/User.php classes/Models/User.php classes/Utility/User.php User.php classes User" }, { "answer_id": 24074, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "__autoload" }, { "answer_id": 24106, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 4, "selected": true, "text": "setup.php define('MAP', 'var/cache/autoload.map');\nerror_reporting(E_ALL);\nrequire 'setup.php';\nprint(buildAutoloaderMap() . \" classes mapped\\n\");\n\nfunction buildAutoloaderMap() {\n $dirs = array('lib', 'view', 'model');\n $cache = array();\n $n = 0;\n foreach ($dirs as $dir) {\n foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) {\n $fn = $entry->getFilename();\n if (!preg_match('/\\.class\\.php$/', $fn))\n continue;\n $c = str_replace('.class.php', '', $fn);\n if (!class_exists($c)) {\n $cache[$c] = ($pn = $entry->getPathname());\n ++$n;\n }\n }\n }\n ksort($cache);\n file_put_contents(MAP, serialize($cache));\n return $n;\n}\n define('MAP', 'var/cache/autoload.map');\n\nfunction __autoload($className) {\n static $map;\n $map or ($map = unserialize(file_get_contents(MAP)));\n $fn = array_key_exists($className, $map) ? $map[$className] : null;\n if ($fn and file_exists($fn)) {\n include $fn;\n unset($map[$className]);\n }\n}\n autobuild.php" }, { "answer_id": 24137, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 1, "selected": false, "text": "Zend_Loader::loadClass(\"Zend_Db_Table\");" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
23,853
<p>I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:</p> <blockquote> <p><strong>Name</strong>: Fernando</p> <p><strong>Age</strong>: {person.age}</p> <p><strong>Sex</strong>: Male</p> </blockquote> <p>I would like to know how to hide it!</p>
[ { "answer_id": 23879, "author": "Jason Sparks", "author_id": 512, "author_profile": "https://Stackoverflow.com/users/512", "pm_score": 7, "selected": true, "text": "$!variable\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
23,867
<p>The <code>Close</code> method on an <code>ICommunicationObject</code> can throw two types of exceptions as MSDN outlines <a href="http://msdn.microsoft.com/en-us/library/ms195520.aspx" rel="nofollow noreferrer">here</a>. I understand why the <code>Close</code> method can throw those exceptions, but what I don't understand is why the <code>Dispose</code> method on a service proxy calls the <code>Close</code> method without a <code>try</code> around it. Isn't your <code>Dispose</code> method the one place where you want make sure you don't throw any exceptions?</p>
[ { "answer_id": 23879, "author": "Jason Sparks", "author_id": 512, "author_profile": "https://Stackoverflow.com/users/512", "pm_score": 7, "selected": true, "text": "$!variable\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
23,899
<p>I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development.</p> <p>One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on.</p> <p>Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?)</p> <p>I'd love to get some unit testing going for business logic too, but maybe I'm asking too much?</p> <h3>Update:</h3> <p>There are over 200 ASP scripts in the project, some thousands of lines long ;) UGH!</p> <p>We may opt for the &quot;big rewrite&quot; but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti.</p>
[ { "answer_id": 60404, "author": "Christopher Mahan", "author_id": 479, "author_profile": "https://Stackoverflow.com/users/479", "pm_score": 5, "selected": true, "text": "<font size=3>crap</font>" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2477/" ]
23,907
<p>Basically I want to get the number of lines-of-code in the repository after each commit.</p> <p>The only (really crappy) ways I have found is to use <code>git filter-branch</code> to run <code>wc -l *</code>, and a script that runs <code>git reset --hard</code> on each commit, then runs <code>wc -l</code></p> <p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):</p> <pre class="lang-none prettyprint-override"><code>me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 </code></pre> <p>I've played around with the ruby 'git' library, but the closest I found was using the <code>.lines()</code> method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)</p> <pre class="lang-rb prettyprint-override"><code>require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end </code></pre>
[ { "answer_id": 35664, "author": "fserb", "author_id": 3702, "author_profile": "https://Stackoverflow.com/users/3702", "pm_score": 5, "selected": false, "text": "git log --shortstat --reverse --pretty=oneline\n #!/usr/bin/python\n\n\"\"\"\nDisplay the per-commit size of the current git branch.\n\"\"\"\n\nimport subprocess\nimport re\nimport sys\n\ndef main(argv):\n git = subprocess.Popen([\"git\", \"log\", \"--shortstat\", \"--reverse\",\n \"--pretty=oneline\"], stdout=subprocess.PIPE)\n out, err = git.communicate()\n total_files, total_insertions, total_deletions = 0, 0, 0\n for line in out.split('\\n'):\n if not line: continue\n if line[0] != ' ': \n # This is a description line\n hash, desc = line.split(\" \", 1)\n else:\n # This is a stat line\n data = re.findall(\n ' (\\d+) files changed, (\\d+) insertions\\(\\+\\), (\\d+) deletions\\(-\\)', \n line)\n files, insertions, deletions = ( int(x) for x in data[0] )\n total_files += files\n total_insertions += insertions\n total_deletions += deletions\n print \"%s: %d files, %d lines\" % (hash, total_files,\n total_insertions - total_deletions)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
23,918
<p>I'm trying to do a simple rotation in OpenGL but must be missing the point. I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.</p> <p>At the moment I have code like this:</p> <pre><code>glPushMatrix(); glRotatef(90.0, 0.0, 1.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f( 1.0, 1.0, 0.0 ); glVertex3f( 3.0, 2.0, 0.0 ); glVertex3f( 3.0, 1.0, 0.0 ); glEnd(); glPopMatrix(); </code></pre> <p>But the result is not a triangle rotated 90 degrees.</p> <p><strong>Edit</strong> Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. </p>
[ { "answer_id": 23925, "author": "spate", "author_id": 2276, "author_profile": "https://Stackoverflow.com/users/2276", "pm_score": 3, "selected": false, "text": "glMatrixMode(GL_MODELVIEW);\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
23,930
<p>I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.</p> <h2>Ideas:</h2> <ul> <li>Procedural</li> <li>Functional</li> <li>Object Oriented</li> <li>One liners</li> <li>Obfuscated</li> <li>Oddball</li> <li>Bad Code</li> <li><a href="http://en.wikipedia.org/wiki/Polyglot_%28computing%29" rel="nofollow noreferrer">Polyglot</a></li> </ul> <p>Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.</p> <p>Please limit it to one example per entry. I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.</p> <p>The only real requirement is it must find the factorial of a given argument, in all languages represented.</p> <h1>Be Creative!</h1> <h2>Recommended Guideline:</h2> <pre> # Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here </pre> <p>I will ocasionally go along and edit any answer that does not have decent formatting.</p>
[ { "answer_id": 23932, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "multi factorial ( Int $n where { $n <= 0 } ){\n return 1;\n}\nmulti factorial ( Int $n ){\n return $n * factorial( $n-1 );\n}\n multi factorial(0) { 1 }\nmulti factorial(Int $n) { $n * factorial($n - 1) }\n" }, { "answer_id": 23936, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "sub factorial ( int $n ){\n\n my $result = 1;\n\n loop ( ; $n > 0; $n-- ){\n\n $result *= $n;\n\n }\n\n return $result;\n}\n" }, { "answer_id": 23938, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": " int factorial(int x) {\n int product = 1;\n\n for (int i = x; i > 0; i--) {\n product *= i;\n }\n\n return product;\n }\n" }, { "answer_id": 23958, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 2, "selected": false, "text": "factorial = function( n )\n{\n return n > 0 ? n * factorial( n - 1 ) : 1;\n}\n" }, { "answer_id": 23969, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 4, "selected": false, "text": "ones = 1 : ones\nintegers = head ones : zipWith (+) integers (tail ones)\nfactorials = head integers : zipWith (*) factorials (tail integers)\n" }, { "answer_id": 23976, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 3, "selected": false, "text": "(define (factorial x)\n (if (= x 0) 1\n (* x (factorial (- x 1)))))\n (define factorial\n (letrec ((fact (lambda (x accum)\n (if (= x 0) accum\n (fact (- x 1) (* accum x))))))\n (lambda (x)\n (fact x 1))))\n" }, { "answer_id": 23979, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 1, "selected": false, "text": "factorial(int n)\n{\n for(int i=1, f = 1; i<=n; i++)\n f *= i;\n return f;\n}\n" }, { "answer_id": 23982, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 3, "selected": false, "text": "unsigned long factorial(int n)\n{\n unsigned long factorial = 1;\n int i;\n\n for (i = 2; i <= n; i++)\n factorial *= i;\n\n return factorial;\n}\n function factorial($n)\n{\n for ($factorial = 1, $i = 2; $i <= $n; $i++)\n $factorial *= $i;\n\n return $factorial;\n}\n" }, { "answer_id": 23989, "author": "Ed.", "author_id": 522, "author_profile": "https://Stackoverflow.com/users/522", "pm_score": 7, "selected": false, "text": "HAI\nCAN HAS STDIO?\nI HAS A VAR\nI HAS A INT\nI HAS A CHEEZBURGER\nI HAS A FACTORIALNUM\nIM IN YR LOOP\n UP VAR!!1\n TIEMZD INT!![CHEEZBURGER]\n UP FACTORIALNUM!!1\n IZ VAR BIGGER THAN FACTORIALNUM? GTFO\nIM OUTTA YR LOOP\nU SEEZ INT\nKTHXBYE \n" }, { "answer_id": 24296, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "template factorial(int n : 1)\n{\n const factorial = 1;\n}\n\ntemplate factorial(int n)\n{\n const factorial =\n n * factorial!(n-1);\n}\n template factorial(int n)\n{\n static if(n == 1)\n const factorial = 1;\n else \n const factorial =\n n * factorial!(n-1);\n}\n factorial!(5)\n" }, { "answer_id": 24300, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 2, "selected": false, "text": "def fact(x): \n return (1 if x==0 else x * fact(x-1))\n import operator\n\ndef fact(x):\n return reduce(operator.mul, xrange(1, x+1))\n" }, { "answer_id": 24343, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 2, "selected": false, "text": "(* returns pure function *)\n(FixedPoint[(If[#[[2]]>1,{#[[1]]*#[[2]],#[[2]]-1},#])&,{1,n}][[1]])&\n\n(* not using built-in, returns pure function, don't use: might build 1..n list *)\n(Times @@ Range[#])&\n" }, { "answer_id": 24524, "author": "Josh Brown", "author_id": 2030, "author_profile": "https://Stackoverflow.com/users/2030", "pm_score": 1, "selected": false, "text": "int factorial(int x) {\n return x == 0 ? 1 : x * factorial(x-1);\n}\n" }, { "answer_id": 27114, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 2, "selected": false, "text": "(If[#>1,# #0[#-1],1])&\n" }, { "answer_id": 27142, "author": "krujos", "author_id": 511, "author_profile": "https://Stackoverflow.com/users/511", "pm_score": 2, "selected": false, "text": "def factorial(n)\n return 1 if n == 1\n n * factorial(n -1)\nend\n" }, { "answer_id": 27149, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "function factorial (n)\n if (n <= 1) then return 1 end\n return n*factorial(n-1)\nend\n > print (factorial(234132))\nstdin:3: stack overflow\nstack traceback:\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n ...\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:1: in main chunk\n [C]: ?\n" }, { "answer_id": 37416, "author": "Chris Smith", "author_id": 322, "author_profile": "https://Stackoverflow.com/users/322", "pm_score": 3, "selected": false, "text": "let rec fact x = \n if x < 0 then failwith \"Invalid value.\"\n elif x = 0 then 1\n else x * fact (x - 1)\n let fact x = [1 .. x] |> List.fold_left ( * ) 1\n" }, { "answer_id": 37421, "author": "Andres", "author_id": 1815, "author_profile": "https://Stackoverflow.com/users/1815", "pm_score": 1, "selected": false, "text": " fact 0 = 1\n fact n = n * fact (n-1)\n" }, { "answer_id": 37427, "author": "Chris de Vries", "author_id": 3836, "author_profile": "https://Stackoverflow.com/users/3836", "pm_score": 6, "selected": false, "text": "template<unsigned int n>\nstruct factorial {\n enum { result = n * factorial<n - 1>::result };\n};\n\ntemplate<>\nstruct factorial<0> {\n enum { result = 1 };\n};\n const unsigned int x = factorial<4>::result;\n" }, { "answer_id": 37459, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "long f(long n)\n{\n long r=1;\n for (long i=1; i<n; i++)\n r=r*i;\n return r;\n}\n\nlong factorial(long n)\n{\n // iterative implementation should be efficient\n long result;\n for (long i=0; i<f(n); i++)\n result=result+1;\n return result;\n}\n" }, { "answer_id": 37576, "author": "Chris de Vries", "author_id": 3836, "author_profile": "https://Stackoverflow.com/users/3836", "pm_score": 4, "selected": false, "text": "section .text\n global factorial\n; factorial in x86-64 - n is passed in via RDI register\n; takes a 64-bit unsigned integer\n; returns a 64-bit unsigned integer in RAX register\n; C declaration in GCC:\n; extern unsigned long long factorial(unsigned long long n);\nfactorial:\n enter 0,0\n ; n is placed in rdi by caller\n mov rax, 1 ; factorial = 1\n mov rcx, 2 ; i = 2\nloopstart:\n cmp rcx, rdi\n ja loopend\n mul rcx ; factorial *= i\n inc rcx\n jmp loopstart\nloopend:\n leave\n ret\n" }, { "answer_id": 37647, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<Extension()> _\nPublic Function Product(ByVal xs As IEnumerable(Of Integer)) As Integer\n Return xs.Aggregate(1, Function(a, b) a * b)\nEnd Function\n\nPublic Function Fact(ByVal n As Integer) As Integer\n Return Aggregate x In Enumerable.Range(1, n) Into Product()\nEnd Function\n Aggregate" }, { "answer_id": 37664, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": false, "text": "function factorial( [int] $n ) \n{ \n $result = 1; \n\n if ( $n -gt 1 ) \n { \n $result = $n * ( factorial ( $n - 1 ) ) \n } \n\n $result \n}\n $n..1 | % {$result = 1}{$result *= $_}{$result}\n" }, { "answer_id": 37736, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "fac(0,1).\nfac(N,X) :- N1 is N -1, fac(N1, T), X is N * T.\n fac(0,N,N).\nfac(X,N,T) :- A is N * X, X1 is X - 1, fac(X1,A,T).\nfac(N,T) :- fac(N,1,T).\n" }, { "answer_id": 37814, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 1, "selected": false, "text": "factorial() {\n if [ $1 -eq 0 ]\n then\n echo 1\n return\n fi\n\n a=`expr $1 - 1`\n expr $1 \\* `factorial $a`\n}\n" }, { "answer_id": 37847, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 1, "selected": false, "text": "(defun factorial (x) \n (if (<= x 1) \n 1 \n (* x (factorial (- x 1)))))\n" }, { "answer_id": 37906, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 1, "selected": false, "text": "var f = function(n){\n if(n>1){\n return arguments.callee(n-1)*n;\n }\n return 1;\n}\n" }, { "answer_id": 38369, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": false, "text": "Gamma n = (n-1)! let rec gamma z =\n let pi = 4.0 *. atan 1.0 in\n if z < 0.5 then\n pi /. ((sin (pi*.z)) *. (gamma (1.0 -. z)))\n else\n let consts = [| 0.99999999999980993; 676.5203681218851; -1259.1392167224028;\n 771.32342877765313; -176.61502916214059; 12.507343278686905;\n -0.13857109526572012; 9.9843695780195716e-6; 1.5056327351493116e-7;\n |] \n in\n let z = z -. 1.0 in\n let results = Array.fold_right \n (fun x y -> x +. y)\n (Array.mapi \n (fun i x -> if i = 0 then x else x /. (z+.(float i)))\n consts\n )\n 0.0\n in\n let x = z +. (float (Array.length consts)) -. 1.5 in\n let final = (sqrt (2.0*.pi)) *. \n (x ** (z+.0.5)) *.\n (exp (-.x)) *. result\n in\n final\n\nlet factorial_gamma n = int_of_float (gamma (float (n+1)))\n" }, { "answer_id": 38399, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "int f(int n) { for (int i = n - 1; i > 0; n *= i, i--); return n ? n : 1; }\n" }, { "answer_id": 38423, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 3, "selected": false, "text": "10 HOME\n20 INPUT N\n30 LET ANS = 1\n40 FOR I = 1 TO N\n50 ANS = ANS * I\n60 NEXT I\n70 PRINT ANS\n" }, { "answer_id": 38484, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 3, "selected": false, "text": "private static Map<BigInteger, BigInteger> _results = new HashMap()\n\npublic static BigInteger factorial(BigInteger n){\n if (0 >= n.compareTo(BigInteger.ONE))\n return BigInteger.ONE.max(n);\n if (_results.containsKey(n))\n return _results.get(n);\n BigInteger result = factorial(n.subtract(BigInteger.ONE)).multiply(n);\n _results.put(n, result);\n return result;\n}\n" }, { "answer_id": 38673, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 2, "selected": false, "text": "(define (factorial n)\n (define (fac-times n acc)\n (if (= n 0)\n acc\n (fac-times (- n 1) (* acc n))))\n (if (< n 0)\n (display \"Wrong argument!\")\n (fac-times n 1)))\n" }, { "answer_id": 38717, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": false, "text": "@echo off\n\nset n=%1\nset result=1\n\nfor /l %%i in (%n%, -1, 1) do (\n set /a result=result * %%i\n)\n\necho %result%\n" }, { "answer_id": 38734, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 0, "selected": false, "text": "factorial n = factorial' n 1\n\nfactorial' 0 a = a\nfactorial' n a = factorial' (n-1) (n*a)\n" }, { "answer_id": 38781, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 2, "selected": false, "text": "data Nat = zero | suc (m::Nat)\n\nadd (m::Nat) (n::Nat) :: Nat\n = case m of\n (zero ) -> n\n (suc p) -> suc (add p n)\n\nmul (m::Nat) (n::Nat)::Nat\n = case m of\n (zero ) -> zero\n (suc p) -> add n (mul p n)\n\nfactorial (n::Nat)::Nat \n = case n of\n (zero ) -> suc zero\n (suc p) -> mul n (factorial p)\n" }, { "answer_id": 38935, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 5, "selected": false, "text": "public static int Factorial(int f)\n{ \n if (f<0 || f>12)\n {\n throw new ArgumentException(\"Out of range for integer factorial\");\n }\n int [] fact={1,1,2,6,24,120,720,5040,40320,362880,3628800,\n 39916800,479001600};\n return fact[f];\n}\n" }, { "answer_id": 43858, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "facts: array[2..12] of integer;\n\nfunction TForm1.calculate(f: integer): integer;\nbegin\n if f = 1 then\n Result := f\n else if f > High(facts) then\n Result := High(Integer)\n else if (facts[f] > 0) then\n Result := facts[f]\n else begin\n facts[f] := f * Calculate(f-1);\n Result := facts[f];\n end;\nend;\n\ninitialize\n\n for i := Low(facts) to High(facts) do\n facts[i] := 0;\n" }, { "answer_id": 49300, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 5, "selected": false, "text": "K(SII(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(K(S(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))))))))K))))))(S(K(S(K(S(SI(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))(S(S(KS)K))(S(SII)I(S(S(KS)K)I))))))))K)))))))\n (S(S(KS)K)(K(S(S(KS)K)))))))))(K(S(K(S(S(KS)K)))K))))(SII))II)\n (lazy-def '(fac input)\n '((Y (lambda (f n a) ((lambda (b) ((cons 10) ((b (cons 42)) (f (1+ n) b))))\n (* a n)))) 1 1))\n" }, { "answer_id": 49312, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": " public static int factorial(int n)\n {\n return (Enumerable.Range(1, n).Aggregate(1, (previous, value) => previous * value));\n }\n" }, { "answer_id": 49444, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 3, "selected": false, "text": "class Number\n{\n public Number ()\n {\n m_number = \"0\";\n }\n\n public Number (string value)\n {\n m_number = value;\n }\n\n public int this [int column]\n {\n get\n {\n return column < m_number.Length ? m_number [m_number.Length - column - 1] - '0' : 0;\n }\n }\n\n public static implicit operator Number (string rhs)\n {\n return new Number (rhs);\n }\n\n public static bool operator == (Number lhs, Number rhs)\n {\n return lhs.m_number == rhs.m_number;\n }\n\n public static bool operator != (Number lhs, Number rhs)\n {\n return lhs.m_number != rhs.m_number;\n }\n\n public override bool Equals (object obj)\n {\n return this == (Number) obj;\n }\n\n public override int GetHashCode ()\n {\n return m_number.GetHashCode ();\n }\n\n public static Number operator + (Number lhs, Number rhs)\n {\n StringBuilder\n result = new StringBuilder (new string ('0', lhs.m_number.Length + rhs.m_number.Length));\n\n int\n carry = 0;\n\n for (int i = 0 ; i < result.Length ; ++i)\n {\n int\n sum = carry + lhs [i] + rhs [i],\n units = sum % 10;\n\n carry = sum / 10;\n\n result [result.Length - i - 1] = (char) ('0' + units);\n }\n\n return TrimLeadingZeros (result);\n }\n\n public static Number operator * (Number lhs, Number rhs)\n {\n StringBuilder\n result = new StringBuilder (new string ('0', lhs.m_number.Length + rhs.m_number.Length));\n\n for (int multiplier_index = rhs.m_number.Length - 1 ; multiplier_index >= 0 ; --multiplier_index)\n {\n int\n multiplier = rhs.m_number [multiplier_index] - '0',\n column = result.Length - rhs.m_number.Length + multiplier_index;\n\n for (int i = lhs.m_number.Length - 1 ; i >= 0 ; --i, --column)\n {\n int\n product = (lhs.m_number [i] - '0') * multiplier,\n units = product % 10,\n tens = product / 10,\n hundreds = 0,\n unit_sum = result [column] - '0' + units;\n\n if (unit_sum > 9)\n {\n unit_sum -= 10;\n ++tens;\n }\n\n result [column] = (char) ('0' + unit_sum);\n\n int\n tens_sum = result [column - 1] - '0' + tens;\n\n if (tens_sum > 9)\n {\n tens_sum -= 10;\n ++hundreds;\n }\n\n result [column - 1] = (char) ('0' + tens_sum);\n\n if (hundreds > 0)\n {\n int\n hundreds_sum = result [column - 2] - '0' + hundreds;\n\n result [column - 2] = (char) ('0' + hundreds_sum);\n }\n }\n }\n\n return TrimLeadingZeros (result);\n }\n\n public override string ToString ()\n {\n return m_number;\n }\n\n static string TrimLeadingZeros (StringBuilder number)\n {\n while (number [0] == '0' && number.Length > 1)\n {\n number.Remove (0, 1);\n }\n\n return number.ToString ();\n }\n\n string\n m_number;\n}\n\nstatic void Main (string [] args)\n{\n Number\n a = new Number (\"1\"),\n b = new Number (args [0]),\n one = new Number (\"1\");\n\n for (Number c = new Number (\"1\") ; c != b ; )\n {\n c = c + one;\n a = a * c;\n }\n\n Console.WriteLine (string.Format (\"{0}! = {1}\", new object [] { b, a }));\n}\n" }, { "answer_id": 51952, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "factorial = lambda n: reduce(lambda x,y: x*y, range(1, n+1), 1)\n print factorial(100)\n93326215443944152681699238856266700490715968264381621468592963895217599993229915\\\n608941463976156518286253697920827223758251185210916864000000000000000000000000\n" }, { "answer_id": 51975, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 6, "selected": false, "text": "curl http://www.google.com/search?q=170!\n curl http://www58.wolframalpha.com/input/?i=171!\n" }, { "answer_id": 52946, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env python\n\"\"\" weave_factorial.py\n\n\"\"\"\n# [weave] factorial() as extension module in C++\nfrom scipy.weave import ext_tools\n\ndef build_factorial_ext():\n func = ext_tools.ext_function(\n 'factorial', \n r\"\"\"\n unsigned long long i = 1;\n for ( ; n > 1; --n)\n i *= n;\n\n PyObject *o = PyLong_FromUnsignedLongLong(i);\n return_val = o;\n Py_XDECREF(o); \n \"\"\", \n ['n'], \n {'n': 1}, # effective type declaration\n {})\n mod = ext_tools.ext_module('factorial_ext')\n mod.add_function(func)\n mod.compile()\n\ntry: from factorial_ext import factorial as factorial_weave\nexcept ImportError:\n build_factorial_ext()\n from factorial_ext import factorial as factorial_weave\n\n\n# [python] pure python procedural factorial()\ndef factorial_python(n):\n i = 1\n while n > 1:\n i *= n\n n -= 1\n return i\n\n\n# [psyco] factorial() psyco-optimized\ntry:\n import psyco\n factorial_psyco = psyco.proxy(factorial_python)\nexcept ImportError:\n pass\n\n\n# [list] list-lookup factorial()\nfactorials = map(factorial_python, range(21)) \nfactorial_list = lambda n: factorials[n]\n $ python -mtimeit \\\n -s \"from weave_factorial import factorial_$label as f\" \"f($n)\"\n" }, { "answer_id": 53810, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 3, "selected": false, "text": "k \\f n. f^k n 3 = \\f n. f (f (f n))) (\\x. x x) (\\y f. f (y y f)) (\\y n. n (\\x y z. z) (\\x y. x) (\\f n. f n) (\\f. n (y (\\f m. n (\\g h. h (g f)) (\\x. m) (\\x. x)) f)))\n" }, { "answer_id": 58361, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "def factorial(n)\n (1 .. n).inject{|a, b| a*b}\nend\n def factorial(n)\n n == 1 ? 1 : n * factorial(n-1)\nend\n" }, { "answer_id": 58368, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 2, "selected": false, "text": "def fact(n) {\n | 0 => 1\n | x => x * fact(x-1)\n}\n" }, { "answer_id": 58433, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": false, "text": "#Language: T-SQL\n#Style: Recursive, divide and conquer\n create function factorial(@b int=1, @e int) returns float as begin\n return case when @b>=@e then @e else \n convert(float,dbo.factorial(@b,convert(int,@b+(@e-@b)/2)))\n * convert(float,dbo.factorial(convert(int,@b+1+(@e-@b)/2),@e)) end\nend\n print dbo.factorial(1,170) -- the 1 being the starting number\n" }, { "answer_id": 58594, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": false, "text": "#Language: T-SQL\n#Style: Big Numbers\n create function bigfact(@x varchar(max)) returns varchar(max) as begin\n declare @c int\n declare @n table(n int,e int)\n declare @f table(n int,e int)\n\n set @c=0\n while @c<len(@x) begin\n set @c=@c+1\n insert @n(n,e) values(convert(int,substring(@x,@c,1)),len(@x)-@c)\n end\n\n -- our current factorial\n insert @f(n,e) select 1,0\n\n while 1=1 begin\n declare @p table(n int,e int)\n delete @p\n -- product\n insert @p(n,e) select sum(f.n*n.n), f.e+n.e from @f f cross join @n n group by f.e+n.e\n\n -- normalize\n while 1=1 begin\n delete @f\n insert @f(n,e) select sum(n),e from (\n select (n % 10) as n,e from @p union all \n select (n/10) % 10,e+1 from @p union all \n select (n/100) %10,e+2 from @p union all \n select (n/1000)%10,e+3 from @p union all \n select (n/10000) % 10,e+4 from @p union all \n select (n/100000)% 10,e+5 from @p union all \n select (n/1000000)%10,e+6 from @p union all \n select (n/10000000) % 10,e+7 from @p union all \n select (n/100000000)% 10,e+8 from @p union all \n select (n/1000000000)%10,e+9 from @p\n ) f group by e having sum(n)>0\n\n set @c=0\n select @c=count(*) from @f where n>9\n if @c=0 break\n delete @p\n insert @p(n,e) select n,e from @f\n end\n\n -- decrement\n update @n set n=n-1 where e=0\n\n -- normalize\n while 1=1 begin\n declare @e table(e int)\n delete @e\n insert @e(e) select e from @n where n<0\n if @@rowcount=0 break\n\n update @n set n=n+10 where e in (select e from @e)\n update @n set n=n-1 where e in (select e+1 from @e)\n end \n\n set @c=0\n select @c=count(*) from @n where n>0\n if @c=0 break\n end\n\n select @c=max(e) from @f\n set @x=''\n declare @l varchar(max)\n while @c>=0 begin\n set @l='0'\n select @l=convert(varchar(max),n) from @f where e=@c\n set @x=@x+@l\n set @c=@c-1\n end\n return @x\nend\n print dbo.bigfact('69')\n 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000\n" }, { "answer_id": 67805, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 3, "selected": false, "text": "(factorial=Hash.new{|h,k|k*h[k-1]})[1]=1\n \n factorial[5]\n => 120\n" }, { "answer_id": 67979, "author": "Paul Reiners", "author_id": 7648, "author_profile": "https://Stackoverflow.com/users/7648", "pm_score": 2, "selected": false, "text": "Moog moog => dac;\n4.0 => moog.gain;\n\nfor (0 => int i; i < 8; i++) {\n <<< factorial(i) >>>;\n}\n\nfun int factorial(int n) {\n 1 => int result;\n if (n != 0) {\n n * factorial(n - 1) => result;\n }\n\n Std.mtof(result % 128) => moog.freq;\n 0.25::second => now;\n\n return result;\n}\n" }, { "answer_id": 71849, "author": "TonJ", "author_id": 11537, "author_profile": "https://Stackoverflow.com/users/11537", "pm_score": 4, "selected": false, "text": "+++++\n>+<[[->>>>+<<<<]>>>>[-<<<<+>>+>>]<<<<>[->>+<<]<>>>[-<[->>+<<]>>[-<<+<+>>>]<]<[-]><<<-]\n" }, { "answer_id": 81669, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 4, "selected": false, "text": "×/⍳X\n !X\n" }, { "answer_id": 82369, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 3, "selected": false, "text": "#!/bin/bash\necho $(($1 * `( [[ $1 -gt 1 ]] && ./$0 $(($1 - 1)) ) || echo 1`));\n" }, { "answer_id": 90589, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 1, "selected": false, "text": "def factorial (n)\n return multiply_range(1, n)\nend\n\ndef multiply_range(n, m)\n if (m < n)\n return 1\n elsif (n == m)\n return m\n else\n i = (n + m) / 2\n return multiply_range(n, i) * multiply_range(i+1, m)\n end\nend\n" }, { "answer_id": 90659, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "#include <stdexcept>;\n\nlong fact(long f)\n{\n static long fact [] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 1932053504, 1278945280, 2004310016, 2004189184 };\n static long max = sizeof(fact)/sizeof(long);\n\n if ((f < 0) || (f >= max))\n { throw std::range_error(\"Factorial Range Error\");\n }\n\n return fact[f];\n}\n" }, { "answer_id": 90728, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "(defun fact (n)\n (loop for i from 1 to n\n for acc = 1 then (* acc i)\n finally (return acc)))\n" }, { "answer_id": 90911, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "(defun format-fact (stream arg colonp atsignp &rest args)\n (destructuring-bind (n acc) arg\n (format stream\n \"~[~A~:;~*~/format-fact/~]\"\n (1- n)\n acc\n (list (1- n) (* acc n)))))\n\n(defun fact (n)\n (parse-integer (format nil \"~/format-fact/\" (list n 1))))\n" }, { "answer_id": 91039, "author": "Calum", "author_id": 8434, "author_profile": "https://Stackoverflow.com/users/8434", "pm_score": 1, "selected": false, "text": "def factorial( value: BigInt ): BigInt = value match {\n case 0 => 1\n case _ => value * factorial( value - 1 )\n}\n" }, { "answer_id": 91175, "author": "Dynite", "author_id": 16177, "author_profile": "https://Stackoverflow.com/users/16177", "pm_score": 1, "selected": false, "text": "PROC subprocess(MOBILE CHAN INT parent.out!,parent.in?)\nINT value:\n SEQ\n parent.in ? value\n IF \n value = 1\n SEQ\n parent.out ! value\n OTHERWISE\n INITIAL MOBILE CHAN INT child.in IS MOBILE CHAN INT:\n INITIAL MOBILE CHAN INT child.out IS MOBILE CHAN INT:\n FORKING\n INT newvalue:\n SEQ\n FORK subprocess(child.in!,child.out?)\n child.out ! (value-1)\n child.in ? newvalue\n parent.out ! (newalue*value)\n:\n\nPROC main(CHAN BYTE in?,src!,kyb?)\nINITIAL INT value IS 0:\nINITIAL MOBILE CHAN INT child.out is MOBILE CHAN INT\nINITIAL MOBILE CHAN INT child.in is MOBILE CHAN INT\nSEQ \n WHILE TRUE\n SEQ\n subprocess(child.in!,child.out?)\n child.out ! value\n child.in ? value\n src ! value:\n value := value + 1\n:\n" }, { "answer_id": 100199, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "procedure factorial(n)\n return (0<n) * factorial(n-1) | 1\nend\n return (0<n) * factorial(n-1) | (n=0 & 1)\n write(factorial(3))\nwrite(factorial(-1))\nwrite(factorial(20))\n 6\n2432902008176640000\n procedure factorials()\n local f,n\n f := 1; n := 0\n repeat suspend f *:= (n +:= 1)\nend\n every write(factorials() \\ 5)\n 1\n2\n6\n24\n120\n suspend yield every \\ factorials" }, { "answer_id": 106580, "author": "Jiří Pospíšil", "author_id": 19093, "author_profile": "https://Stackoverflow.com/users/19093", "pm_score": 0, "selected": false, "text": "function factorial\n parameters n\nreturn iif( n>0, n*factorial(n-1), 1)\n" }, { "answer_id": 106621, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 1, "selected": false, "text": "# let rec factorial n =\n if n=0 then 1 else n * factorial(n - 1);;\n" }, { "answer_id": 114277, "author": "dogbane", "author_id": 7412, "author_profile": "https://Stackoverflow.com/users/7412", "pm_score": 2, "selected": false, "text": "#!/usr/bin/awk -f\n{\n result=1;\n for(i=$1;i>0;i--){\n result=result*i;\n }\n print result;\n}\n" }, { "answer_id": 114930, "author": "Einar", "author_id": 20445, "author_profile": "https://Stackoverflow.com/users/20445", "pm_score": 1, "selected": false, "text": "public final class Factorial {\n\n public static void main(String[] args) {\n final int n = Integer.valueOf(args[0]);\n System.out.println(\"Factorial of \" + n + \" is \" + create(n).apply());\n }\n\n private static Function create(final int n) {\n return n == 0 ? new ZeroFactorialFunction() : new NFactorialFunction(n);\n }\n\n interface Function {\n int apply();\n }\n\n private static class NFactorialFunction implements Function {\n private final int n;\n public NFactorialFunction(final int n) {\n this.n = n;\n }\n @Override\n public int apply() {\n return n * Factorial.create(n - 1).apply();\n }\n }\n\n private static class ZeroFactorialFunction implements Function {\n @Override\n public int apply() {\n return 1;\n }\n }\n\n}\n" }, { "answer_id": 115633, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "fac(0) -> 1;\nfac(N) when N > 0 -> fac(N, 1).\n\nfac(1, R) -> R;\nfac(N, R) -> fac(N - 1, R * N).\n" }, { "answer_id": 153790, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": false, "text": "#Language: T-SQL, C#\n#Style: Custom Aggregate\n /* ProductAggregate.cs */\nusing System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\n[Serializable]\n[SqlUserDefinedAggregate(Format.Native)]\npublic struct product {\n private SqlDouble accum;\n public void Init() { accum = 1; }\n public void Accumulate(SqlDouble value) { accum *= value; }\n public void Merge(product value) { Accumulate(value.Terminate()); }\n public SqlDouble Terminate() { return accum; }\n}\n create assembly ProductAggregate from 'ProductAggregate.dll' with permission_set=safe -- mod path to point to actual dll location on disk.\n\ncreate aggregate product(@a float) returns float external name ProductAggregate.product\n select 1 as n into #n union select 2 union select 3 union select 4 union select 5\n select dbo.product(n) from #n\n" }, { "answer_id": 201631, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "public static int Factorial(int n)\n{\n switch (n)\n {\n case 1:\n return 1;\n case 2:\n return 2;\n case 3:\n return 6;\n case 4:\n return 24;\n default:\n throw new Exception(\"Sorry, I can only count to 4\");\n }\n\n}\n" }, { "answer_id": 201662, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": "private static int factorial(int n){ if (n == 0)return 1;else return n * factorial(n - 1); }\n" }, { "answer_id": 215337, "author": "nonowarn", "author_id": 28720, "author_profile": "https://Stackoverflow.com/users/28720", "pm_score": 4, "selected": false, "text": "sub factorial ($n) { [*] 1..$n }\n [*] product sub postfix:<!> ($n) { [*] 1..$n }\n\n# This function(?) call like below ... It looks like mathematical notation.\nsay 10!;\n" }, { "answer_id": 216448, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "factorial n = product [1..n]\n" }, { "answer_id": 264821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\nclass\n APPLICATION\ninherit\n ARGUMENTS\n\ncreate\n make\n\nfeature -- Initialization\n\n make is\n -- Run application.\n local\n l_fact: NATURAL_64\n do\n l_fact := factorial(argument(1).to_natural_64)\n print(\"Result is: \" + l_fact.out)\n end\n\n factorial(n: NATURAL_64): NATURAL_64 is\n --\n require\n positive_n: n >= 0\n do\n if n = 0 then\n Result := 1\n else\n Result := n * factorial(n-1)\n end\n end\n\nend -- class APPLICATION\n" }, { "answer_id": 287796, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "/fact0 { dup 2 lt { pop } { 2 copy mul 3 1 roll 1 sub exch pop fact0 } ifelse } def\n/fact { 1 exch fact0 } def\n" }, { "answer_id": 287816, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 2, "selected": false, "text": " v\n>v\"Please enter a number (1-16) : \"0<\n,: >$*99g1-:99p#v_.25*,@\n^_&:1-99p>:1-:!|10 < \n ^ <\n" }, { "answer_id": 287921, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "e f [2++d]se[d1-d_1<fd0>e*]sf\n lfx f x (x, x-1) (x, (x-1)!) x (0, -1) x 2++d (0, -1) (1, 1)" }, { "answer_id": 288143, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "setGeneric( 'fct', function( x ) { standardGeneric( 'fct' ) } )\nsetMethod( 'fct', 'numeric', function( x ) { \n lapply( x, function(a) { \n if( a == 0 ) 1 else a * fact( a - 1 ) \n } )\n} )\n > fct( c( 3, 5, 6 ) )\n[[1]]\n[1] 6\n\n[[2]]\n[1] 120\n\n[[3]]\n[1] 720\n" }, { "answer_id": 288232, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 2, "selected": false, "text": "print sub {\n my $f = shift;\n sub {\n my $f1 = shift;\n $f->( sub { $f1->( $f1 )->( @_ ) } )\n }->( sub {\n my $f2 = shift;\n $f->( sub { $f2->( $f2 )->( @_ ) } )\n } )\n}->( sub {\n my $h = shift;\n sub {\n my $n = shift;\n return 1 if $n <=1;\n return $n * $h->($n-1);\n }\n})->(5);\n" }, { "answer_id": 288461, "author": "Danko Durbić", "author_id": 19241, "author_profile": "https://Stackoverflow.com/users/19241", "pm_score": 4, "selected": false, "text": "<?xml version=\"1.0\"?>\n<?xml-stylesheet href=\"factorial.xsl\" type=\"text/xsl\" ?>\n<n>\n 20\n</n>\n <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" >\n <xsl:output method=\"text\"/>\n <!-- 0! = 1 -->\n <xsl:template match=\"text()[. = 0]\">\n 1\n </xsl:template>\n <!-- n! = (n-1)! * n-->\n <xsl:template match=\"text()[. > 0]\">\n <xsl:variable name=\"x\">\n <xsl:apply-templates select=\"msxsl:node-set( . - 1 )/text()\"/>\n </xsl:variable>\n <xsl:value-of select=\"$x * .\"/>\n </xsl:template>\n <!-- Calculate n! -->\n <xsl:template match=\"/n\">\n <xsl:apply-templates select=\"text()\"/>\n </xsl:template>\n</xsl:stylesheet>\n" }, { "answer_id": 288596, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 2, "selected": false, "text": " fact=. verb define\n*/ >:@i. y\n)\n" }, { "answer_id": 288688, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 1, "selected": false, "text": "factorial = 1 fby factorial * (time+1);" }, { "answer_id": 288792, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 2, "selected": false, "text": "(defn fact \n ([n] (fact n 1))\n ([n acc] (if (= n 0) \n acc \n (recur (- n 1) (* acc n)))))\n (defn fact [n] (apply * (range 1 (+ n 1))))\n" }, { "answer_id": 288834, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 1, "selected": false, "text": "!" }, { "answer_id": 289853, "author": "namin", "author_id": 34596, "author_profile": "https://Stackoverflow.com/users/34596", "pm_score": 2, "selected": false, "text": "def fact(n: Int): BigInt = 1 to n reduceLeft(_*_)\n def fact(n: Int): BigInt = if (n == 0) 1 else fact(n-1) * n\n object extendBuiltins extends Application {\n\n class Factorizer(n: Int) {\n def ! = 1 to n reduceLeft(_*_)\n }\n\n implicit def int2fact(n: Int) = new Factorizer(n)\n\n println(\"10! = \" + (10!))\n}\n" }, { "answer_id": 289881, "author": "Chris Jefferson", "author_id": 27074, "author_profile": "https://Stackoverflow.com/users/27074", "pm_score": 2, "selected": false, "text": "template<unsigned i>\nstruct factorial\n{ static const unsigned value = i * factorial<i-1>::value; };\n\ntemplate<>\nstruct factorial<0>\n{ static const unsigned value = 1; };\n Factorial<5>::value\n" }, { "answer_id": 290638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "factorial n = product [1..n]\n" }, { "answer_id": 290643, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "fac n = if n == 0 \n then 1\n else n * fac (n-1)\n fac = (\\(n) ->\n (if ((==) n 0)\n then 1\n else ((*) n (fac ((-) n 1)))))\n fac 0 = 1\nfac (n+1) = (n+1) * fac n\n fac 0 = 1\nfac n = n * fac (n-1)\n fac n = foldr (*) 1 [1..n]\n fac n = foldl (*) 1 [1..n]\n -- using foldr to simulate foldl\n\nfac n = foldr (\\x g n -> g (x*n)) id [1..n] 1\n facs = scanl (*) 1 [1..]\n\nfac n = facs !! n\n fac = foldr (*) 1 . enumFromTo 1\n fac n = result (for init next done)\n where init = (0,1)\n next (i,m) = (i+1, m * (i+1))\n done (i,_) = i==n\n result (_,m) = m\n\nfor i n d = until d n i\n fac n = snd (until ((>n) . fst) (\\(i,m) -> (i+1, i*m)) (1,1))\n facAcc a 0 = a\nfacAcc a n = facAcc (n*a) (n-1)\n\nfac = facAcc 1\n facCps k 0 = k 1\nfacCps k n = facCps (k . (n *)) (n-1)\n\nfac = facCps id\n y f = f (y f)\n\nfac = y (\\f n -> if (n==0) then 1 else n * f (n-1))\n s f g x = f x (g x)\n\nk x y = x\n\nb f g x = f (g x)\n\nc f g x = f x g\n\ny f = f (y f)\n\ncond p f g x = if p x then f x else g x\n\nfac = y (b (cond ((==) 0) (k 1)) (b (s (*)) (c b pred)))\n arb = () -- \"undefined\" is also a good RHS, as is \"arb\" :)\n\nlistenc n = replicate n arb\nlistprj f = length . f . listenc\n\nlistprod xs ys = [ i (x,y) | x<-xs, y<-ys ]\n where i _ = arb\n\nfacl [] = listenc 1\nfacl n@(_:pred) = listprod n (facl pred)\n\nfac = listprj facl\n -- a dynamically-typed term language\n\ndata Term = Occ Var\n | Use Prim\n | Lit Integer\n | App Term Term\n | Abs Var Term\n | Rec Var Term\n\ntype Var = String\ntype Prim = String\n\n\n-- a domain of values, including functions\n\ndata Value = Num Integer\n | Bool Bool\n | Fun (Value -> Value)\n\ninstance Show Value where\n show (Num n) = show n\n show (Bool b) = show b\n show (Fun _) = \"\"\n\nprjFun (Fun f) = f\nprjFun _ = error \"bad function value\"\n\nprjNum (Num n) = n\nprjNum _ = error \"bad numeric value\"\n\nprjBool (Bool b) = b\nprjBool _ = error \"bad boolean value\"\n\nbinOp inj f = Fun (\\i -> (Fun (\\j -> inj (f (prjNum i) (prjNum j)))))\n\n\n-- environments mapping variables to values\n\ntype Env = [(Var, Value)]\n\ngetval x env = case lookup x env of\n Just v -> v\n Nothing -> error (\"no value for \" ++ x)\n\n\n-- an environment-based evaluation function\n\neval env (Occ x) = getval x env\neval env (Use c) = getval c prims\neval env (Lit k) = Num k\neval env (App m n) = prjFun (eval env m) (eval env n)\neval env (Abs x m) = Fun (\\v -> eval ((x,v) : env) m)\neval env (Rec x m) = f where f = eval ((x,f) : env) m\n\n\n-- a (fixed) \"environment\" of language primitives\n\ntimes = binOp Num (*)\n\nminus = binOp Num (-)\nequal = binOp Bool (==)\ncond = Fun (\\b -> Fun (\\x -> Fun (\\y -> if (prjBool b) then x else y)))\n\nprims = [ (\"*\", times), (\"-\", minus), (\"==\", equal), (\"if\", cond) ]\n\n\n-- a term representing factorial and a \"wrapper\" for evaluation\n\nfacTerm = Rec \"f\" (Abs \"n\" \n (App (App (App (Use \"if\")\n (App (App (Use \"==\") (Occ \"n\")) (Lit 0))) (Lit 1))\n (App (App (Use \"*\") (Occ \"n\"))\n (App (Occ \"f\") \n (App (App (Use \"-\") (Occ \"n\")) (Lit 1))))))\n\nfac n = prjNum (eval [] (App facTerm (Lit n)))\n -- static Peano constructors and numerals\n\ndata Zero\ndata Succ n\n\ntype One = Succ Zero\ntype Two = Succ One\ntype Three = Succ Two\ntype Four = Succ Three\n\n\n-- dynamic representatives for static Peanos\n\nzero = undefined :: Zero\none = undefined :: One\ntwo = undefined :: Two\nthree = undefined :: Three\nfour = undefined :: Four\n\n\n-- addition, a la Prolog\n\nclass Add a b c | a b -> c where\n add :: a -> b -> c\n\ninstance Add Zero b b\ninstance Add a b c => Add (Succ a) b (Succ c)\n\n\n-- multiplication, a la Prolog\n\nclass Mul a b c | a b -> c where\n mul :: a -> b -> c\n\ninstance Mul Zero b Zero\ninstance (Mul a b c, Add b c d) => Mul (Succ a) b d\n\n\n-- factorial, a la Prolog\n\nclass Fac a b | a -> b where\n fac :: a -> b\n\ninstance Fac Zero One\ninstance (Fac n k, Mul (Succ n) k m) => Fac (Succ n) m\n\n-- try, for \"instance\" (sorry):\n-- \n-- :t fac four\n -- the natural numbers, a la Peano\n\ndata Nat = Zero | Succ Nat\n\n\n-- iteration and some applications\n\niter z s Zero = z\niter z s (Succ n) = s (iter z s n)\n\nplus n = iter n Succ\nmult n = iter Zero (plus n)\n\n\n-- primitive recursion\n\nprimrec z s Zero = z\nprimrec z s (Succ n) = s n (primrec z s n)\n\n\n-- two versions of factorial\n\nfac = snd . iter (one, one) (\\(a,b) -> (Succ a, mult a b))\nfac' = primrec one (mult . Succ)\n\n\n-- for convenience and testing (try e.g. \"fac five\")\n\nint = iter 0 (1+)\n\ninstance Show Nat where\n show = show . int\n\n(zero : one : two : three : four : five : _) = iterate Succ Zero\n -- (curried, list) fold and an application\n\nfold c n [] = n\nfold c n (x:xs) = c x (fold c n xs)\n\nprod = fold (*) 1\n\n\n-- (curried, boolean-based, list) unfold and an application\n\nunfold p f g x = \n if p x \n then [] \n else f x : unfold p f g (g x)\n\ndownfrom = unfold (==0) id pred\n\n\n-- hylomorphisms, as-is or \"unfolded\" (ouch! sorry ...)\n\nrefold c n p f g = fold c n . unfold p f g\n\nrefold' c n p f g x = \n if p x \n then n \n else c (f x) (refold' c n p f g (g x))\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac = prod . downfrom\nfac' = refold (*) 1 (==0) id pred\nfac'' = refold' (*) 1 (==0) id pred\n -- (product-based, list) catamorphisms and an application\n\ncata (n,c) [] = n\ncata (n,c) (x:xs) = c (x, cata (n,c) xs)\n\nmult = uncurry (*)\nprod = cata (1, mult)\n\n\n-- (co-product-based, list) anamorphisms and an application\n\nana f = either (const []) (cons . pair (id, ana f)) . f\n\ncons = uncurry (:)\n\ndownfrom = ana uncount\n\nuncount 0 = Left ()\nuncount n = Right (n, n-1)\n\n\n-- two variations on list hylomorphisms\n\nhylo f g = cata g . ana f\n\nhylo' f (n,c) = either (const n) (c . pair (id, hylo' f (c,n))) . f\n\npair (f,g) (x,y) = (f x, g y)\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac = prod . downfrom\nfac' = hylo uncount (1, mult)\nfac'' = hylo' uncount (1, mult)\n -- explicit type recursion based on functors\n\nnewtype Mu f = Mu (f (Mu f)) deriving Show\n\nin x = Mu x\nout (Mu x) = x\n\n\n-- cata- and ana-morphisms, now for *arbitrary* (regular) base functors\n\ncata phi = phi . fmap (cata phi) . out\nana psi = in . fmap (ana psi) . psi\n\n\n-- base functor and data type for natural numbers,\n-- using a curried elimination operator\n\ndata N b = Zero | Succ b deriving Show\n\ninstance Functor N where\n fmap f = nelim Zero (Succ . f)\n\nnelim z s Zero = z\nnelim z s (Succ n) = s n\n\ntype Nat = Mu N\n\n\n-- conversion to internal numbers, conveniences and applications\n\nint = cata (nelim 0 (1+))\n\ninstance Show Nat where\n show = show . int\n\nzero = in Zero\nsuck = in . Succ -- pardon my \"French\" (Prelude conflict)\n\nplus n = cata (nelim n suck )\nmult n = cata (nelim zero (plus n))\n\n\n-- base functor and data type for lists\n\ndata L a b = Nil | Cons a b deriving Show\n\ninstance Functor (L a) where\n fmap f = lelim Nil (\\a b -> Cons a (f b))\n\nlelim n c Nil = n\nlelim n c (Cons a b) = c a b\n\ntype List a = Mu (L a)\n\n\n-- conversion to internal lists, conveniences and applications\n\nlist = cata (lelim [] (:))\n\ninstance Show a => Show (List a) where\n show = show . list\n\nprod = cata (lelim (suck zero) mult)\n\nupto = ana (nelim Nil (diag (Cons . suck)) . out)\n\ndiag f x = f x x\n\nfac = prod . upto\n -- explicit type recursion with functors and catamorphisms\n\nnewtype Mu f = In (f (Mu f))\n\nunIn (In x) = x\n\ncata phi = phi . fmap (cata phi) . unIn\n\n\n-- base functor and data type for natural numbers,\n-- using locally-defined \"eliminators\"\n\ndata N c = Z | S c\n\ninstance Functor N where\n fmap g Z = Z\n fmap g (S x) = S (g x)\n\ntype Nat = Mu N\n\nzero = In Z\nsuck n = In (S n)\n\nadd m = cata phi where\n phi Z = m\n phi (S f) = suck f\n\nmult m = cata phi where\n phi Z = zero\n phi (S f) = add m f\n\n\n-- explicit products and their functorial action\n\ndata Prod e c = Pair c e\n\noutl (Pair x y) = x\noutr (Pair x y) = y\n\nfork f g x = Pair (f x) (g x)\n\ninstance Functor (Prod e) where\n fmap g = fork (g . outl) outr\n\n\n-- comonads, the categorical \"opposite\" of monads\n\nclass Functor n => Comonad n where\n extr :: n a -> a\n dupl :: n a -> n (n a)\n\ninstance Comonad (Prod e) where\n extr = outl\n dupl = fork id outr\n\n\n-- generalized catamorphisms, zygomorphisms and paramorphisms\n\ngcata :: (Functor f, Comonad n) =>\n (forall a. f (n a) -> n (f a))\n -> (f (n c) -> c) -> Mu f -> c\n\ngcata dist phi = extr . cata (fmap phi . dist . fmap dupl)\n\nzygo chi = gcata (fork (fmap outl) (chi . fmap outr))\n\npara :: Functor f => (f (Prod (Mu f) c) -> c) -> Mu f -> c\npara = zygo In\n\n\n-- factorial, the *hard* way!\n\nfac = para phi where\n phi Z = suck zero\n phi (S (Pair f n)) = mult f (suck n)\n\n\n-- for convenience and testing\n\nint = cata phi where\n phi Z = 0\n phi (S f) = 1 + f\n\ninstance Show (Mu N) where\n show = show . int\n fac n = product [1..n]\n" }, { "answer_id": 292898, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": " fac := [ :x | x = 0 ifTrue: [ 1 ] ifFalse: [ x * (fac value: x -1) ]].\n\n Transcript show: (fac value: 24) \"-> 620448401733239439360000\"\n" }, { "answer_id": 292915, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": "Dictionary >> fac: x\n ^self at: x ifAbsentPut: [ x * (self fac: x - 1) ]\n d := Dictionary new.\n d at: 0 put: 1.\n d fac: 24 \n" }, { "answer_id": 292921, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": "(1 to: 24) inject: 1 into: [ :a :b | a * b ] \n" }, { "answer_id": 311784, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 2, "selected": false, "text": "function nu(x)\n{\n var r=0\n while( x ) {\n x &= x-1\n r++\n }\n return r\n}\n\nfunction fac(n)\n{\n var r= Math.pow(2,n-nu(n))\n\n for ( var i=3 ; i <= n ; i+= 2 )\n r *= Math.pow(i,Math.floor(Math.log(n/i)/Math.LN2)+1)\n return r\n}\n" }, { "answer_id": 311826, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "function fac { seq $1 | paste -sd* | bc; } \n$ fac 42\n1405006117752879898543142606244511569936384000000000\n$\n" }, { "answer_id": 383858, "author": "Clayton", "author_id": 22201, "author_profile": "https://Stackoverflow.com/users/22201", "pm_score": 1, "selected": false, "text": "fact(N)\n N F,I S F=1 F I=2:1:N S F=F*I\n QUIT F\n fact(N)\n N F,I S F=1 F I=2:1:N S F=F_\"*\"_I\n QUIT @F\n" }, { "answer_id": 385519, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": false, "text": "fact[n_] := Times @@ Range[n]\n Apply[Times, Range[n]] n!" }, { "answer_id": 393925, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "(defun ! (n) (reduce #'* (loop for i from 2 below (+ n 1) collect i)))\n * (! 42)\n\n1405006117752879898543142606244511569936384000000000\n" }, { "answer_id": 426478, "author": "Pål GD", "author_id": 40058, "author_profile": "https://Stackoverflow.com/users/40058", "pm_score": 0, "selected": false, "text": "(defun factorial (n)\n (if (<= n 1)\n 1 \n (* n (factorial (1- n)))))\n" }, { "answer_id": 432010, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 2, "selected": false, "text": ">>>>,----------[>>>>,----------]>>>>++<<<<<<<<[>++++++[<----\n-->-]<-<<<<]>>>>[[>>+<<-]>>[<<+>+>-]<->+<[>>>>+<<<-<[-]]>[-]\n>>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]>>>>[-[>+<-]+>>>\n>]<<<<[<<<<]<<<<[<<<<]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>+<<\n<<-]<<<<]>>>>+<<<<<<<[<<<<]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>>\n+<<<-]>>>[<<<+>>+>-]<-[>>+<<[-]]<<[<<<<]>>>>[>[>+<-]>[<<+>+>\n-]<<[>>>+<<<-]>>>[<<<+>>+>-]<->+++++++++[-<[-[>>>>+<<<<-]]>>\n>>[<<<<+>>>>-]<<<]<[>>+<<<<[-]>>[<<+>>-]]>>]<<<<[<<<<]<<<[<<\n<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]>>[<<+>+>-]<->+<[>-<[-\n]]>[-<<-<<<<[>>+<<-]>>[<<+>+>-]<->+<[>-<[-]]>]<<[<<<<]<<<<-[\n>>+<<-]>>[<<+>+>-]+<[>-<[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<\n<+>+>-]+<[>-<[-]]>]<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]<->+<[>>>\n>+<<<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]<--.<<\n<<]++++++++++.\n >++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-\n]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<\n<<<<<-[>+<-]]]]]]]]]]]>[<+>-]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>\n>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[>+<-]<<<<]>>[->[-]\n++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]\n" }, { "answer_id": 441229, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 9, "selected": true, "text": "perl FILENAME runhugs FILENAME g++ -lgmpxx -lgmp -x c++ FILENAME ./a.out bf < FILENAME > EXECUTABLE wspace FILENAME <code>" }, { "answer_id": 450128, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "function f(n) {\n var result = n>1 ? arguments.callee(n-1)*n : 1;\n return result;\n}\n// function call\nf(3);\n" }, { "answer_id": 514922, "author": "Phil", "author_id": 62789, "author_profile": "https://Stackoverflow.com/users/62789", "pm_score": 0, "selected": false, "text": "(defun factorial (x)\n (if (< x 2) (return-from factorial (print 1)))\n (let ((tempx 1) (ans 1))\n (loop until (equalp x tempx) do\n (incf tempx)\n (setf ans (* tempx ans)))\n (list ans)))\n" }, { "answer_id": 546268, "author": "stevenvh", "author_id": 66056, "author_profile": "https://Stackoverflow.com/users/66056", "pm_score": 2, "selected": false, "text": "function Factorial(aNumber: Int64): String;\nvar\n F: Double;\nbegin\n F := 0;\n while aNumber > 1 do begin\n F := F + log10(aNumber);\n dec(aNumber);\n end;\n Result := FloatToStr(Power(10, Frac(F))) + ' * 10^' + IntToStr(Trunc(F));\nend;\n" }, { "answer_id": 576331, "author": "SingleNegationElimination", "author_id": 65696, "author_profile": "https://Stackoverflow.com/users/65696", "pm_score": 1, "selected": false, "text": "proc factorial {n} {\n if { $n == 0 } { return 1 }\n return [expr {$n*[factorial [expr {$n-1}]]}]\n}\nputs [factorial 6]\n package require math::bignum\nproc factorial {n} {\n if { $n == 0 } { return 1 }\n return [ ::math::bignum::tostr [ ::math::bignum::mul [\n ::math::bignum::fromstr $n] [ ::math::bignum::fromstr [\n factorial [expr {$n-1} ]\n ]]]]\n}\nputs [factorial 60]\n" }, { "answer_id": 576336, "author": "mweiss", "author_id": 33254, "author_profile": "https://Stackoverflow.com/users/33254", "pm_score": 2, "selected": false, "text": "? to factorial :n\n> ifelse :n = 0 [output 1] [output :n * factorial :n - 1]\n> end\n ? print factorial 5\n120\n" }, { "answer_id": 673795, "author": "jfklein", "author_id": 72919, "author_profile": "https://Stackoverflow.com/users/72919", "pm_score": 1, "selected": false, "text": "f[n_ /; n < 2] := 1\nf[n_] := (f[n] = n*f[n - 1])\n" }, { "answer_id": 690619, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "(defun factorial(x)\n (labels((f (x acc)\n (if (> x 1)\n (f (1- x)(* x acc))\n acc)))\n (f x 1)))\n" }, { "answer_id": 827102, "author": "fishlips", "author_id": 101790, "author_profile": "https://Stackoverflow.com/users/101790", "pm_score": 2, "selected": false, "text": "module fac where\n\ndata Nat : Set where -- Peano numbers\n zero : Nat\n suc : Nat -> Nat\n{-# BUILTIN NATURAL Nat #-}\n{-# BUILTIN SUC suc #-}\n{-# BUILTIN ZERO zero #-}\n\ninfixl 10 _+_ -- Addition over Peano numbers\n_+_ : Nat -> Nat -> Nat\nzero + n = n\n(suc n) + m = suc (n + m)\n\ninfixl 20 _*_ -- Multiplication over Peano numbers\n_*_ : Nat -> Nat -> Nat\nzero * n = zero\nn * zero = zero\n(suc n) * (suc m) = suc n + (suc n * m)\n\n_! : Nat -> Nat -- Factorial function, syntax: \"x !\"\nzero ! = suc zero\n(suc n) ! = (suc n) * (n !)\n" }, { "answer_id": 827173, "author": "Daniel Huckstep", "author_id": 4657, "author_profile": "https://Stackoverflow.com/users/4657", "pm_score": 1, "selected": false, "text": "class Integer\n def fact\n return 1 if self.zero?\n (1..self).to_a.inject(:*)\n end\nend" }, { "answer_id": 831961, "author": "ijw", "author_id": 87583, "author_profile": "https://Stackoverflow.com/users/87583", "pm_score": 2, "selected": false, "text": "# Because there are just so many other ways to get programs wrong...\nuse strict;\nuse warnings;\n\nsub factorial {\n my ($x)=@_;\n\n for(my $f=1;;$f++) {\n my $tmp=$f;\n foreach my $g (1..$x) {\n $tmp/=$g;\n }\n return $f if $tmp == 1;\n }\n}\n" }, { "answer_id": 1244406, "author": "nes1983", "author_id": 52573, "author_profile": "https://Stackoverflow.com/users/52573", "pm_score": 1, "selected": false, "text": "gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},\n visit[k_] := Module[{t},\n id++; If[k != 0, val[[k]] = id];\n If[id == n, f[val]];\n Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];\n id--; val[[k]] = Null;];\n visit[0];\n ]\n\nFactorial[n_] := Module[{res=0}, gen[res++&, n]; res]\n" }, { "answer_id": 1244623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "def factorial(n):\n return reduce(lambda x, y: x * y,range(1, n + 1))\n" }, { "answer_id": 1653893, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 1, "selected": false, "text": "function f($n){return array_reduce(range(1,$n),'bcmul',1);}\n array_product(range(1,$n));\n" }, { "answer_id": 1743311, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "seq -s'*' 42 | bc\n jot -s'*' 42 | bc\n" }, { "answer_id": 1743353, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 1, "selected": false, "text": "proc factorial(n);\n return 1 */ {1..n};\nend factorial;\n INTEGER n" }, { "answer_id": 2126153, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 1, "selected": false, "text": "0&>:1-:v v *_$.@ \n ^ _$>\\:^\n" }, { "answer_id": 2126202, "author": "Ken", "author_id": 230831, "author_profile": "https://Stackoverflow.com/users/230831", "pm_score": 1, "selected": false, "text": "(defgeneric factorial (n))\n(defmethod factorial ((n (eql 0))) 1)\n(defmethod factorial ((n integer)) (* n (factorial (1- n))))\n" }, { "answer_id": 2298931, "author": "Lynn", "author_id": 257418, "author_profile": "https://Stackoverflow.com/users/257418", "pm_score": 1, "selected": false, "text": "~),1>{*}*\n ~ ) , 1> {*}* echo 5 | ruby gs.rb fact.gs\n" }, { "answer_id": 2299240, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": ": FACT 1 SWAP 1 + 1 DO I * LOOP ;\n" }, { "answer_id": 2299739, "author": "Paul", "author_id": 103081, "author_profile": "https://Stackoverflow.com/users/103081", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl -w\n\nuse strict;\nuse bigint;\n\nprint STDOUT &main::rangeProduct(1,$ARGV[0]).\"\\n\";\n\nsub main::rangeProduct {\n my($l, $h) = @_;\n return $l if ($l==$h);\n return $l*$h if ($l==($h-1));\n # arghhh - multiplying more than 2 numbers at a time is too much work\n # find the midpoint and split the work up :-)\n my $m = int(($h+$l)/2);\n my $pid = open(my $KID, \"-|\");\n if ($pid){ # parent\n my $X = &main::rangeProduct($l,$m);\n my $Y = <$KID>;\n chomp($Y);\n close($KID);\n die \"kid failed\" unless defined $Y;\n return $X*$Y;\n } else {\n # kid\n print STDOUT &main::rangeProduct($m+1,$h).\"\\n\";\n exit(0);\n }\n}\n" }, { "answer_id": 3026710, "author": "James Mills", "author_id": 364980, "author_profile": "https://Stackoverflow.com/users/364980", "pm_score": 0, "selected": false, "text": "factorial := method(n,\n if (list(0, 1) contains(n),\n 1,\n n * factorial(n - 1)\n )\n)\n" }, { "answer_id": 3026924, "author": "erjiang", "author_id": 140827, "author_profile": "https://Stackoverflow.com/users/140827", "pm_score": 2, "selected": false, "text": "(define factorial\n (lambda (n)\n (if (= n 0)\n 1\n (* n (factorial (- n 1))))))\n (define factorial\n (lambda (n)\n (factorial_cps n (lambda (k) k))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (k 1)\n (factorial (- n 1) (lambda (v)\n (k (* n v)))))))\n (define factorial\n (lambda (n)\n (factorial_cps n (k_))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (apply_k 1)\n (factorial (- n 1) (k_extend n k))))\n\n(define apply_k\n (lambda (ko v)\n (ko v)))\n(define kt_empty\n (lambda ()\n (lambda (v) v)))\n(define kt_extend \n (lambda ()\n (lambda (v)\n (apply_k k (* n v)))))\n kt_ kt_ (define factorial\n (lambda (n)\n (factorial_cps n (kt_empty))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (apply_k 1)\n (factorial (- n 1) (kt_extend n k))))\n\n(define-union kt\n (empty)\n (extend n k))\n(define apply_k\n (lambda ()\n (union-case kh kt\n [(empty) v]\n [(extend n k) (begin\n (set! kh k)\n (set! v (* n v))\n (apply_k))])))\n (define-registers n k kh v)\n(define-program-counter pc)\n\n(define-label main\n (begin\n (set! n 5) ; what is the factorial of 5??\n (set! pc factorial_cps)\n (mount-trampoline kt_empty k pc)\n (printf \"Factorial of 5: ~d\\n\" v)))\n\n(define-label factorial_cps\n (if (zero? n)\n (begin\n (set! kh k)\n (set! v 1)\n (set! pc apply_k))\n (begin\n (set! k (kt_extend n k))\n (set! n (- n 1))\n (set! pc factorial_cps))))\n\n(define-union kt\n (empty dismount) ; get off the trampoline!\n (extend n k))\n\n(define-label apply_k\n (union-case kh kt\n [(empty dismount) (dismount-trampoline dismount)]\n [(extend n k) (begin\n (set! kh k)\n (set! v (* n v))\n (set! pc apply_k))]))\n main fact5.pc > (load \"pc2c.ss\")\n> (pc2c \"fact5.pc\" \"fact5.c\" \"fact5.h\")\n fact5.c fact5.h $ gcc fact5.c -o fact5\n$ ./fact5\nFactorial of 5: 120\n" }, { "answer_id": 3230390, "author": "Robert William Hanks", "author_id": 350331, "author_profile": "https://Stackoverflow.com/users/350331", "pm_score": 2, "selected": false, "text": " factorial = lambda n: ((n <= 1) and 1) or factorial(n-1) * n\n" }, { "answer_id": 5759098, "author": "Anthony Faull", "author_id": 63264, "author_profile": "https://Stackoverflow.com/users/63264", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION dbo.Factorial(@n int) RETURNS TABLE\nAS\nRETURN\n WITH RecursiveCTE (N, Value) AS\n (\n SELECT 1, CAST(1 AS decimal(38,0))\n UNION ALL\n SELECT N+1, CAST(Value*(N+1) AS decimal(38,0))\n FROM RecursiveCTE\n )\n SELECT TOP 1 Value\n FROM RecursiveCTE\n WHERE N = @n\n" }, { "answer_id": 8297255, "author": "NoSenseEtAl", "author_id": 700825, "author_profile": "https://Stackoverflow.com/users/700825", "pm_score": 0, "selected": false, "text": "constexpr uint64_t fact(uint32_t n)\n{\n return (n==0) ? 1:n*fact(n-1);\n}\n" }, { "answer_id": 9284383, "author": "iSun", "author_id": 960097, "author_profile": "https://Stackoverflow.com/users/960097", "pm_score": 0, "selected": false, "text": "Private Function factCalculation(ByVal Number%)\n Dim intNum%\n intNum = 1\n For i = 2 To Number\n intNum = intNum * Number\n Next i\n return intNum\nEnd Function\n\nPrivate Sub Form_Load()\n Dim FactResult% : FactResult = factCalculation(3) 'e.g\n Print FactResult\nEnd Sub\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1337/" ]
23,931
<p>Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).</p> <p>Do you know any algorithm to do this kind of job?</p>
[ { "answer_id": 3445087, "author": "Tom Gullen", "author_id": 356635, "author_profile": "https://Stackoverflow.com/users/356635", "pm_score": 8, "selected": false, "text": "white\nred\nblue\ngreen\nblack\n FFFFFF|000000|FDFD44|FFFFFF\n" }, { "answer_id": 3464874, "author": "navneeth", "author_id": 191241, "author_profile": "https://Stackoverflow.com/users/191241", "pm_score": 3, "selected": false, "text": "from PIL import Image\nimport imagehash\n\n# image_fns : List of training image files\nimg_hashes = {}\n\nfor img_fn in sorted(image_fns):\n hash = imagehash.average_hash(Image.open(image_fn))\n if hash in img_hashes:\n print( '{} duplicate of {}'.format(image_fn, img_hashes[hash]) )\n else:\n img_hashes[hash] = image_fn\n from PIL import Image\nimport imagehash\n\n# image_fns : List of training image files\nimg_hashes = {}\nepsilon = 50\n\nfor img_fn1, img_fn2 in zip(image_fns, image_fns[::-1]):\n if image_fn1 == image_fn2:\n continue\n\n hash1 = imagehash.average_hash(Image.open(image_fn1))\n hash2 = imagehash.average_hash(Image.open(image_fn2))\n if hash1 - hash2 < epsilon:\n print( '{} is near duplicate of {}'.format(image_fn1, image_fn2) )\n\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
23,962
<p>For example, Look at the code that calculates the n-th Fibonacci number:</p> <pre><code>fib(int n) { if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2); } </code></pre> <p>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).</p> <p>Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion?</p> <p>I am looking for a generic technique that can be used in almost all problems.</p>
[ { "answer_id": 23973, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 1, "selected": false, "text": "class fibstorage {\n\n\n bool has-result(int n) { return fibresults.contains(n); }\n int get-result(int n) { return fibresult.find(n).value; }\n void add-result(int n, int v) { fibresults.add(n,v); }\n\n map<int, int> fibresults;\n\n}\n\n\nfib(int n ) {\n if(n==0 || n==1)\n return 1;\n\n if (fibstorage.has-result(n)) {\n return fibstorage.get-result(n-1);\n }\n\n return ( (fibstorage.has-result(n-1) ? fibstorage.get-result(n-1) : fib(n-1) ) +\n (fibstorage.has-result(n-2) ? fibstorage.get-result(n-2) : fib(n-2) )\n );\n}\n\n\ncalcfib(n) {\n v = fib(n);\n fibstorage.add-result(n,v);\n}\n" }, { "answer_id": 23975, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 5, "selected": true, "text": "in OCaml:\n\nlet rec fibo n = \n let rec aux = fun\n | 0 -> (1,1)\n | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur)\n let (cur,prec) = aux n in prec;;\n\n\n\nin C++:\n\nint fibo(int n) {\n if (n == 0 ) return 1;\n if (n == 1 ) return 1;\n int p = fibo(0);\n int c = fibo(1);\n int buff = 0;\n for (int i=1; i < n; ++i) {\n buff = c;\n c = p+c;\n p = buff;\n };\n return c;\n};\n | u(n+1) | = | 1 1 | | u(n) |\n| u(n) | | 1 0 | | u(n-1) | \n | u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 |\n| u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 |\n M^(0) = Id\nM^(2p+1) = (M^2p) * M\nM^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here.\n" }, { "answer_id": 23985, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 1, "selected": false, "text": "var cache = [];\nfunction fib(n) {\n if (n < 2) return 1;\n if (cache.length > n) return cache[n];\n var result = fib(n - 2) + fib(n - 1);\n cache[n] = result;\n return result;\n}\n fibs = 1:1:(zipWith (+) fibs (tail fibs))\nfib n = fibs !! n\n" }, { "answer_id": 23986, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "(define (memoize fn)\n (letrec ((get (lambda (query) '(#f)))\n (set (lambda (query value)\n (let ((old-get get))\n (set! get (lambda (q)\n (if (equal? q query)\n (cons #t value)\n (old-get q))))))))\n (lambda args\n (let ((val (get args)))\n (if (car val)\n (cdr val)\n (let ((ret (apply fn args)))\n (set args ret)\n ret))))))\n\n\n(define fib (memoize (lambda (x)\n (if (< x 2) x\n (+ (fib (- x 1)) (fib (- x 2)))))))\n" }, { "answer_id": 24035, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "class Program\n{\n public static readonly Dictionary<int,int> Items = new Dictionary<int,int>();\n static void Main(string[] args)\n {\n Console.WriteLine(Fibbonacci(46).ToString());\n Console.ReadLine();\n }\n\n public static int Fibbonacci(int number)\n {\n if (number == 1 || number == 0)\n {\n return 1;\n }\n\n var minus2 = number - 2;\n var minus1 = number - 1;\n\n if (!Items.ContainsKey(minus2))\n {\n Items.Add(minus2, Fibbonacci(minus2));\n }\n\n if (!Items.ContainsKey(minus1))\n {\n Items.Add(minus1, Fibbonacci(minus1));\n }\n\n return (Items[minus2] + Items[minus1]);\n }\n}\n" }, { "answer_id": 24098, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 2, "selected": false, "text": "ulong Fib(int n)\n{\n ulong fib = 1; // value of fib(i)\n ulong fib1 = 1; // value of fib(i-1)\n ulong fib2 = 0; // value of fib(i-2)\n\n for (int i = 0; i < n; i++)\n {\n fib = fib1 + fib2;\n fib2 = fib1;\n fib1 = fib;\n }\n\n return fib;\n}\n" }, { "answer_id": 24169, "author": "ESRogs", "author_id": 88, "author_profile": "https://Stackoverflow.com/users/88", "pm_score": 2, "selected": false, "text": "type1 foo(type2 bar) { ... } map<type2, type1> M // your original method\nint fib(int n)\n{\n if(n==0 || n==1)\n return 1;\n return fib(n-1) + fib(n-2);\n}\n\n// with memoization\nmap<int, int> M = map<int, int>();\nint fib(int n)\n{\n if(n==0 || n==1)\n return 1;\n\n // only compute the value for fib(n) if we haven't before\n if(M.count(n) == 0)\n M[n] = fib(n-1) + fib(n-2);\n\n return M[n];\n}\n vector<something> map<int, something>" }, { "answer_id": 24175, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "std::map vector<unsigned int> fib_cache;\nfib_cache.push_back(1);\nfib_cache.push_back(1);\n\nunsigned int fib(unsigned int n) {\n if (fib_cache.size() <= n)\n fib_cache.push_back(fib(n - 1) + fib(n - 2));\n\n return fib_cache[n];\n}\n" }, { "answer_id": 24202, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "[Serializable]\npublic class MemoizeAttribute : PostSharp.Laos.OnMethodBoundaryAspect, IEqualityComparer<Object[]>\n{\n private Dictionary<Object[], Object> _Cache;\n\n public MemoizeAttribute()\n {\n _Cache = new Dictionary<object[], object>(this);\n }\n\n public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)\n {\n Object[] arguments = eventArgs.GetReadOnlyArgumentArray();\n if (_Cache.ContainsKey(arguments))\n {\n eventArgs.ReturnValue = _Cache[arguments];\n eventArgs.FlowBehavior = FlowBehavior.Return;\n }\n }\n\n public override void OnExit(MethodExecutionEventArgs eventArgs)\n {\n if (eventArgs.Exception != null)\n return;\n\n _Cache[eventArgs.GetReadOnlyArgumentArray()] = eventArgs.ReturnValue;\n }\n\n #region IEqualityComparer<object[]> Members\n\n public bool Equals(object[] x, object[] y)\n {\n if (Object.ReferenceEquals(x, y))\n return true;\n\n if (x == null || y == null)\n return false;\n\n if (x.Length != y.Length)\n return false;\n\n for (Int32 index = 0, len = x.Length; index < len; index++)\n if (Comparer.Default.Compare(x[index], y[index]) != 0)\n return false;\n\n return true;\n }\n\n public int GetHashCode(object[] obj)\n {\n Int32 hash = 23;\n\n foreach (Object o in obj)\n {\n hash *= 37;\n if (o != null)\n hash += o.GetHashCode();\n }\n\n return hash;\n }\n\n #endregion\n}\n [Memoize]\nprivate Int32 Fibonacci(Int32 n)\n{\n if (n <= 1)\n return 1;\n else\n return Fibonacci(n - 2) + Fibonacci(n - 1);\n}\n" }, { "answer_id": 25417, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 0, "selected": false, "text": " function (parameters)\n body (with recursive calls to calculate result)\n return result\n function (parameters)\n key = serialized parameters to string\n if (cache[key] does not exist) {\n body (with recursive calls to calculate result)\n cache[key] = result\n }\n return cache[key]\n" }, { "answer_id": 25419, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 0, "selected": false, "text": "# Compute Fibonacci numbers\nsub fib {\n my $n = shift;\n return $n if $n < 2;\n fib($n-1) + fib($n-2);\n}\n use Memoize;\nmemoize('fib');\n# Rest of the fib function just like the original version.\n# Now fib is automagically much faster ;-)\n" }, { "answer_id": 169900, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 1, "selected": false, "text": "fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n] = fib[n-1] + fib[n-2]\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
23,970
<p>Joe Van Dyk <a href="http://www.zenspider.com/pipermail/ruby/2008-August/004223.html" rel="noreferrer">asked the Ruby mailing list</a>:</p> <blockquote> <p>Hi,</p> <p>In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages?</p> <p>What I was trying to do:</p> </blockquote> <pre><code>l = lamda { ... } Bj.submit "/path/to/ruby/program", :stdin =&gt; Marshal.dump(l) </code></pre> <blockquote> <p>So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran.</p> <p>Joe</p> </blockquote>
[ { "answer_id": 3705317, "author": "dominic", "author_id": 122875, "author_profile": "https://Stackoverflow.com/users/122875", "pm_score": 4, "selected": false, "text": "code = %{\n lambda {\"hello ruby code\".split(\" \").each{|e| puts e + \"!\"}}\n}\n eval code\n %{} %{ [] {} }" }, { "answer_id": 52353048, "author": "Paul Brannan", "author_id": 244083, "author_profile": "https://Stackoverflow.com/users/244083", "pm_score": 1, "selected": false, "text": "p = proc { 1 + 1 } #=> #<Proc>\ns = Marshal.dump(p) #=> #<String>\nu = Marshal.load(s) #=> #<UnboundProc>\np2 = u.bind(binding) #=> #<Proc>\np2.call() #=> 2\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
23,996
<p>I'm working with <a href="http://webby.rubyforge.org" rel="nofollow noreferrer" title="Webby">Webby</a> and am looking for some clarification. Can I define attributes like <code>title</code> or <code>author</code> in my layout?</p>
[ { "answer_id": 26243, "author": "Mando Escamilla", "author_id": 1388162, "author_profile": "https://Stackoverflow.com/users/1388162", "pm_score": 2, "selected": true, "text": "SITE.page_defaults['title'] = \"My awesome title\"\nSITE.page_defaults['author'] = \"Shazbug\"\nSITE.page_defaults['is_mando_awesome'] = \"very yes\"\n Written by <%= @page.author %>\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2165/" ]
24,041
<p>I'm using markdown to edit this question right now. In some <a href="http://en.wikipedia.org/wiki/Wikipedia:How_to_edit_a_page#Wiki_markup" rel="noreferrer">wikis</a> I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use?</p>
[ { "answer_id": 24093, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": false, "text": "<ul>\n <li>Item one</li>\n <li>Item two</li>\n</ul>\n * Item one\n* Item two\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
24,046
<p>I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years. </p> <p>A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.</p> <p>Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.</p> <p>I made a pared down webpage to illustrate the principle.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt;&lt;title&gt;Safari Back Button Test&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; &lt;/head&gt; &lt;body onload="alert('Hello');"&gt; &lt;a href="http://www.codinghorror.com"&gt;Coding Horror&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.</p> <p>After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?</p> <p>If this is a stupid question please be gentle, javascript is somewhat new to me.</p>
[ { "answer_id": 24059, "author": "Stefan Ladwig", "author_id": 2585, "author_profile": "https://Stackoverflow.com/users/2585", "pm_score": 3, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head><title>Safari Back Button Test</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</head>\n<body onload=\"alert('Hello');\">\n<a href=\"http://www.codinghorror.com\">Coding Horror</a>\n<iframe style=\"height:0px;width:0px;visibility:hidden\" src=\"about:blank\">\nthis prevents back forward cache\n</iframe>\n</body>\n</html>\n" }, { "answer_id": 346841, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 4, "selected": false, "text": "window.onunload = function(){};\n" }, { "answer_id": 5846452, "author": "Manuel Pardo", "author_id": 733011, "author_profile": "https://Stackoverflow.com/users/733011", "pm_score": 3, "selected": false, "text": "<body onunload=\"\">" }, { "answer_id": 12294511, "author": "Gary Hayes", "author_id": 1615776, "author_profile": "https://Stackoverflow.com/users/1615776", "pm_score": 3, "selected": false, "text": "/*! Reloads page on every visit */\nfunction Reload() {\n try {\n var headElement = document.getElementsByTagName(\"head\")[0];\n if (headElement && headElement.innerHTML)\n headElement.innerHTML += \" \";\n } catch (e) {}\n }\n\n /*! Reloads on every visit in mobile safari */\n if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) {\n window.onpageshow = function(evt) {\n if (evt.persisted) {\n document.body.style.display = \"none\";\n location.reload();\n }\n };\n }\n" }, { "answer_id": 17023561, "author": "ArnaudBB", "author_id": 2470769, "author_profile": "https://Stackoverflow.com/users/2470769", "pm_score": 0, "selected": false, "text": "var showLoadingBoxSetIntervalVar;\nvar showLoadingBoxCount = 0;\nvar showLoadingBoxLoadedTimestamp = 0\n\nfunction showLoadingBox(text) {\n\n var showLoadingBoxSetIntervalVar=self.setInterval(function(){showLoadingBoxIpadRelaod()},1000);\n showLoadingBoxCount = 0\n showLoadingBoxLoadedTimestamp = new Date().getTime();\n\n //Here load the spinner\n\n}\n\nfunction showLoadingBoxIpadRelaod()\n{\n //Calculate difference between now and page loaded time minus threshold 500ms\n var diffTime = ( (new Date().getTime()) - showLoadingBoxLoadedTimestamp - 500)/1000;\n\n showLoadingBoxCount = showLoadingBoxCount + 1;\n var isiPad = navigator.userAgent.match(/iPad/i) != null;\n\n if(diffTime > showLoadingBoxCount && isiPad){\n location.reload();\n }\n}\n" }, { "answer_id": 19941107, "author": "bluesmoon", "author_id": 76392, "author_profile": "https://Stackoverflow.com/users/76392", "pm_score": 3, "selected": false, "text": "pageshow onload pageshow onload" }, { "answer_id": 36773400, "author": "ztech", "author_id": 1789517, "author_profile": "https://Stackoverflow.com/users/1789517", "pm_score": 2, "selected": false, "text": "$(window).bind(\"pageshow\", function(event) {\n if (event.originalEvent.persisted) {\n window.location.reload() \n }\n});\n" }, { "answer_id": 68949055, "author": "Samet ÇELİKBIÇAK", "author_id": 10509056, "author_profile": "https://Stackoverflow.com/users/10509056", "pm_score": 0, "selected": false, "text": "onunload=\"\" index.html <body class=\"mat-typography\" onunload=\"\">\n <app-root></app-root>\n</body>\n ngOnInit public ngOnInit(): void {\n window.onpageshow = (event) => {\n if (event.persisted) {\n document.body.style.display = \"none\";\n location.reload();\n }\n };\n ...\n }\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051/" ]
24,109
<p>I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE?</p> <p>I could find these SO topics:</p> <ul> <li><a href="https://stackoverflow.com/questions/2756/lightweight-ide-for-linux">Lightweight IDE for linux</a> and</li> <li><a href="https://stackoverflow.com/questions/17228/what-tools-do-you-use-to-develop-c-applications-on-linux">What tools do you use to develop C++ applications on Linux?</a></li> </ul> <p>I'm not looking for a <em>lightweight</em> IDE. If an IDE is worth the money, then I will pay for it, so it need not be free.</p> <p>My question, then:</p> <blockquote> <p><em>What good, C++ programming IDE is available for Linux?</em></p> </blockquote> <p>The minimums are fairly standard: syntax highlighting, code completion (like <a href="http://en.wikipedia.org/wiki/IntelliSense" rel="nofollow noreferrer">intellisense</a> or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints).</p> <p>I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that <a href="http://www.eclipse.org/cdt/" rel="nofollow noreferrer">Eclipse supports C++</a>, and I really like that IDE for Java, but is it any good for C++ and is there something better?</p> <p>The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages?</p> <p>Maybe my question should therefore be:</p> <blockquote> <p><em>What IDE do you propose (given your experiences), and why?</em></p> </blockquote>
[ { "answer_id": 24156, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "man $ man toolname\n $ make make .gvimrc g++ ld gdb DDD gdb TextBox cmd.exe :tabe :e gt :help gt" }, { "answer_id": 2540028, "author": "Charles Zhang", "author_id": 304449, "author_profile": "https://Stackoverflow.com/users/304449", "pm_score": 4, "selected": false, "text": "struct IdAndValue\n{\n int ID;\n int value;\n};\n\n\nIdAndValue IdAndValues[1000];\n define PrintVal \nset $i=0\nprintf \"ID = %d\\n\", $arg0\nwhile $i<1000\n if IdAndValues[$i].ID == $arg0\n printf \"ordinal = %d, value = %d\\n\", $i, IdAndValues[$i].vaue\n set $i++\n end\nend\nend\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ]
24,130
<p>Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.</p> <pre><code>// Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -&gt; name = $name; $this -&gt; height = $height; $this -&gt; weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; </code></pre> <hr> <p>Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.</p> <p>I've not idea which answer I should accept to I've just upvoted all of them.</p> <hr> <p>And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.</p> <p>Thank you for helping to make me a better programmer.</p>
[ { "answer_id": 24134, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": true, "text": "weight getWeight() setWeight() setWeight() public function setWeight($weight)\n{\n if($weight >= 0)\n {\n $this->weight = $weight;\n }\n else\n {\n // Handle this scenario however you like\n }\n}\n" }, { "answer_id": 4571581, "author": "Richard Varno", "author_id": 214891, "author_profile": "https://Stackoverflow.com/users/214891", "pm_score": 0, "selected": false, "text": " <?php\n$rx = \"\";\n$rt = \"\";\n$rf = \"\";\n\n$ta = 0; // total array time\n$tc = 0; // total class time\n\n// flip these to test different attributes\n$test_globals = true;\n$test_functions = true;\n$test_assignments = true;\n$test_reads = true;\n\n\n// define class\n\n\nclass TestObject\n{\n public $a;\n public $b;\n public $c;\n public $d;\n public $e;\n public $f;\n\n public function __construct($a,$b,$c,$d,$e,$f)\n {\n $this->a = $a;\n $this->b = $b;\n $this->c = $c;\n $this->d = $d;\n $this->e = $e;\n $this->f = $f;\n }\n\n public function setAtoB()\n {\n $this->a = $this->b;\n }\n}\n\n// begin test\n\necho \"<br>test reads: \" . $test_reads;\necho \"<br>test assignments: \" . $test_assignments;\necho \"<br>test globals: \" . $test_globals;\necho \"<br>test functions: \" . $test_functions;\necho \"<br>\";\n\nfor ($z=0;$z<10;$z++)\n{\n $starta = microtime(true);\n\n for ($x=0;$x<100000;$x++)\n {\n $xr = getArray('aaa','bbb','ccccccccc','ddddddddd','eeeeeeee','fffffffffff');\n\n if ($test_assignments)\n {\n $xr['e'] = \"e\";\n $xr['c'] = \"sea biscut\";\n }\n\n if ($test_reads)\n {\n $rt = $x['b'];\n $rx = $x['f'];\n }\n\n if ($test_functions) { setArrAtoB($xr); }\n if ($test_globals) { $rf = glb_arr(); }\n }\n $ta = $ta + (microtime(true)-$starta);\n echo \"<br/>Array time = \" . (microtime(true)-$starta) . \"\\n\\n\";\n\n\n $startc = microtime(true);\n\n for ($x=0;$x<100000;$x++)\n {\n $xo = new TestObject('aaa','bbb','ccccccccc','ddddddddd','eeeeeeee','fffffffffff');\n\n if ($test_assignments)\n {\n $xo->e = \"e\";\n $xo->c = \"sea biscut\";\n }\n\n if ($test_reads)\n {\n $rt = $xo->b;\n $rx = $xo->f;\n }\n\n if ($test_functions) { $xo->setAtoB(); }\n if ($test_globals) { $xf = glb_cls(); }\n }\n\n $tc = $tc + (microtime(true)-$startc);\n echo \"<br>Class time = \" . (microtime(true)-$startc) . \"\\n\\n\";\n\n echo \"<br>\";\n echo \"<br>Total Array time (so far) = \" . $ta . \"(100,000 iterations) \\n\\n\";\n echo \"<br>Total Class time (so far) = \" . $tc . \"(100,000 iterations) \\n\\n\";\n echo \"<br>\";\n\n}\necho \"TOTAL TIMES:\";\necho \"<br>\";\necho \"<br>Total Array time = \" . $ta . \"(1,000,000 iterations) \\n\\n\";\necho \"<br>Total Class time = \" . $tc . \"(1,000,000 iterations)\\n\\n\";\n\n\n// test functions\n\nfunction getArray($a,$b,$c,$d,$e,$f)\n{\n $arr = array();\n $arr['a'] = $a;\n $arr['b'] = $b;\n $arr['c'] = $c;\n $arr['d'] = $d;\n $arr['d'] = $e;\n $arr['d'] = $f;\n return($arr);\n}\n\n//-------------------------------------\n\nfunction setArrAtoB($r)\n{\n $r['a'] = $r['b'];\n}\n\n//-------------------------------------\n\nfunction glb_cls()\n{\n global $xo;\n\n $xo->d = \"ddxxdd\";\n return ($xo->f);\n}\n\n//-------------------------------------\n\nfunction glb_arr()\n{\n global $xr;\n\n $xr['d'] = \"ddxxdd\";\n return ($xr['f']);\n}\n\n//-------------------------------------\n\n?>\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
24,168
<p>When writing database queries in something like TSQL or PLSQL, we often have a choice of iterating over rows with a cursor to accomplish the task, or crafting a single SQL statement that does the same job all at once.</p> <p>Also, we have the choice of simply pulling a large set of data back into our application and then processing it row by row, with C# or Java or PHP or whatever.</p> <p>Why is it better to use set-based queries? What is the theory behind this choice? What is a good example of a cursor-based solution and its relational equivalent?</p>
[ { "answer_id": 24211, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": false, "text": "--Cursor\nDECLARE @phoneNumber char(7)\nDECLARE c CURSOR LOCAL FAST_FORWARD FOR\n SELECT PhoneNumber FROM Customer WHERE AreaCode IS NULL\nOPEN c\nFETCH NEXT FROM c INTO @phoneNumber\nWHILE @@FETCH_STATUS = 0 BEGIN\n DECLARE @exchange char(3), @areaCode char(3)\n SELECT @exchange = LEFT(@phoneNumber, 3)\n\n SELECT @areaCode = AreaCode \n FROM AreaCode_Exchange \n WHERE Exchange = @exchange\n\n IF @areaCode IS NOT NULL BEGIN\n UPDATE Customer SET AreaCode = @areaCode\n WHERE CURRENT OF c\n END\n FETCH NEXT FROM c INTO @phoneNumber\nEND\nCLOSE c\nDEALLOCATE c\nEND\n\n--Set\nUPDATE Customer SET\n AreaCode = AreaCode_Exchange.AreaCode\nFROM Customer\nJOIN AreaCode_Exchange ON\n LEFT(Customer.PhoneNumber, 3) = AreaCode_Exchange.Exchange\nWHERE\n Customer.AreaCode IS NULL\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
24,200
<p>I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.</p> <p>I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.</p> <p>I have a simple table that looks like this: </p> <pre><code> CREATE TABLE [BulkData]( [ContainerId] [int] NOT NULL, [BinId] [smallint] NOT NULL, [Sequence] [smallint] NOT NULL, [ItemId] [int] NOT NULL, [Left] [smallint] NOT NULL, [Top] [smallint] NOT NULL, [Right] [smallint] NOT NULL, [Bottom] [smallint] NOT NULL, CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED ( [ContainerIdId] ASC, [BinId] ASC, [Sequence] ASC )) </code></pre> <p>I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. </p> <p>The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.</p> <p>Does it help any if I:</p> <ol> <li>Drop the Primary key while I am doing the inserting and recreate it later</li> <li>Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small</li> <li>Anything else?</li> </ol> <p>-- Based on the responses I have gotten, let me clarify a little bit:</p> <p>Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?</p> <p>Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.</p> <p>Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps.</p>
[ { "answer_id": 2899468, "author": "JohnB", "author_id": 287311, "author_profile": "https://Stackoverflow.com/users/287311", "pm_score": 5, "selected": false, "text": "--Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE\nGO\n--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948/" ]
24,207
<p>I'm trying to use “rusage” statistics in my program to get data similar to that of the <a href="http://en.wikipedia.org/wiki/Time_%28Unix%29" rel="nofollow noreferrer">time</a> tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better?</p> <p>Sorry for the long code.</p> <pre><code>class StopWatch { public: void start() { getrusage(RUSAGE_SELF, &amp;m_begin); gettimeofday(&amp;m_tmbegin, 0); } void stop() { getrusage(RUSAGE_SELF, &amp;m_end); gettimeofday(&amp;m_tmend, 0); timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime); timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime); timeval_sub(m_tmend, m_tmbegin, m_tmdiff); } void printf(std::ostream&amp; out) const { using namespace std; timeval const&amp; utime = m_diff.ru_utime; timeval const&amp; stime = m_diff.ru_stime; format_time(out, utime); out &lt;&lt; "u "; format_time(out, stime); out &lt;&lt; "s "; format_time(out, m_tmdiff); } private: rusage m_begin; rusage m_end; rusage m_diff; timeval m_tmbegin; timeval m_tmend; timeval m_tmdiff; static void timeval_add(timeval const&amp; a, timeval const&amp; b, timeval&amp; ret) { ret.tv_usec = a.tv_usec + b.tv_usec; ret.tv_sec = a.tv_sec + b.tv_sec; if (ret.tv_usec &gt; 999999) { ret.tv_usec -= 1000000; ++ret.tv_sec; } } static void timeval_sub(timeval const&amp; a, timeval const&amp; b, timeval&amp; ret) { ret.tv_usec = a.tv_usec - b.tv_usec; ret.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_usec &lt; b.tv_usec) { ret.tv_usec += 1000000; --ret.tv_sec; } } static void format_time(std::ostream&amp; out, timeval const&amp; tv) { using namespace std; long usec = tv.tv_usec; while (usec &gt;= 1000) usec /= 10; out &lt;&lt; tv.tv_sec &lt;&lt; '.' &lt;&lt; setw(3) &lt;&lt; setfill('0') &lt;&lt; usec; } }; // class StopWatch </code></pre>
[ { "answer_id": 26827, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 2, "selected": false, "text": "static int timeval_diff_ms(timeval const& end, timeval const& start) {\n int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000 \n + end.tv_usec - start.tv_usec;\n\n return micro_seconds;\n}\n\nstatic float timeval_diff(timeval const& end, timeval const& start) {\n return (timeval_diff_ms(end, start)/1000000.0f);\n}\n" }, { "answer_id": 71401, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "while (usec >= 1000)\n usec /= 10;\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
24,221
<p>What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?</p> <p>What are their typical usages?</p> <p>Are they unique to Java? Is there a C++ equivalent?</p>
[ { "answer_id": 24227, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "@Override" }, { "answer_id": 24335, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "@Test(expected=IOException.class)\npublic void flatfileMissing() throws IOException {\n readFlatFile(\"testfiles\"+separator+\"flatfile_doesnotexist.dat\");\n}\n @Test flatfileMissing IOException IOException" }, { "answer_id": 34927561, "author": "Harvester", "author_id": 5821907, "author_profile": "https://Stackoverflow.com/users/5821907", "pm_score": 0, "selected": false, "text": "transfer(Account account1, Account account2, long amount) \n{\n // 1: Call middleware API to perform a security check\n // 2: Call middleware API to start a transaction\n // 3: Call middleware API to load rows from the database\n // 4: Subtract the balance from one account, add to the other\n // 5: Call middleware API to store rows in the database\n // 6: Call middleware API to end the transaction\n}\n transfer(Account account1, Account account2, long amount) \n{\n // 1: Subtract the balance from one account, add to the other\n}\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142/" ]
24,241
<p>Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?</p>
[ { "answer_id": 39620743, "author": "unknown6656", "author_id": 3902603, "author_profile": "https://Stackoverflow.com/users/3902603", "pm_score": 2, "selected": false, "text": "IntPtr _methodPtr IntPtr _methodPtrAux _methodPtr public static unsafe int? InjectAndRunX86ASM(this Func<int> del, byte[] asm)\n{\n if (del != null)\n fixed (byte* ptr = &asm[0])\n {\n FieldInfo _methodPtr = typeof(Delegate).GetField(\"_methodPtr\", BindingFlags.NonPublic | BindingFlags.Instance);\n FieldInfo _methodPtrAux = typeof(Delegate).GetField(\"_methodPtrAux\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n _methodPtr.SetValue(del, ptr);\n _methodPtrAux.SetValue(del, ptr);\n\n return del();\n }\n else\n return null;\n}\n Func<int> del = () => 0;\nbyte[] asm_bytes = new byte[] { 0xb8, 0x15, 0x03, 0x00, 0x00, 0xbb, 0x42, 0x00, 0x00, 0x00, 0x03, 0xc3 };\n// mov eax, 315h\n// mov ebx, 42h\n// add eax, ebx\n// ret\n\nint res = del.InjectAndRunX86ASM(asm_bytes); // should be 789 + 66 = 855\n public static unsafe int RunX86ASM(byte[] asm)\n{\n Func<int> del = () => 0; // create a delegate variable\n Array.Resize(ref asm, asm.Length + 1);\n\n // add a return instruction at the end to prevent any memory leaks\n asm[asm.Length - 1] = 0xC3;\n\n fixed (byte* ptr = &asm[0])\n {\n FieldInfo _methodPtr = typeof(Delegate).GetField(\"_methodPtr\", BindingFlags.NonPublic | BindingFlags.Instance);\n FieldInfo _methodPtrAux = typeof(Delegate).GetField(\"_methodPtrAux\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n _methodPtr.SetValue(del, ptr);\n _methodPtrAux.SetValue(del, ptr);\n\n return del();\n }\n}\n // UNTESTED //\n\nAction new_method_body = () => { };\nMethodInfo nfo = typeof(MyType).GetMethod( ..... );\nIntPtr ptr = nfo.MethodHandle.Value; // ptr is a pointer to the method in question\n\nInjectX86ASM(new_method_body, new byte[] { ......., 0xC3 }); // assembly bytes to be injected\n\nint target = new_method_body.Method.MethodHandle.Value.ToInt32();\n\nbyte[] redirector = new byte[] {\n 0xE8, // CALL INSTRUCTION + TARGET ADDRESS IN LITTLE ENDIAN\n (byte)(target & 0xff),\n (byte)((target >> 8) & 0xff),\n (byte)((target >> 16) & 0xff),\n (byte)((target >> 24) & 0xff),\n 0xC3, // RETURN INSTRUCTION\n};\nMarshal.Copy(redirector, 0, ptr, redirector.Length);\n /unsafe" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
24,270
<p>As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace.</p> <p>I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does <em>exactly</em> what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible <em>in the right way</em>, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile.</p> <p>In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles).</p> <p>So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better?</p>
[ { "answer_id": 24331, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "HANDLE" }, { "answer_id": 24361, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "RegisterClass CreateWindow WndProc DefWindowProc final" }, { "answer_id": 402001, "author": "Dan Rosenstark", "author_id": 8047, "author_profile": "https://Stackoverflow.com/users/8047", "pm_score": 3, "selected": false, "text": "variable2654 variable3 value b c q Z this this this this this this" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2131/" ]
24,279
<p>In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming.</p> <p>What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language?</p>
[ { "answer_id": 24301, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 2, "selected": false, "text": "SomeKindOfRecord<T> getOrCreate(T thing) { \n if(localMap.contains(thing)) { return localMap.get(thing); }\n SomeKindOfRecord<T> record = new SomeKindOfRecord<T>(thing);\n localMap = localMap.put(thing, record);\n return record; \n}\n RT<T> getOrCreate(T thing, \n Function<RT<T>> thingConstructor, \n Map<T,RT<T>> localMap) {\n if(localMap.contains(thing)) { return localMap.get(thing); }\n RT<T> record = thingConstructor(thing);\n localMap = localMap.put(thing,record);\n return record; \n}\n getOrCreate = myLib.getOrCreate(*,\n SomeKindOfRecord<T>.constructor(<T>), \n localMap);\n" }, { "answer_id": 559340, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "record = thingConstructor(t) localMap.put(record) return return ?: localMap.put" }, { "answer_id": 14549335, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 5, "selected": false, "text": "map reduce mapReduce System.Func System.Action Parallel.For Linq void *" }, { "answer_id": 34650349, "author": "onmyway133", "author_id": 1418457, "author_profile": "https://Stackoverflow.com/users/1418457", "pm_score": 1, "selected": false, "text": "when public Program getProgramAt(TVGuide guide, int channel, Date when) {\n Schedule schedule = guide.getSchedule(channel);\n\n Program program = schedule.programAt(when);\n\n return program;\n}\n public Program getCurrentProgram(TVGuide guide, int channel) {\n Schedule schedule = guide.getSchedule(channel);\n\n Program current = schedule.programAt(new Date());\n\n return current;\n}\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
24,298
<p>I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application.</p> <p>I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand.</p>
[ { "answer_id": 741170, "author": "Brian Armstrong", "author_id": 76486, "author_profile": "https://Stackoverflow.com/users/76486", "pm_score": 7, "selected": true, "text": "has_secure_password" }, { "answer_id": 1901005, "author": "sarahhodne", "author_id": 231245, "author_profile": "https://Stackoverflow.com/users/231245", "pm_score": 2, "selected": false, "text": ":perishable_token" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168/" ]
24,315
<p>In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.</p> <p>The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.</p> <p>Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?</p>
[ { "answer_id": 24429, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": false, "text": " Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)\n Dim FileOpen As Boolean\n Dim File As System.IO.FileStream = Nothing\n Dim StartTime As DateTime\n Dim MaxWaitSeconds As Integer = 120\n\n StartTime = DateTime.Now\n\n FileOpen = False\n\n Do\n Try\n File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)\n FileOpen = True\n\n Catch ex As Exception\n\n If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then\n Throw New Exception(\"Waited more than \" & MaxWaitSeconds & \" To Open File.\")\n Else\n Dim FileWatch As System.IO.FileSystemWatcher\n\n FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)\n FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)\n End If\n\n FileOpen = False\n\n End Try\n\n Loop While Not FileOpen\n\n If FileOpen Then\n File.Write(Data, 0, Data.Length)\n File.Close()\n End If\n End Sub\n" }, { "answer_id": 1115109, "author": "Jader Dias", "author_id": 48465, "author_profile": "https://Stackoverflow.com/users/48465", "pm_score": 0, "selected": false, "text": "using (var watcher = new FileSystemWatcher(MatlabPath, fileName))\n{\n var wait = new EventWaitHandle(false, EventResetMode.AutoReset);\n watcher.EnableRaisingEvents = true;\n watcher.Changed += delegate(object sender, FileSystemEventArgs e)\n {\n wait.Set();\n };\n if (!wait.WaitOne(MillissecondsTimeout))\n {\n throw new TimeoutException();\n }\n }\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
24,451
<p>I've long been under the impression that <code>goto</code> should never be used if possible.</p> <p>However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it.</p> <p>Is it ever advantageous to use <code>goto</code> in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a <code>goto</code>.</p>
[ { "answer_id": 24475, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "goto goto goto finally goto return goto goto goto" }, { "answer_id": 24511, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 5, "selected": false, "text": "switch(value)\n{\n case 0:\n Console.WriteLine(\"In case 0\");\n goto case 1;\n case 1:\n Console.WriteLine(\"In case 1\");\n goto case 2;\n case 2:\n Console.WriteLine(\"In case 2\");\n goto default;\n default:\n Console.WriteLine(\"In default\");\n break;\n}\n" }, { "answer_id": 24537, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 3, "selected": false, "text": "loop1:\n a\nloop2:\n b\n if(cond1) goto loop1\n c\n if(cond2) goto loop2\n goto goto" }, { "answer_id": 25598, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "#ifdef TONGUE_IN_CHEEK goto sub factorial {\n my ($n, $acc) = (@_, 1);\n return $acc if $n < 1;\n @_ = ($n - 1, $acc * $n);\n goto &factorial;\n}\n #endif goto goto longjmp call/cc" }, { "answer_id": 74375, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "caller() goto &subroutine sub AUTOLOAD{\n my($self) = @_;\n my $name = $AUTOLOAD;\n $name =~ s/.*:://;\n\n *{$name} = my($sub) = sub{\n # the body of the closure\n }\n\n goto $sub;\n\n # nothing after the goto will ever be executed.\n}\n goto sub factorial($){\n my($n,$tally) = (@_,1);\n\n return $tally if $n <= 1;\n\n $tally *= $n--;\n @_ = ($n,$tally);\n goto &factorial;\n}\n goto __SUB__; tail recur goto use Sub::Call::Tail;\nsub AUTOLOAD {\n ...\n tail &$sub( @_ );\n}\n\nuse Sub::Call::Recur;\nsub factorial($){\n my($n,$tally) = (@_,1);\n\n return $tally if $n <= 1;\n recur( $n-1, $tally * $n );\n}\n goto redo LABEL: ;\n...\ngoto LABEL if $x;\n {\n ...\n redo if $x;\n}\n last goto LABEL if $x;\n...\ngoto LABEL if $y;\n...\nLABEL: ;\n {\n last if $x;\n ...\n last if $y\n ...\n}\n" }, { "answer_id": 2187203, "author": "dsimcha", "author_id": 23903, "author_profile": "https://Stackoverflow.com/users/23903", "pm_score": 7, "selected": false, "text": "goto goto goto goto goto" }, { "answer_id": 2809244, "author": "Ricardo", "author_id": 338062, "author_profile": "https://Stackoverflow.com/users/338062", "pm_score": 3, "selected": false, "text": "// Overwrite an element with same hash key if it exists\nfor (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++)\n if (slot_p[add_index].hash_key == hash_key)\n goto add;\n\n// Otherwise, find first empty element\nfor (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++)\n if ((slot_p[add_index].type == TT_ELEMENT_EMPTY)\n goto add;\n\n// Additional passes go here...\n\nadd:\n// element is written to the hash table here\n // Overwrite an element with same hash key if it exists\nfor (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++)\n if (slot_p[add_index].hash_key == hash_key)\n break;\n\nif (add_index >= ELEMENTS_PER_BUCKET) {\n // Otherwise, find first empty element\n for (add_index=0; add_index < ELEMENTS_PER_BUCKET; add_index++)\n if ((slot_p[add_index].type == TT_ELEMENT_EMPTY)\n break;\n if (add_index >= ELEMENTS_PER_BUCKET)\n // Additional passes go here (nested further)...\n}\n\n// element is written to the hash table here\n" }, { "answer_id": 2809313, "author": "Viktor Sehr", "author_id": 100724, "author_profile": "https://Stackoverflow.com/users/100724", "pm_score": 5, "selected": false, "text": "goto's // 1\n try{\n ...\n throw NoErrorException;\n ...\n } catch (const NoErrorException& noe){\n // This is the worst\n } \n\n\n // 2\n do {\n ...break; \n ...break;\n } while (false);\n\n\n // 3\n for(int i = 0;...) { \n bool restartOuter = false;\n for (int j = 0;...) {\n if (...)\n restartOuter = true;\n if (restartOuter) {\n i = -1;\n }\n }\n\netc\netc\n" }, { "answer_id": 2809622, "author": "JUST MY correct OPINION", "author_id": 282658, "author_profile": "https://Stackoverflow.com/users/282658", "pm_score": 10, "selected": false, "text": "goto goto goto goto goto goto #define _ -F<00||--F-OO--;\nint F=00,OO=00;main(){F_OO();printf(\"%1.3f\\n\",4.*-F/OO/OO);}F_OO()\n{\n _-_-_-_\n _-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_\n _-_-_-_\n}\n goto a[900]; b;c;d=1 ;e=1;f; g;h;O; main(k,\nl)char* *l;{g= atoi(* ++l); for(k=\n0;k*k< g;b=k ++>>1) ;for(h= 0;h*h<=\ng;++h); --h;c=( (h+=g>h *(h+1)) -1)>>1;\nwhile(d <=g){ ++O;for (f=0;f< O&&d<=g\n;++f)a[ b<<5|c] =d++,b+= e;for( f=0;f<O\n&&d<=g; ++f)a[b <<5|c]= d++,c+= e;e= -e\n;}for(c =0;c<h; ++c){ for(b=0 ;b<k;++\nb){if(b <k/2)a[ b<<5|c] ^=a[(k -(b+1))\n<<5|c]^= a[b<<5 |c]^=a[ (k-(b+1 ))<<5|c]\n;printf( a[b<<5|c ]?\"%-4d\" :\" \" ,a[b<<5\n|c]);} putchar( '\\n');}} /*Mike Laman*/\n goto for #define goto goto goto goto goto godo do break goto goto" }, { "answer_id": 2810495, "author": "Sandy", "author_id": 338240, "author_profile": "https://Stackoverflow.com/users/338240", "pm_score": 2, "selected": false, "text": "for (stepfailed=0 ; ! stepfailed ; /*empty*/)\n" }, { "answer_id": 8726959, "author": "pocjoc", "author_id": 357960, "author_profile": "https://Stackoverflow.com/users/357960", "pm_score": 2, "selected": false, "text": "If A <> 0 Then A = 0 EndIf\nWrite(\"Value of A:\" + A)\n If A == 0 Then GOTO FINAL EndIf\n A = 0\nFINAL:\nWrite(\"Value of A:\" + A)\n GOTO FINAL" }, { "answer_id": 20081648, "author": "Nuclear", "author_id": 935512, "author_profile": "https://Stackoverflow.com/users/935512", "pm_score": 1, "selected": false, "text": "int doSomething (struct my_complicated_stuff *ctx) \n{\n db_conn *conn;\n RSA *key;\n char *temp_data;\n conn = db_connect(); \n\n\n if (ctx->smth->needs_alloc) {\n temp_data=malloc(ctx->some_size);\n if (!temp_data) {\n db_disconnect(conn);\n return -1; \n }\n }\n\n ...\n\n if (!ctx->smth->needs_to_be_processed) {\n free(temp_data); \n db_disconnect(conn); \n return -2;\n }\n\n pthread_mutex_lock(ctx->mutex);\n\n if (ctx->some_other_thing->error) {\n pthread_mutex_unlock(ctx->mutex);\n free(temp_data);\n db_disconnect(conn); \n return -3; \n }\n\n ...\n\n key=rsa_load_key(....);\n\n ...\n\n if (ctx->something_else->error) {\n rsa_free(key); \n pthread_mutex_unlock(ctx->mutex);\n free(temp_data);\n db_disconnect(conn); \n return -4; \n }\n\n if (ctx->something_else->additional_check) {\n rsa_free(key); \n pthread_mutex_unlock(ctx->mutex);\n free(temp_data);\n db_disconnect(conn); \n return -5; \n }\n\n\n pthread_mutex_unlock(ctx->mutex);\n free(temp_data); \n db_disconnect(conn); \n return 0; \n}\n int doSomething_goto (struct my_complicated_stuff *ctx)\n{\n int ret=0;\n db_conn *conn;\n RSA *key;\n char *temp_data;\n conn = db_connect(); \n\n\n if (ctx->smth->needs_alloc) {\n temp_data=malloc(ctx->some_size);\n if (!temp_data) {\n ret=-1;\n goto exit_db; \n }\n }\n\n ...\n\n if (!ctx->smth->needs_to_be_processed) {\n ret=-2;\n goto exit_freetmp; \n }\n\n pthread_mutex_lock(ctx->mutex);\n\n if (ctx->some_other_thing->error) {\n ret=-3;\n goto exit; \n }\n\n ...\n\n key=rsa_load_key(....);\n\n ...\n\n if (ctx->something_else->error) {\n ret=-4;\n goto exit_freekey; \n }\n\n if (ctx->something_else->additional_check) {\n ret=-5;\n goto exit_freekey; \n }\n\nexit_freekey:\n rsa_free(key);\nexit: \n pthread_mutex_unlock(ctx->mutex);\nexit_freetmp:\n free(temp_data); \nexit_db:\n db_disconnect(conn); \n return ret; \n}\n" }, { "answer_id": 21360087, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 3, "selected": false, "text": "int big_function()\n{\n /* do some work */\n if([error])\n {\n /* clean up*/\n return [error];\n }\n /* do some more work */\n if([error])\n {\n /* clean up*/\n return [error];\n }\n /* do some more work */\n if([error])\n {\n /* clean up*/\n return [error];\n }\n /* do some more work */\n if([error])\n {\n /* clean up*/\n return [error];\n }\n /* clean up*/\n return [success];\n}\n goto int big_function()\n{\n int ret_val = [success];\n /* do some work */\n if([error])\n {\n ret_val = [error];\n goto end;\n }\n /* do some more work */\n if([error])\n {\n ret_val = [error];\n goto end;\n }\n /* do some more work */\n if([error])\n {\n ret_val = [error];\n goto end;\n }\n /* do some more work */\n if([error])\n {\n ret_val = [error];\n goto end;\n }\nend:\n /* clean up*/\n return ret_val;\n}\n goto" }, { "answer_id": 24730841, "author": "Fizz", "author_id": 3588161, "author_profile": "https://Stackoverflow.com/users/3588161", "pm_score": 2, "selected": false, "text": "if (something())\n goto fail;\n goto fail; // copypasta bug\nprintf(\"Never reached\\n\");\nfail:\n // control jumps here\n struct Fail {};\n\ntry {\n if (something())\n throw Fail();\n throw Fail(); // copypasta bug\n printf(\"Never reached\\n\");\n}\ncatch (Fail&) {\n // control jumps here\n}\n int computation1() {\n return 1;\n}\n\nint computation2() {\n return computation1();\n}\n void tough1() {\n if (computation1() != computation2())\n printf(\"Unreachable\\n\");\n}\n\nvoid tough2() {\n if (computation1() == computation2())\n goto out;\n printf(\"Unreachable\\n\");\nout:;\n}\n\nstruct Out{};\n\nvoid tough3() {\n try {\n if (computation1() == computation2())\n throw Out();\n printf(\"Unreachable\\n\");\n }\n catch (Out&) {\n }\n}\n" }, { "answer_id": 40031837, "author": "Jan Turoň", "author_id": 343721, "author_profile": "https://Stackoverflow.com/users/343721", "pm_score": 3, "selected": false, "text": "int i;\n\nPROMPT_INSERT_NUMBER:\n std::cout << \"insert number: \";\n std::cin >> i;\n if(std::cin.fail()) {\n std::cin.clear();\n std::cin.ignore(1000,'\\n');\n goto PROMPT_INSERT_NUMBER; \n }\n\nstd::cout << \"your number is \" << i;\n int i;\n\nbool loop;\ndo {\n loop = false;\n std::cout << \"insert number: \";\n std::cin >> i;\n if(std::cin.fail()) {\n std::cin.clear();\n std::cin.ignore(1000,'\\n');\n loop = true; \n }\n} while(loop);\n\nstd::cout << \"your number is \" << i;\n {} do {...} while loop loop loop void sort(int* array, int length) {\nSORT:\n for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) {\n swap(data[i], data[i+1]);\n goto SORT; // it is very easy to understand this code, right?\n }\n}\n void sort(int* array, int length) {\n bool seemslegit;\n do {\n seemslegit = true;\n for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) {\n swap(data[i], data[i+1]);\n seemslegit = false;\n }\n } while(!seemslegit);\n}\n void sort(int* array, int length) {\n for(int i=0; i<length-1; ++i) if(array[i]>array[i+1]) {\n swap(data[i], data[i+1]);\n i = -1; // it works, but WTF on the first glance\n }\n}\n ; P1 states loops\n; 11111110 <-\n; 11111101 |\n; 11111011 |\n; 11110111 |\n; 11101111 |\n; 11011111 |\n; |_________|\n\ninit_roll_state:\n MOV P1,#11111110b\n ACALL delay\nnext_roll_state:\n MOV A,P1\n RL A\n MOV P1,A\n ACALL delay\n JNB P1.5, init_roll_state\n SJMP next_roll_state\n if(valid) {\n do { // while(loop)\n\n// more than one page of code here\n// so it is better to comment the meaning\n// of the corresponding curly bracket\n\n } while(loop);\n} // if(valid)\n if(!valid) goto NOTVALID;\n LOOPBACK:\n\n// more than one page of code here\n\n if(loop) goto LOOPBACK;\nNOTVALID:;\n" }, { "answer_id": 57281180, "author": "Beefster", "author_id": 5079779, "author_profile": "https://Stackoverflow.com/users/5079779", "pm_score": 2, "selected": false, "text": "for cur_char, next_char in sliding_window(input_string) {\n if cur_char == '%' {\n if next_char == '%' {\n cur_char_index += 1\n goto handle_literal\n }\n # Some additional logic\n if chars_should_be_handled_literally() {\n goto handle_literal\n }\n # Handle the format\n }\n # some other control characters\n else {\n handle_literal:\n # Complicated logic here\n # Maybe it's writing to an array for some OpenGL calls later or something,\n # all while modifying a bunch of local variables declared outside the loop\n }\n}\n goto handle_literal continue" }, { "answer_id": 64478049, "author": "bask185", "author_id": 8477952, "author_profile": "https://Stackoverflow.com/users/8477952", "pm_score": 3, "selected": false, "text": "goto switch( x ) {\n \n case 1: case1() ; doStuffFor123() ; break ;\n case 2: case2() ; doStuffFor123() ; break ;\n case 3: case3() ; doStuffFor123() ; break ;\n \n case 4: case4() ; doStuffFor456() ; break ;\n case 5: case5() ; doStuffFor456() ; break ;\n case 6: case6() ; doStuffFor456() ; break ;\n \n case 7: case7() ; doStuffFor789() ; break ;\n case 8: case8() ; doStuffFor789() ; break ;\n case 9: case9() ; doStuffFor789() ; break ;\n}\n break goto goto switch( x ) {\n \n case 1: case1() ; goto stuff123 ;\n case 2: case2() ; goto stuff123 ;\n case 3: case3() ; goto stuff123 ;\n \n case 4: case4() ; goto stuff456 ;\n case 5: case5() ; goto stuff456 ;\n case 6: case6() ; goto stuff456 ;\n \n case 7: case7() ; goto stuff789 ;\n case 8: case8() ; goto stuff789 ;\n case 9: case9() ; goto stuff789 ;\n \n stuff123: doStuffFor123() ; break ;\n stuff456: doStuffFor456() ; break ;\n stuff789: doStuffFor789() ; break ;\n}\n doStuffFor123() doStuffFor456()" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
24,468
<p>When I try to run a .NET assembly (<code>boo.exe</code>) from a network share (mapped to a drive), it fails since it's only partially trusted:</p> <pre><code>Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe </code></pre> <p>With instructions from <a href="http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx" rel="nofollow noreferrer">a blog post</a>, I added a policy to the .NET Configuration fully trusting all assemblies with <code>file:///H:/*</code> as their URL. I verified this by entering the URL <code>file:///H:/boo-svn/bin/boo.exe</code> into the <em>Evaluate Assembly</em> tool in the .NET Configuration and noting that boo.exe had the <em>Unrestricted</em> permission (which it didn't have before the policy).</p> <p>Even with the permission, <code>boo.exe</code> does not run. I still get the same error message.</p> <p>What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?</p>
[ { "answer_id": 26376, "author": "Tomi Kyöstilä", "author_id": 616, "author_profile": "https://Stackoverflow.com/users/616", "pm_score": 2, "selected": false, "text": "caspol caspol -addgroup 1.2 -url file:///H:/* FullTrust\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616/" ]
24,470
<p>Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.</p> <pre><code>Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT </code></pre> <p>I would like to use PIVOT (if even possible) to make the results like so:</p> <pre><code>Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT </code></pre> <p>Is this even possible with the PIVOT functionality?</p>
[ { "answer_id": 24538, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 3, "selected": false, "text": "select \n distinct a,\n (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'),\n (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT')\nfrom t t1\n" }, { "answer_id": 40434, "author": "John Hubert", "author_id": 4286, "author_profile": "https://Stackoverflow.com/users/4286", "pm_score": 8, "selected": true, "text": "SELECT Action,\n MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, \n MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol\n FROM t\n GROUP BY Action\n" }, { "answer_id": 40625, "author": "Miles D", "author_id": 3898, "author_profile": "https://Stackoverflow.com/users/3898", "pm_score": 6, "selected": false, "text": "SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'\nFROM (\n SELECT act, cmd FROM data\n) AS src\nPIVOT (\n MAX(cmd) FOR cmd IN ([View], [Edit])\n) AS pvt\n" }, { "answer_id": 7213585, "author": "saranya", "author_id": 915293, "author_profile": "https://Stackoverflow.com/users/915293", "pm_score": 3, "selected": false, "text": "SELECT CUST, PRODUCT, QTY\nFROM Product) up\nPIVOT\n( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p\nUNPIVOT\n(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)\n) AS Unpvt\nGO\n" }, { "answer_id": 10857177, "author": "mxasim", "author_id": 581836, "author_profile": "https://Stackoverflow.com/users/581836", "pm_score": 6, "selected": false, "text": "CREATE TABLE dbo.tbl (\n action VARCHAR(20) NOT NULL,\n view_edit VARCHAR(20) NOT NULL\n);\n\nINSERT INTO dbo.tbl (action, view_edit)\nVALUES ('Action1', 'VIEW'),\n ('Action1', 'EDIT'),\n ('Action2', 'VIEW'),\n ('Action3', 'VIEW'),\n ('Action3', 'EDIT');\n SELECT action, view_edit FROM dbo.tbl SELECT Action, \n[View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'),\n[Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT')\nFROM tbl t\nGROUP BY Action\n SELECT [Action], [View], [Edit] FROM\n(SELECT [Action], view_edit FROM tbl) AS t1 \nPIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2\n" }, { "answer_id": 20688536, "author": "Vishwanath Dalvi", "author_id": 435559, "author_profile": "https://Stackoverflow.com/users/435559", "pm_score": 3, "selected": false, "text": "With pivot_data as\n(\nselect \naction, -- grouping column\nview_edit -- spreading column\nfrom tbl\n)\nselect action, [view], [edit]\nfrom pivot_data\npivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p;\n" }, { "answer_id": 54918063, "author": "1994Nerd", "author_id": 11081348, "author_profile": "https://Stackoverflow.com/users/11081348", "pm_score": 0, "selected": false, "text": "PIVOT(\n min(value)\n FOR ColTitle in([F4], [UR], [UQ])\n )\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2626/" ]
24,495
<p>I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.</p> <p>I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.</p> <p>How do I code this. I tried something like that in the template file:</p> <pre><code>#if($car != null) #ssubmit("name=view" "value=View Car") #else #ssubmit("name=new" "value=Choose Car") #end </code></pre> <p>But I keep getting error about Null value in the <em>#if</em> line. </p> <p>I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.</p> <p>And Velocity + Struts tutorials are difficult to find or have good information.</p> <p>Thanks</p>
[ { "answer_id": 24510, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 4, "selected": true, "text": "#if($car)\n" }, { "answer_id": 64065, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 2, "selected": false, "text": "#if( $car == $null ) $car #if( $car && $car != false )" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
24,515
<p>Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="noreferrer">found this</a> one, and it's a start, but nothing more.</p> <p>Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) </p> <p>The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. </p> <p>Thanks for any help.</p>
[ { "answer_id": 24615, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 6, "selected": true, "text": "<?php\n\n/**\n * @author [email protected]\n **/\n\nif($_GET['act'] == 'do')\n {\n $pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]';\n $pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]';\n $pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])';\n $pattern['d'] = '/[d]/'; $replace['d'] = '[d D]';\n $pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]';\n $pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])';\n $pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]';\n $pattern['h'] = '/[h]/'; $replace['h'] = '[h H]';\n $pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]';\n $pattern['j'] = '/[j]/'; $replace['j'] = '[j J]';\n $pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])';\n $pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]';\n $pattern['m'] = '/[m]/'; $replace['m'] = '[m M]';\n $pattern['n'] = '/[n]/'; $replace['n'] = '[n N]';\n $pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]';\n $pattern['p'] = '/[p]/'; $replace['p'] = '[p P]';\n $pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]';\n $pattern['r'] = '/[r]/'; $replace['r'] = '[r R]';\n $pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]';\n $pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]';\n $pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]';\n $pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]';\n $pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]';\n $pattern['x'] = '/[x]/'; $replace['x'] = '[x X]';\n $pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]';\n $pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]';\n $word = str_split(strtolower($_POST['word']));\n $i=0;\n while($i < count($word))\n {\n if(!is_numeric($word[$i]))\n {\n if($word[$i] != ' ' || count($word[$i]) < '1')\n {\n $word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]);\n }\n }\n $i++;\n }\n //$word = \"/\" . implode('', $word) . \"/\";\n echo implode('', $word);\n }\n\nif($_GET['act'] == 'list')\n {\n $link = mysql_connect('localhost', 'username', 'password', '1');\n mysql_select_db('peoples');\n $sql = \"SELECT word FROM filters\";\n $result = mysql_query($sql, $link);\n $i=0;\n while($i < mysql_num_rows($result))\n {\n echo mysql_result($result, $i, 'word') . \"<br />\";\n $i++;\n }\n echo '<hr>';\n }\n?>\n<html>\n <head>\n <title>RegEx Generator</title>\n </head>\n <body>\n <form action='badword.php?act=do' method='post'>\n Word: <input type='text' name='word' /><br />\n <input type='submit' value='Generate' />\n </form>\n <a href=\"badword.php?act=list\">List Words</a>\n </body>\n</html>\n" }, { "answer_id": 11801638, "author": "Tony", "author_id": 48615, "author_profile": "https://Stackoverflow.com/users/48615", "pm_score": 3, "selected": false, "text": "http://www.wdyl.com/profanity?q=naughtyword\n\n{\nresponse: \"false\"\n}\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178/" ]
24,516
<p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p> <pre><code>%token &lt;int&gt; INT %token &lt;string&gt; ID %token MINUS %start expr %type &lt;expr&gt; expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; </code></pre> <p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>
[ { "answer_id": 24589, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 4, "selected": true, "text": "expr simple_expr expr_with_prefix simple_expr (expr_with_prefix) a(b(c)) (a(b))(c) applied_expression (applied_expression) expr := INT\n | parenthesized_expr\n | expr MINUS expr\n\nparenthesized_expr := ( expr )\n | ( applied_expr )\n | ( expr_with_prefix )\n\napplied_expr := expr expr\n\nexpr_with_prefix := MINUS expr\n" }, { "answer_id": 7678584, "author": "Chris Dodd", "author_id": 16406, "author_profile": "https://Stackoverflow.com/users/16406", "pm_score": 0, "selected": false, "text": "expr MINUS expr MINUS expr a-b" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891/" ]