qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
117,312
|
<p>I work with a bunch of sets in order to generate constrained random traffic, but I want to be able to call a Specman macro that computes the complement of a set with syntax like:</p>
<pre><code>COMPLEMENT begin
domain=[0..10,24..30],
complementing_set=[2..3,27..30]
end
</code></pre>
<p>and have it generate:</p>
<pre><code>[0..1,4..10,24..26]
</code></pre>
<p>Every time I need the complement of a set I'm using fully populated lists (e.g. {0;1;2;3....} ) and then removing elements, instead of using Specman's built-in int_range_list object. And I'm also doing a lot of these set calculations at run-time instead of compile-time.</p>
|
[
{
"answer_id": 146590,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "var domain: list of int = {0..10, 24..30}; \nvar complementing_set: list of int = {2..3, 27..30};\nvar complement: list of int = domain.all(it in complementing set);\n all"
},
{
"answer_id": 10928047,
"author": "guy",
"author_id": 1441644,
"author_profile": "https://Stackoverflow.com/users/1441644",
"pm_score": 1,
"selected": false,
"text": "domain : uint(bits:500);\ncomplement : uint(bits:500);\nset : uint(bits:500) = domain & ~complement;\n set_l : list of uint = set[.]].all_indices(it==1);\n"
},
{
"answer_id": 22993713,
"author": "Yuri Tsoglin",
"author_id": 3518556,
"author_profile": "https://Stackoverflow.com/users/3518556",
"pm_score": 2,
"selected": false,
"text": "set var s1: set = [1..5, 10..15];\nvar s2: set = [4..13];\nvar s3: set = s1.intersect(s2);\n x: int;\ny: int;\n........\nvar s1: set = [x..y];\nvar s2: set = [1..10];\nvar s3: set = s1.union(s2);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20712/"
] |
117,337
|
<p>Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt) </p>
|
[
{
"answer_id": 117376,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 8,
"selected": true,
"text": "C:\\src\\2\\Merlin\\Main>tfpt unshelve /?\ntfpt unshelve - Unshelve into workspace with pending changes\n\nAllows a shelveset to be unshelved into a workspace with pending changes.\nMerges content between local and shelved changes. Allows migration of shelved\nchanges from one branch into another by rewriting server paths.\n\nUsage: tfpt unshelve [shelvesetname[;username]] [/nobackup]\n [/migrate /source:serverpath /target:serverpath]\n\n shelvesetname The name of the shelveset to unshelve\n /nobackup Skip the creation of a backup shelveset\n /migrate Rewrite the server paths of the shelved items\n (for example to unshelve into another branch)\n /source:serverpath Source location for path rewrite (supply with /migrate)\n /target:serverpath Target location for path rewrite (supply with /migrate)\n /nobackup Skip the creation of a backup shelveset\n >tfpt unshelve \"Shelve Set Name\";domain\\userName /migrate /source:\"$/Project/Branch1/\" /target:\"$/Project/Branch2/\"\n"
},
{
"answer_id": 5428836,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 5,
"selected": false,
"text": "C:\\temp\\shelveset-name c:\\temp\\shelveset-name"
},
{
"answer_id": 50260445,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 0,
"selected": false,
"text": "cd [your !!source!! branch root]\ntfpt unshelve /migrate /source:\"$/MyCollection/Development/Maint1.1\" /target:\"$/MyCollection/Development/Maint1.2\" \"myShelveset;UserName\"\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
] |
117,346
|
<p>I'm working on a C++ application that needs detailed timing information, down to the millisecond level. </p>
<p>We intend to gather the time to second accuracy using the standard <code>time()</code> function in <code><ctime></code>. We would like to additionally gather the milliseconds elapsed since the last second given by <code>time()</code>. </p>
<p>Does anyone know a convenient method for obtaining this information? </p>
|
[
{
"answer_id": 117381,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 0,
"selected": false,
"text": "(c)time.h"
},
{
"answer_id": 117432,
"author": "Justin Rudd",
"author_id": 12968,
"author_profile": "https://Stackoverflow.com/users/12968",
"pm_score": 4,
"selected": false,
"text": "int number_of_tenths = 5;\n//create a resolution independent count -- divide by 10 since there are \n//10 tenths in a second. \nint count = number_of_tenths*(time_duration::ticks_per_second()/10);\ntime_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings\n"
},
{
"answer_id": 117564,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "#include < stdio.h > // stackoverflow bug: pre tag eats the filenames,\n#include < stdint.h > // so i had to put spaces in the angle brackets\n\ninline uint64_t rdtsc() {\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\");\n return (uint64_t)hi << 32 | lo;\n}\n\nmain()\n{\n unsigned long long x;\n unsigned long long y;\n x = rdtsc();\n printf(\"%lld\\n\",x);\n y = rdtsc();\n printf(\"%lld\\n\",y);\n printf(\"it took this long to call printf: %lld\\n\",y-x);\n}\n"
},
{
"answer_id": 117728,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 2,
"selected": false,
"text": "int gettimeofday(struct timeval *tv, struct timezone *tz);\n\nstruct timeval {\n time_t tv_sec; /* seconds */\n suseconds_t tv_usec; /* microseconds */\n};\n"
},
{
"answer_id": 117899,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#include <ctime>\n\nclock_t elapsed = static_cast<double>(clock() / CLOCKS_PER_SEC);\n"
},
{
"answer_id": 122199,
"author": "Mathieu Pagé",
"author_id": 5861,
"author_profile": "https://Stackoverflow.com/users/5861",
"pm_score": 2,
"selected": false,
"text": "#if defined(_MSC_VER)\n# define NOMINMAX // workaround un bug dans windows.h qui define des macros\n // \"min\" et \"max\" qui entrent en conflit avec la STL.\n# include <windows.h>\n#else\n# include <sys/time.h>\n#endif\n\nnamespace Utils\n{\n\n /**\n * Implémente un chronométre qui mesure le temps etre deux appels.\n */\n class CTimer\n {\n private:\n# if defined(_MSC_VER)\n LARGE_INTEGER m_depart;\n# else\n timeval m_depart;\n# endif\n\n public:\n /**\n * Démarre le timer.\n * \n * Cette fonction sert à démarrer le timer. Si le timer est déja\n * démarrer, elle le redémarre simplement.\n */\n inline void start()\n {\n# if defined(_MSC_VER)\n QueryPerformanceCounter(&m_depart);\n# else\n gettimeofday(&m_depart, 0);\n# endif\n\n };\n\n /**\n * Retourne le nombre de secondes depuis le départ du timer.\n * \n * @return Nombre de secondes écoulés depuis le départ du timer\n */\n inline float GetSecondes() const\n {\n# if defined(_MSC_VER)\n LARGE_INTEGER now;\n LARGE_INTEGER freq;\n\n QueryPerformanceCounter(&now);\n QueryPerformanceFrequency(&freq);\n\n return (now.QuadPart - m_depart.QuadPart) / static_cast<float>(freq.QuadPart);\n# else\n timeval now;\n gettimeofday(&now, 0);\n\n return now.tv_sec - m_depart.tv_sec + (now.tv_usec - m_depart.tv_usec) / 1000000.0f;\n# endif\n };\n };\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20716/"
] |
117,348
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/506368/how-do-i-serialize-an-enum-value-as-an-int">How do I serialize an enum value as an int?</a> </p>
</blockquote>
<p>Hi, all!</p>
<p>I'm wondering if there's a way to force the serialization of an enum value into its integer value, instead of its string representation.</p>
<p>To put you into context:
We're using, in a web application that heavily relies on web services, a single baseclass for all our request headers, independantly of the type of request. </p>
<p>I want to add a Result field to the header, so we'll have a place to pass hints back to the calling app as to how the operation went on the web service side. We already have an enum declared to that effect, but since we have legacy apps that call on those web services that may not know about those enums, I'd like to send serialize those values as integers.</p>
<p>We've already had to cut down on the length of those headers by using the [XmlElement(ElementName = "string representationOfAttributeName")] because we occasionally exceeded IE maximum url length, and I wondered whether there's a similar Attributes to force the serialization of enum values into integers.</p>
<p>Anyone ever heard of such an attribute?</p>
<p>As ever, thanks for the help,
Pascal</p>
|
[
{
"answer_id": 117374,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 4,
"selected": true,
"text": "[XmlIgnore]\npublic MyThing MyThing { get; set; }\n\n[XmlElement(\"MyThing\")]\n[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]\npublic string MyThingForSerialization\n{\n get { return //convert MyThing to string; }\n set { MyThing = //convert string to MyThing; }\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3403/"
] |
117,352
|
<p>I have this C-code to do multiplications over GF(8):</p>
<pre><code>int32_t GaloisMultiply (int32_t a, int32_t b)
{
int32_t i;
int32_t mask = 0x100;
int32_t y = 0;
for(i=0;i<8;i++)
{
if(b & mask)
{
y ^= a;
}
mask >>= 1;
y <<= 1;
}
if(b & 0x1)
{
y ^= a;
}
return(y);
}
</code></pre>
<p>That's more or less the text-book implementation.</p>
<p>I wonder if I there is a clever optimization for above algorithm if I can assert that a is always b, e.g. I do squaring instead of multiplication. I'm not after a cryptographic use btw. I just want to make use of the fact that x*x in GF(8) interleaves the bits of x with zero bits one by one.</p>
<p>There are already quite clever methods to do the bit interleaving, but since I've found out that x*x in GF(8) does the bit interleaving thing (by accident) I can't stop trying to use it for bit-interleaving optimizations.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 117473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "int32_t GaloisMultiply( int32_t a ) \n{\n int32_t y = 0;\n int32_t b = a & 0x01ff;\n\n while ( b ) \n {\n if ( b & 1 ) \n y ^= a;\n\n a <<= 1;\n b >>= 1;\n }\n return y;\n}\n int32_t GaloisMultiply( int32_t a ) \n{\n int32_t y = 0;\n for ( int32_t b = a & 0x01ff; b; b >>= 1 )\n {\n if ( b & 1 ) \n y ^= a;\n\n a <<= 1;\n }\n return y;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
] |
117,355
|
<p>I'm trying to find the most reusable, yet elegant, piece of code possible for determining if an IEnumerable. In the ideal, this should be a function I can call absolutely any time I need to tell if an IEnumerable is empty.</p>
<p>While I have developed an answer for .NET 3.5 that has worked well for me so far, my current thought is that there is no perfect answer, since an IEnumerable can technically encapsulate a collection (or queue of iterators) that modifies the underlying results as it iterates, which would cause problems. However, this would also be an impediment to implementing IEnumerable.Count(), and that didn't stop MS from providing it.</p>
<p>So I thought I'd put it to SO to see if someone has a better one, and in case someone else should find it useful.</p>
<p><strong>Edit:</strong> Wow, I can't believe I didn't know about IEnumerable.Any. I knew it existed, but never bothered to check what it did. Let this be a lesson. Read the documentation. Just because a method name doesn't imply it does what you want, doesn't mean it doesn't do what you want.</p>
|
[
{
"answer_id": 117367,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 6,
"selected": true,
"text": "!enumerable.Any()\n IEnumerable"
},
{
"answer_id": 117480,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "IEnumerator e;\ntry\n{\n e = enumerable.GetEnumerator();\n return e.MoveNext();\n}\nfinally\n{ \n if (e is IDisposable)\n e.Dispose();\n}\n using (IEnumerator<T> e = enumerable.GetEnumerator())\n{\n return e.MoveNext();\n}\n"
},
{
"answer_id": 117507,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "foreach"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729/"
] |
117,356
|
<p>I've currently got multiple select's on a page that are added dynamically with <code>ajax</code> calls using jquery.</p>
<p>The problem I've had is I could not get the change event to work on the added select unless I use the <code>onchange</code> inside the tag e.g. </p>
<pre><code><select id="Size" size="1" onchange="onChange(this);">
</code></pre>
<p>This works, but I'm wondering if there's a way to get it to be assigned by jquery. I've tried using <code>$('select').change(onChange($(this));</code> in the usual place of <code>$(document).ready</code> but that didn't work.</p>
<p>I've tried adding the event with bind after the ajax call but that did not work either.</p>
<p>Any better way to assign the event?</p>
|
[
{
"answer_id": 117392,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 3,
"selected": false,
"text": "$('select').change(onChange);\n"
},
{
"answer_id": 117404,
"author": "Gilean",
"author_id": 6305,
"author_profile": "https://Stackoverflow.com/users/6305",
"pm_score": 3,
"selected": true,
"text": "$('p').click( function() { alert('blah'); } ) \n $('p').click( function() { alert('blah'); } )\n"
},
{
"answer_id": 117925,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 0,
"selected": false,
"text": "$('#newSelect').change(\n function() \n { \n onChange(this)\n }\n);\n $('.classname').unbind(\"change\");\n$('.classname').change(\n function() \n { \n onChange(this)\n }\n);\n"
},
{
"answer_id": 119776,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " $(this).load('ploc002.php', {JobNumber: JobNumber, Edit: this.id}, function()\n {\n // The DOM has been changed by the AJAX call\n // Now we need to reassign the onchange events\n $('select,input').change( function()\n {\n onChange(this)\n });\n });\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,361
|
<p>I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using jQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to.</p>
<p>In more detail, say I have a "class" as follows:</p>
<pre><code>function Car(owner) {
this.owner = owner;
}
Car.prototype = {
drive: function() {
alert("Driving "+this.owner+"s car!");
}
}
</code></pre>
<p>And an instance:</p>
<pre><code>var myCar = new Car("Bob");
</code></pre>
<p>I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class".</p>
<p>Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods".</p>
<pre><code>function createHandler( obj, method ) {
return function( event ) {
return obj[method](event||window.event);
}
}
</code></pre>
<p>I've used it as follows:</p>
<pre><code>document.getElementById("myButton")
.addEventListener("click", createHandler(myCar,"drive"));
</code></pre>
<p>How do I accomplish something like this with JQuery? </p>
<p>I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.</p>
|
[
{
"answer_id": 117456,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 3,
"selected": true,
"text": "$(\"#myButton\").click(function() { myCar.drive(); });\n"
},
{
"answer_id": 33007772,
"author": "Ben Bozorg",
"author_id": 4728122,
"author_profile": "https://Stackoverflow.com/users/4728122",
"pm_score": 0,
"selected": false,
"text": "$(\"#myButton\").each(function() {\n\nvar $btn = $(this);\n\n $btn.on('click',function(){\n\n // Do whatever you want.\n\n });\n});\n $(\".myButton\").each(...\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2105/"
] |
117,372
|
<p>I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this:</p>
<pre><code>$MimeType = new MimeType();
$mimetype = $MimeType->getType($filename);
$basename = basename($filename);
header("Content-type: $mimetype");
header("Content-Disposition: attachment; filename=\"$basename\"");
header('Content-Length: '. filesize($filename));
if ( @readfile($filename)===false ) {
header("HTTP/1.0 500 Internal Server Error");
loadErrorPage('500');
}
</code></pre>
<p>Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any <code>utf-8 characters</code>(and the $filename has not any utf-8 characteres neither).</p>
|
[
{
"answer_id": 117428,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 3,
"selected": true,
"text": "session_start();"
},
{
"answer_id": 117613,
"author": "levhita",
"author_id": 7946,
"author_profile": "https://Stackoverflow.com/users/7946",
"pm_score": 3,
"selected": false,
"text": "header('Pragma: public');\nheader('Cache-Control: max-age=0');\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7946/"
] |
117,378
|
<p><strong>The situation</strong><br>
I have a Git repo and an SVN repo that both hold the same source code but different commit histories. The Git repo has a lot of small well commented submits... while the SVN repo has a few huge commits with comments like "Lots of stuff".
Both series of commits follow the same changes made in the code and are roughly equivalent.</p>
<p><strong>The desired outcome</strong><br>
I would like to switch to using Git-SVN <em>without</em> losing the detailed history from the current Git repo. This should be done by 'grafting' the history from the Git repo onto an SVN branch of the project (branched from the point I really started using Git).</p>
<p><strong>Why would you do that? (history)</strong><br>
A while ago I started to play with Git. I started by setting up a Git repo in a project I had under SVN control. With a little config, I had both Git and SVN working in parallel on the same source code.</p>
<p>This was a great way for me to learn and play with Git, while still having the safety net of SVN. It was a sandbox with real data basically. I didn't have the time to really <em>learn</em> Git but I really wanted to tinker with it. This was actually a pretty good way to learn Git for me.</p>
<p>At first, after doing some edits, I would commit to SVN and then to Git... then play with Git knowing my changes were safely in SVN. Soon I was committing more frequently to Git than SVN... Now, SVN commits have fallen to an annoying chore I have to do sometimes.</p>
<p>When learning the difference between <code>git revert</code> and <code>svn revert</code> I was <em>VERY</em> glad I had been checking in to the SVN repo. I almost lost a few weeks' work assuming that the two worked the same.</p>
<p>I now know the glories of Git-SVN and I am using it happily on several other projects.
I fully realized when I started that I might lose my Git repo and have to setup a new one 'properly' using <code>git-svn init</code>... but having played with Git for a while now, I'm sure there is some way of hacking the Git history into SVN.</p>
|
[
{
"answer_id": 117593,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 2,
"selected": false,
"text": "git-svn clone path/to/your/svn/repo\ngit-commit -a -m 'my small change'\nvi some files to change.txt\ngit-commit -a -m 'another small change' \ngit-svn dcommit # sends your little changes as individual svn commits\n"
},
{
"answer_id": 137168,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "rm .svn\n(configure git-svn '/myproject/branch/git-remerge')\ngit svn sync_versions --svn_revision=123 --hash=ad346f221455\ngit svn dcommit\n mkdir ../svn_proxy\ncd ../svn_proxy\ngit svn init\ngit checkout hash_of_svn_branch_point\ngit pull ../messy_repo\n"
},
{
"answer_id": 144170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "git-svn set-tree git branch svn-reconsile HASH_OF_SECOND_COMMIT\ngit checkout -f svn-reconsile\n\ngit svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_SECOND_COMMIT\n\ngit rebase git-svn\n\ngit merge master\n\ngit svn dcommit\n git svn dcommit master git svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_MOST_RECENT_COMMIT\n\ngit rebase git-svn\n --no-squash"
},
{
"answer_id": 3552739,
"author": "Simon Ruggier",
"author_id": 428978,
"author_profile": "https://Stackoverflow.com/users/428978",
"pm_score": 0,
"selected": false,
"text": "git remote add old-repo <path-to-old-repo>\ngit fetch old-repo\n# to browse and figure out the hashes, if that helps\ngitk --all &\n\n# for each branch you want to graft\ngit rebase --onto <new git svn branch base> <old-repo branch base> <old-repo branch tip>\n\n# when done\ngit remote rm old-repo\n"
},
{
"answer_id": 5319123,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 0,
"selected": false,
"text": "filter-branch"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,379
|
<p>I'm successfully using VBScript within WScript to remotely read and write IIS configurations from the server. When I attempt to run these same scripts from my desk box they fail, though. Example:</p>
<pre><code>Dim vdir
Set vdir = GetObject("IIS://servername/w3svc/226/root")
</code></pre>
<p>Error = "Invalid syntax"</p>
<p>The code works perfectly when run from one IIS server to another, but I'd like to run it from my XP Workstation. It would seem reasonable that there's a download of ADSI available that will make things work from my desktop, but I cannot find one. I downloaded <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&displaylang=en" rel="nofollow noreferrer">ADAM</a> but that only got me a small portion of the functionality I need. </p>
<p>Any hints out there? Thank you. </p>
|
[
{
"answer_id": 117593,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 2,
"selected": false,
"text": "git-svn clone path/to/your/svn/repo\ngit-commit -a -m 'my small change'\nvi some files to change.txt\ngit-commit -a -m 'another small change' \ngit-svn dcommit # sends your little changes as individual svn commits\n"
},
{
"answer_id": 137168,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "rm .svn\n(configure git-svn '/myproject/branch/git-remerge')\ngit svn sync_versions --svn_revision=123 --hash=ad346f221455\ngit svn dcommit\n mkdir ../svn_proxy\ncd ../svn_proxy\ngit svn init\ngit checkout hash_of_svn_branch_point\ngit pull ../messy_repo\n"
},
{
"answer_id": 144170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "git-svn set-tree git branch svn-reconsile HASH_OF_SECOND_COMMIT\ngit checkout -f svn-reconsile\n\ngit svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_SECOND_COMMIT\n\ngit rebase git-svn\n\ngit merge master\n\ngit svn dcommit\n git svn dcommit master git svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_MOST_RECENT_COMMIT\n\ngit rebase git-svn\n --no-squash"
},
{
"answer_id": 3552739,
"author": "Simon Ruggier",
"author_id": 428978,
"author_profile": "https://Stackoverflow.com/users/428978",
"pm_score": 0,
"selected": false,
"text": "git remote add old-repo <path-to-old-repo>\ngit fetch old-repo\n# to browse and figure out the hashes, if that helps\ngitk --all &\n\n# for each branch you want to graft\ngit rebase --onto <new git svn branch base> <old-repo branch base> <old-repo branch tip>\n\n# when done\ngit remote rm old-repo\n"
},
{
"answer_id": 5319123,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 0,
"selected": false,
"text": "filter-branch"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127/"
] |
117,407
|
<ul>
<li>You can use App.config; but it only supports key/value pairs.</li>
<li>You can use .Net configuration, configuration sections; but it can be really complex.</li>
<li>You can use Xml Serialization/Deserialization by yourself; your classes-your way.</li>
<li>You can use some other method; what can they be? ...</li>
</ul>
<p>Which of these or other methods (if there are) do you prefer? Why?</p>
|
[
{
"answer_id": 117597,
"author": "JohnIdol",
"author_id": 1311500,
"author_profile": "https://Stackoverflow.com/users/1311500",
"pm_score": 5,
"selected": true,
"text": " public class CustomSection : ConfigurationSection\n {\n [ConfigurationProperty(\"LastName\", IsRequired = true,\n DefaultValue = \"TEST\")]\n public String LastName\n {\n get { return (String)base[\"LastName\"]; }\n set { base[\"LastName\"] = value; }\n }\n\n [ConfigurationProperty(\"FirstName\", IsRequired = true, DefaultValue =\n \"TEST\")]\n public String FirstName\n {\n get { return (String)base[\"FirstName\"]; }\n set { base[\"FirstName\"] = value; }\n }\n\n public CustomSection()\n {\n\n }\n }\n // Create a custom section.\n static void CreateSection()\n {\n try\n {\n\n CustomSection customSection;\n\n // Get the current configuration file.\n System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@\"ConfigurationTest.exe\");\n\n // Create the section entry \n // in the <configSections> and the \n // related target section in <configuration>.\n if (config.Sections[\"CustomSection\"] == null)\n {\n customSection = new CustomSection();\n config.Sections.Add(\"CustomSection\", customSection);\n customSection.SectionInformation.ForceSave = true;\n config.Save(ConfigurationSaveMode.Full);\n }\n }\n catch (ConfigurationErrorsException err)\n {\n //manage exception - give feedback or whatever\n }\n\n }\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <configSections>\n <section name=\"CustomSection\" type=\"ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" allowLocation=\"true\" allowDefinition=\"Everywhere\" allowExeDefinition=\"MachineToApplication\" overrideModeDefault=\"Allow\" restartOnExternalChanges=\"true\" requirePermission=\"true\" />\n </configSections>\n <CustomSection LastName=\"TEST\" FirstName=\"TEST\" />\n</configuration>\n CustomSection section = (CustomSection)ConfigurationManager.GetSection(\"CustomSection\");\n string lastName = section.LastName;\n string firstName = section.FirstName;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
] |
117,415
|
<p>The subversion concept of branching appears to be focused on creating an [un]stable fork of the entire repository on which to do development. Is there a mechanism for creating branches of individual files?</p>
<p>For a use case, think of a common header (*.h) file that has multiple platform-specific source (*.c) implementations. This type of branch is a permanent one. All of these branches would see ongoing development with occasional cross-branch merging. This is in sharp contrast to unstable development/stable release branches which generally have a finite lifespan.</p>
<p>I <strong>do not</strong> want to branch the entire repository (cheap or not) as it would create an unreasonable amount of maintenance to continuously merge between the trunk and all the branches. At present I'm using ClearCase, which has a different concept of branching that makes this easy. I've been asked to consider transitioning to SVN but this paradigm difference is important. I'm much more concerned about being able to easily create alternate versions for individual files than about things like cutting a stable release branch.</p>
|
[
{
"answer_id": 117442,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 1,
"selected": false,
"text": "svn copy myfile.c myfile_branch.c\n"
},
{
"answer_id": 117500,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 3,
"selected": false,
"text": "branches_files"
},
{
"answer_id": 117585,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 3,
"selected": true,
"text": "svn cp $REP/trunk/file.h $REP/branched_files/file.h\nsvn co $REP/trunk\nsvn switch $REP/branched_files/file.h file.h\n svn st\n S file.h\n"
},
{
"answer_id": 117633,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 1,
"selected": false,
"text": "// foo.h:\nvoid Foo();\n\n// foo_win32.c\n#ifdef _WIN32\nvoid Foo()\n{\n ...\n}\n#endif\n\n// foo_linux.c\n#ifdef _GNUC\nvoid Foo()\n{\n ...\n}\n#endif\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8233/"
] |
117,422
|
<p>My Virtual Machine's clock drifts pretty significantly. There's documentation out there about dealing with this, but nothing seems to be working very well.</p>
<p>Anyone have any suggestions, things that worked well for them, ...</p>
<p>Supposedly updating regularly via ntp is not a good solution.</p>
|
[
{
"answer_id": 117466,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": -1,
"selected": false,
"text": "net time \\\\computer_name /set\n"
},
{
"answer_id": 15264654,
"author": "user2143026",
"author_id": 2143026,
"author_profile": "https://Stackoverflow.com/users/2143026",
"pm_score": 4,
"selected": false,
"text": "tinker panic 0\nrestrict 127.0.0.1\nrestrict default kod nomodify notrap\nserver 0.vmware.pool.ntp.org\nserver 1.vmware.pool.ntp.org\nserver 2.vmware.pool.ntp.org\ndriftfile /var/lib/ntp/drift\n 0.vmware.pool.ntp.org\n1.vmware.pool.ntp.org\n server 127.127.1.0\nfudge 127.127.1.0 stratum 10\n"
},
{
"answer_id": 32562622,
"author": "sysadmiral",
"author_id": 3411119,
"author_profile": "https://Stackoverflow.com/users/3411119",
"pm_score": 0,
"selected": false,
"text": "yum install apt-get install"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
117,426
|
<p>I am working on a project that has grown to a decent size, and I am the only developer. We currently don't use any version control, but I definitely need to start.</p>
<p>I want to use Subversion. What would be the best way to transfer an existing project to it?</p>
<p>I have a test server that I use for developing new features, then transfer those files to the 2 production servers. Is there a tool that will automate the upload to the test, then the deployment to the live servers?</p>
<p>All this is developed in ASP.NET using Visual Studio (if that matters)</p>
|
[
{
"answer_id": 117556,
"author": "Hector Sosa Jr",
"author_id": 12829,
"author_profile": "https://Stackoverflow.com/users/12829",
"pm_score": 3,
"selected": false,
"text": "svn export C:\\MyReporitosy\\Path C:\\DestinationPath\n"
},
{
"answer_id": 155053,
"author": "bill_the_loser",
"author_id": 5239,
"author_profile": "https://Stackoverflow.com/users/5239",
"pm_score": -1,
"selected": false,
"text": "hg init /path/to/repository\n hg add /folder/pattern \n\nOR\n\nhg add FILE\n hg commit\n hg pull //desktop_name/path/to/repo/ \nhg update\n"
},
{
"answer_id": 14700461,
"author": "Tom Stickel",
"author_id": 756246,
"author_profile": "https://Stackoverflow.com/users/756246",
"pm_score": 0,
"selected": false,
"text": "1) Create a New Repository (if needed, if using VisualSVN Server then very easy)\n2) Right click on the Folder of which you want to put the folders and files into your repository \n3) With having the right click menu go to TortoiseSVN\n4) Choose IMPORT \n5) Place in trunk (best practice)\n\ne.g. https://computername:8443/svn/MyCoolCode/trunk\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18234/"
] |
117,429
|
<p>What is the best way to handle large numeric inputs in C++ (for example <code>10^100</code>)? </p>
<p>For algorithms I usually switch over to ruby and I sometimes use strings.</p>
<p>Any other good methods?</p>
|
[
{
"answer_id": 250736,
"author": "Abhishek Mishra",
"author_id": 8786,
"author_profile": "https://Stackoverflow.com/users/8786",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n\nusing namespace std;\n\nstring add (string &s1, string &s2){\n int carry=0,sum,i;\n\n string min=s1,\n max=s2,\n result = \"\";\n\n if (s1.length()>s2.length()){\n max = s1;\n min = s2;\n } else {\n max = s2;\n min = s1;\n }\n\n for (i = min.length()-1; i>=0; i--){\n sum = min[i] + max[i + max.length() - min.length()] + carry - 2*'0';\n\n carry = sum/10;\n sum %=10;\n\n result = (char)(sum + '0') + result;\n }\n\n i = max.length() - min.length()-1;\n\n while (i>=0){\n sum = max[i] + carry - '0';\n carry = sum/10;\n sum%=10;\n\n result = (char)(sum + '0') + result;\n i--;\n }\n\n if (carry!=0){\n result = (char)(carry + '0') + result;\n } \n\n return result;\n}\n\nint main (){\n string a,b;\n\n cin >> a >> b;\n\n cout << add (a,b)<<endl;\n\n return 0;\n}\n"
},
{
"answer_id": 3897035,
"author": "Ashik",
"author_id": 471044,
"author_profile": "https://Stackoverflow.com/users/471044",
"pm_score": -1,
"selected": false,
"text": "atoi() itoa() strlen"
},
{
"answer_id": 20754900,
"author": "herohuyongtao",
"author_id": 2589776,
"author_profile": "https://Stackoverflow.com/users/2589776",
"pm_score": 3,
"selected": false,
"text": "vector<char> vector<char> vector<char> myDigits; // stores all digits of number\n <<, >>, +, -, *, ==, <, !=, >, etc. char array #include <iostream>\n#include <string> // for strings\n#include <vector> // for sequence of digits\nusing namespace std;\n\nclass BigInt\n{\npublic:\n BigInt(); // default constructor, value = 0\n BigInt(int); // assign an integer value\n BigInt(const string &); // assign a string\n // may need these in alternative implementation\n // BigInt(const BigInt &); // copy constructor\n // ~BigInt(); // destructor\n // const BigInt & operator = (const BigInt &);\n // assignment operator\n // operators: arithmetic, relational\n const BigInt & operator += (const BigInt &);\n const BigInt & operator -= (const BigInt &);\n const BigInt & operator *= (const BigInt &);\n const BigInt & operator *= (int num);\n string ToString() const; // convert to string\n int ToInt() const; // convert to int\n double ToDouble() const; // convert to double\n // facilitate operators ==, <, << without friends\n bool Equal(const BigInt & rhs) const;\n bool LessThan(const BigInt & rhs) const;\n void Print(ostream & os) const;\nprivate:\n // other helper functions\n bool IsNegative() const; // return true iff number is negative\n bool IsPositive() const; // return true iff number is positive\n int NumDigits() const; // return # digits in number\n int GetDigit(int k) const;\n void AddSigDigit(int value);\n void ChangeDigit(int k, int value);\n void Normalize();\n // private state/instance variables\n enum Sign{positive,negative};\n Sign mySign; // is number positive or negative\n vector<char> myDigits; // stores all digits of number\n int myNumDigits; // stores # of digits of number\n};\n\n// free functions\nostream & operator <<(ostream &, const BigInt &);\nistream & operator >>(istream &, BigInt &);\nBigInt operator +(const BigInt & lhs, const BigInt & rhs);\nBigInt operator -(const BigInt & lhs, const BigInt & rhs);\nBigInt operator *(const BigInt & lhs, const BigInt & rhs);\nBigInt operator *(const BigInt & lhs, int num);\nBigInt operator *(int num, const BigInt & rhs);\nbool operator == (const BigInt & lhs, const BigInt & rhs);\nbool operator < (const BigInt & lhs, const BigInt & rhs);\nbool operator != (const BigInt & lhs, const BigInt & rhs);\nbool operator > (const BigInt & lhs, const BigInt & rhs);\nbool operator >= (const BigInt & lhs, const BigInt & rhs);\nbool operator <= (const BigInt & lhs, const BigInt & rhs);\n"
},
{
"answer_id": 68671813,
"author": "Sergei Krivonos",
"author_id": 525578,
"author_profile": "https://Stackoverflow.com/users/525578",
"pm_score": 0,
"selected": false,
"text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\nint main()\n{\n using namespace boost::multiprecision;\n\n cpp_int u = 1;\n for(unsigned i = 1; i <= 100; ++i)\n u *= i;\n\n // prints 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 (i.e. 100!)\n std::cout << u << std::endl;\n\n return 0;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20730/"
] |
117,461
|
<p>I want alwaysPositive to be assigned a positive number with all possible values for lareValue1 and largeValue2 (these are at least 1).</p>
<p>The following statement causes a buffer overflow:</p>
<pre><code>int alwaysPositive = (largeValue1 + largeValue2) / 2;
</code></pre>
<p>I know I can prevent it by substracting and adding:</p>
<pre><code>int alwaysPositive = largeValue1 + ((largeValue2 - largeValue1) / 2);
</code></pre>
<p>But in other programming languages I can use an unsigned bitshift to do the trick:</p>
<pre><code>int alwaysPositive3 = (largeValue1 + largeValue2) >>> 1;
</code></pre>
<p>How can I do this in C#?</p>
<hr>
<p>The answers below all solve the problem. There are probably lots of ways to do this, but they all (including my solutions) have one thing in common: they all look obfuscated. </p>
|
[
{
"answer_id": 117519,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 0,
"selected": false,
"text": "uint alwaysPositive = (uint)(largeValue1 + largeValue2) / 2;\n"
},
{
"answer_id": 117542,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": " x = largeValue1;\n y = largeValue2; \n return (x&y)+((x^y)/2);\n"
},
{
"answer_id": 117670,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "int alwaysPositive = (largeValue1 >> 1) + (largeValue2 >> 1) + (largeValue1 & largeValue2 & 0x01);\n int alwaysPositive = (largeValue1 >> 1) + (largeValue2 >> 1) + ((largeValue1 | largeValue2) & 0x01);\n"
},
{
"answer_id": 117808,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "try\n{\n checked { alwaysPositive3 = (largeValue1 + largeValue2); }\n}\ncatch (OverflowException ex)\n{\n // Corrective logic\n}\n"
},
{
"answer_id": 117858,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 2,
"selected": false,
"text": "unchecked((largeValue1 + largeValue2) >> 1)"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13376/"
] |
117,467
|
<p>I need to find a way to crawl one of our company's web applications and create a static site from it that can be burned to a cd and used by traveling sales people to demo the web site. The back end data store is spread across many, many systems so simply running the site on a VM on the sale person's laptop won't work. And they won't have access to the internet while at some clients (no internet, cell phone....primitive, I know).</p>
<p>Does anyone have any good recommendations for crawlers that can handle things like link cleanup, flash, a little ajax, css, etc? I know odds are slim, but I figured I'd throw the question out here before I jump into writing my own tool.</p>
|
[
{
"answer_id": 48452213,
"author": "AsTeR",
"author_id": 172277,
"author_profile": "https://Stackoverflow.com/users/172277",
"pm_score": 3,
"selected": false,
"text": "wget --mirror --convert-links --adjust-extension --page-requisites \\\n--no-parent http://example.org\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17623/"
] |
117,469
|
<p>Could anyone recommend a good BAML Decompiler / Viewer besides BAML Viewer plugin for Reflector, which doesn't handle path geometry/data?</p>
|
[
{
"answer_id": 1194143,
"author": "mark",
"author_id": 80002,
"author_profile": "https://Stackoverflow.com/users/80002",
"pm_score": 2,
"selected": false,
"text": "Ricciolo.StylesExplorer.exe Ricciolo.StylesExplorer.MarkupReflection.dll"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268/"
] |
117,471
|
<p>I have a database issue that i currently cannot wrap my head around with an easy solution. In my db I have a table that stores event values.. 0's and 1's with a timestamp. Issue being that it is possible for there to be the same event to occur twice as a business rule. Like below</p>
<ul>
<li>'2008-09-22 16:28:14.133', 0</li>
<li>'2008-09-22 16:28:35.233', 1</li>
<li>'2008-09-22 16:29:16.353', 1</li>
<li>'2008-09-22 16:31:37.273', 0</li>
<li>'2008-09-22 16:35:43.134', 0</li>
<li>'2008-09-22 16:36:39.633', 1</li>
<li>'2008-09-22 16:41:40.733', 0</li>
</ul>
<p>in real life these events are cycled and I’m trying to query over to get the cycles of these but I need to ignore the duplicate values ( 1,1 ) the current solution is using a SQL cursor to loop each and throw out the value if the previous was the same. I’ve considered using a trigger on the insert to clean up in a post processed table but I can’t think of an easy solution to do this set based.</p>
<p>Any ideas or suggestions?</p>
<p>Thanks</p>
|
[
{
"answer_id": 117587,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "SELECT timestamp, value\nFROM yourtable\n SELECT T1.timestamp, MIN(T2.timestamp) AS next_timestamp, T1.value\nFROM yourtable T1, yourtable T2\nWHERE T2.timestamp > T1.timestamp\nGROUP BY T1.timestamp, T1.value\n SELECT T3.timestamp, T3.value\nFROM (\n SELECT T1.timestamp, MIN(T2.timestamp) AS next_timestamp, T1.value\n FROM yourtable T1, yourtable T2\n WHERE T2.timestamp > T1.timestamp\n GROUP BY T1.timestamp, T1.value\n) T3, yourtable AS T4\nWHERE T3.next_timestamp = T4.timestamp\n AND T3.value <> T4.value\n BEGIN TRANSACTION;\nCREATE TABLE yourtable (timestamp datetime, value int);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:28:14.133',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:28:35.233',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:29:16.353',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:31:37.273',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:35:43.134',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:36:39.633',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:41:40.733',0);\nINSERT INTO \"yourtable\" VALUES('2099-12-31 23:59:59.999',2);\nCOMMIT;\n timestamp value\n2008-09-22 16:28:14.133 0\n2008-09-22 16:29:16.353 1\n2008-09-22 16:35:43.134 0\n2008-09-22 16:36:39.633 1\n2008-09-22 16:41:40.733 0\n"
},
{
"answer_id": 117681,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": true,
"text": ";WITH Firsts AS (\n SELECT t1.dt\n ,MIN(t2.dt) AS Prevdt\n FROM t AS t1\n INNER JOIN t AS t2\n ON t1.dt < t2.dt\n AND t2.cyclestate <> t1.cyclestate\n GROUP BY t1.dt\n)\nSELECT MIN(t1.dt) AS dt_start\n ,t2.dt AS dt_end\nFROM t AS t1\nINNER JOIN Firsts\n ON t1.dt = Firsts.dt\nINNER JOIN t AS t2\n ON t2.dt = Firsts.Prevdt\n AND t1.cyclestate <> t2.cyclestate\nGROUP BY t2.dt\n ,t2.cyclestate\nHAVING MIN(t1.cyclestate) = 0\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20737/"
] |
117,474
|
<p>From time to time, I need to dump USB traffic under Windows, mostly to support hardware under Linux, so my primary goal is to produce dump files for protocol analysis.</p>
<p>For USB traffic, it seems that <a href="https://web.archive.org/web/20151218000528/http://www.pcausa.com/Utilities/UsbSnoop/default.htm" rel="noreferrer">SniffUsb</a> is the clear winner... It works under Windows XP (but <em>not</em> later) and has a much nicer GUI than earlier versions. It produces <em>huge</em> dump files, but everything is there.</p>
<p>However, my device is in fact a USB serial device, so I turned to <a href="http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx" rel="noreferrer">Portmon</a> which can sniff serial port traffic without the USB overhead.</p>
|
[
{
"answer_id": 57109540,
"author": "Renat",
"author_id": 1075282,
"author_profile": "https://Stackoverflow.com/users/1075282",
"pm_score": 2,
"selected": false,
"text": "Device and Log File"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1081/"
] |
117,477
|
<p>A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only.</p>
<p>Unfortunately I lost the name of the library and was unable to Google it. Anyone any ideas?</p>
<p><strong>Edit:</strong> reStructuredText aka rst == docutils. That's not what I'm looking for :)</p>
|
[
{
"answer_id": 117819,
"author": "sean lynch",
"author_id": 14232,
"author_profile": "https://Stackoverflow.com/users/14232",
"pm_score": 1,
"selected": false,
"text": "python markdown.py input_file.txt > output_file.html\n import markdown\nhtml = markdown.markdown(your_text_string)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19990/"
] |
117,481
|
<p>At work I'm using Perl 5.8.0 on Windows.</p>
<p>When I first put Perl on, I went to CPAN, downloaded all the sources, made a few changes (in the .MAK file(?) to support threads, or things like that), and did <code>nmake</code> / <code>nmake test</code> / <code>nmake install</code>. Then, bit by bit, I've downloaded individual modules from CPAN and done the nmake dance.</p>
<p>So, I'd like to upgrade to a more recent version, but the new one must not break any existing scripts. Notably, a bunch of "use" modules that I've installed must be installed in the new version.</p>
<p>What's the most reliable (and easiest) way to update my current version, ensuring that everything I've done with the nmake dance will still be there after updating?</p>
|
[
{
"answer_id": 117577,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "perl -le \"print for @INC\"\n"
},
{
"answer_id": 117938,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": true,
"text": "configure cpan -a"
},
{
"answer_id": 118430,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 1,
"selected": false,
"text": "perl -c"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8763/"
] |
117,484
|
<p>Just a small SVN "problem" here.</p>
<p>I setup my own SVN server <a href="https://blog.codinghorror.com/setting-up-subversion-on-windows/" rel="nofollow noreferrer">Setting up Subversion on Windows</a></p>
<p>Now I made a rep in which all my projects will go.</p>
<p>Now, I checked the rep out in a folder called "Projects".</p>
<p>Now If I make a project and check it in, that project is revision 1. If I make a second project, and check it in, that Project is at revision 2. Thus, if I make a change to Project 1, that project will then be at Revision 3.</p>
<p>What I would really want is for each project to have its own revision scheme. How do I do this? </p>
|
[
{
"answer_id": 117617,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "svnserve -r /path/to/repository \n\nsvn://hostname/ \n svnserve -r /path/to/directory/containing/many/repositories \n\nsvn://hostname/repositoryname/ \n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,512
|
<p>Given a simple (id, description) table t1, such as</p>
<pre><code>id description
-- -----------
1 Alice
2 Bob
3 Carol
4 David
5 Erica
6 Fred
</code></pre>
<p>And a parent-child relationship table t2, such as</p>
<pre><code>parent child
------ -----
1 2
1 3
4 5
5 6
</code></pre>
<p>Oracle offers a way of traversing this as a tree with some custom syntax extensions:</p>
<pre><code>select parent, child, sys_connect_by_path(child, '/') as "path"
from t2
connect by prior parent = child
</code></pre>
<p>The exact syntax is not important, and I've probably made a mistake in the above. The
important thing is that the above will produce something that looks like</p>
<pre><code>parent child path
------ ----- ----
1 2 /1/2
1 3 /1/3
4 5 /4/5
4 6 /4/5/6
5 6 /5/6
</code></pre>
<p>My question is this: is it possible to join another table within the sys_connect_by_path(), such as the t1 table above, to produce something like:</p>
<pre><code>parent child path
------ ----- ----
1 2 /Alice/Bob
1 3 /Alice/Carol
... and so on...
</code></pre>
|
[
{
"answer_id": 117596,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "SELECT parent, child, parents.description||sys_connect_by_path(childs.description, '/') AS \"path\"\nFROM T1 parents, T1 childs, T2\nWHERE T2.parent = parents.id\nAND T2.child = childs.id\nCONNECT BY PRIOR parent = child\n"
},
{
"answer_id": 119726,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 3,
"selected": false,
"text": "select\n T.PARENT\n ,T.CHILD\n ,sys_connect_by_path(T.CDESC, '/')\nfrom\n (\n select\n t2.parent as PARENT\n ,t2.child as CHILD\n ,t1.description as CDESC\n from\n t1, t2\n where\n t2.child = t1.id\n ) T\nwhere\n level > 1 and connect_by_isleaf = 1\nconnect by prior\n T.CHILD = T.PARENT\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18625/"
] |
117,514
|
<p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p>
<pre><code>import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utfoffset(self, dt):
return timedelta(hours=1)
def myDateHandler(aDateString):
"""u'Sat, 6 Sep 2008 21:16:33 EDT'"""
_my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
month = [
'JAN', 'FEB', 'MAR',
'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP',
'OCT', 'NOV', 'DEC'
].index(month.upper()) + 1
dt = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
# dt = dt - datetime.timedelta(hours=1)
# dt = dt - dt.tzinfo.utfoffset(myTimeZone())
return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)
def main():
print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"answer_id": 117615,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": false,
"text": "babel pytz"
},
{
"answer_id": 1893437,
"author": "Carlos H Romano",
"author_id": 268789,
"author_profile": "https://Stackoverflow.com/users/268789",
"pm_score": 3,
"selected": false,
"text": ">>> import time\n>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone\n>>> offset / 60 / 60 * -1\n-9\n * -1 localtime().tm_isdst"
},
{
"answer_id": 65087160,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 2,
"selected": false,
"text": "from datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\nUTC = datetime(2012,11,10,9,0,0, tzinfo=timezone.utc)\n\n# convert to another tz with \"astimezone\":\neastern = UTC.astimezone(ZoneInfo(\"US/Eastern\"))\n\n# note that it is safe to use \"replace\",\n# to get the same wall time in a different tz:\npacific = eastern.replace(tzinfo=ZoneInfo(\"US/Pacific\"))\n\nprint(UTC.isoformat())\nprint(eastern.isoformat())\nprint(pacific.isoformat())\n\n# 2012-11-10T09:00:00+00:00\n# 2012-11-10T04:00:00-05:00\n# 2012-11-10T04:00:00-08:00\n pip install tzdata"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9338/"
] |
117,536
|
<p>I've tried restarting apache and the cached pages still appear, so there must be a folder someplace. I don't have a 'public/cache', so what other places should I look? Is there a URL flag that could trigger this effect as well?</p>
|
[
{
"answer_id": 118951,
"author": "johnp",
"author_id": 19837,
"author_profile": "https://Stackoverflow.com/users/19837",
"pm_score": 4,
"selected": true,
"text": "touch /webapps/mycook/tmp/restart.txt\n"
},
{
"answer_id": 48336423,
"author": "Arman Petrosyan",
"author_id": 2195130,
"author_profile": "https://Stackoverflow.com/users/2195130",
"pm_score": 0,
"selected": false,
"text": "passenger-config restart-app\n passenger-config restart-app /Users/phusion/testapp\n touch tmp/restart.txt\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13320/"
] |
117,547
|
<p>Documentation can be found <a href="http://github.com/madrobby/scriptaculous/wikis/droppables" rel="nofollow noreferrer">here</a></p>
<p>It says in the example:</p>
<p><strong>onDrop:
Called whenever a Draggable is released over the Droppable and the Droppable is accepts it. The callback gets three parameters: the Draggable element, the Droppable element and the Event. You can extract additional information about the drop – like if the Ctrl or Shift keys were pressed – from the Event object.</strong></p>
<p>Then it gives some code</p>
<p>Droppables.add('shopping_cart', {
accept: 'products',
onDrop: function(element) {
$('shopping_cart_text').update('Dropped the ' + element.alt + ' on me.');
}
});</p>
<p>It uses the ambiguous word 'element' in the code. <strong>My question is, does anyone have a good example on how to reference the draggable element and the droppable element in this callback javascript function?</strong></p>
|
[
{
"answer_id": 117583,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 3,
"selected": true,
"text": "onDrop: function() { $('droppable_demo').highlight(); }\n onDrop: function(dragged, dropped, event) { }\n"
},
{
"answer_id": 1429302,
"author": "Mark",
"author_id": 45175,
"author_profile": "https://Stackoverflow.com/users/45175",
"pm_score": 0,
"selected": false,
"text": " Droppables.add('shopping_cart', {\n accept: 'products',\n onDrop: function(dragged, dropped, event) {\n alert('Dragged: ' + dragged.id);\n alert('Dropped onto: ' + dropped.id);\n alert('Held ctrl key: ' + event.ctrlKey);\n }\n});\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,551
|
<p>My website makes a lot of requests. I often need to cancel all current requests, so that the browser is not blocking relevant new requests.</p>
<p>I have 3 kinds of requests:</p>
<ul>
<li>Ajax</li>
<li>inserted script-tags (which do JSONP-Communication)</li>
<li>inserted image-tags (which cause the browser to request data from various servers)</li>
</ul>
<p>For Ajax its no problem as the XMLHttpRequest object supports canceling.
What I need is a way to make any browser stop loading resources, from DOM-Objects.</p>
<p>Looks like simply removing an object (eg. an image-tag) from the DOM only helps avoiding an request, if the request is not already running.</p>
<p><strong>UPDATE:</strong> a way to cancel all requests, which are irrelevant, instead of really any request would be perfect. </p>
|
[
{
"answer_id": 117565,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "document.close()"
},
{
"answer_id": 117628,
"author": "toohool",
"author_id": 14334,
"author_profile": "https://Stackoverflow.com/users/14334",
"pm_score": 7,
"selected": true,
"text": "window.stop()"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20711/"
] |
117,558
|
<p>I am re-designing an application for a ASP.NET CMS that I really don't like. I have made som improvements in performance only to discover that not only does this CMS use MS SQL but some users "simply" use MS Access database.</p>
<p>The problem is that I have some tables which I inner join, that with the MS Access version are in two different files. I am not allowed to simply move the tables to the other mdb file.</p>
<p>I am now trying to figure out a good way to "inner join" across multiple access db files?</p>
<p>It would really be a pity if I have fetch all the data and the do it programmatically!</p>
<p>Thanks</p>
|
[
{
"answer_id": 118234,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 4,
"selected": false,
"text": "SELECT MyTable.*\nFROM MyTable IN 'c:\\MyDBs\\Access.mdb'\n SELECT OtherTable.*\nFROM OtherTable IN 'c:\\MyDBs\\Other.mdb'\n SELECT MyTable.ID, OtherTable.OtherField\nFROM [c:\\MyDBs\\Access.mdb].MyTable \n INNER JOIN [c:\\MyDBs\\Other.mdb].OtherTable ON MyTable.ID = OtherTable.ID\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032/"
] |
117,570
|
<p>On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can retrieve few results at a time, but then sorting won't really work well. What's the best practice to display sortable tables that might contain lots of data? </p>
<hr>
<p>Thanks for all the advises. I will certainly going over these.</p>
<p>We are using an existing Javascript framework that has the sortable table; "lots" of results means hundreds. The problem is that our users are at some remote site and a lot of delay is the network time to send/receive data from the data center. Sorting the data at the database side and only send one page worth of results at a time is nice; but when the user clicks some column header, another round trip is done, which always add 3-4 seconds. </p>
<p>Well, I guess that might be the network team's problem :)</p>
|
[
{
"answer_id": 118683,
"author": "Leo Moore",
"author_id": 6336,
"author_profile": "https://Stackoverflow.com/users/6336",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE GetProductsInCategory\n(@CategoryID INT,\n@DescriptionLength INT,\n@PageNumber INT,\n@ProductsPerPage INT,\n@HowManyProducts INT OUTPUT)\nAS\n\n-- declare a new TABLE variable\nDECLARE @Products TABLE\n(RowNumber INT,\n ProductID INT,\n Name VARCHAR(50),\n Description VARCHAR(5000),\n Price MONEY,\n Image1FileName VARCHAR(50),\n Image2FileName VARCHAR(50),\n OnDepartmentPromotion BIT,\n OnCatalogPromotion BIT)\n\n-- populate the table variable with the complete list of products\nINSERT INTO @Products\nSELECT ROW_NUMBER() OVER (ORDER BY Product.ProductID),\n Product.ProductID, Name, \n SUBSTRING(Description, 1, @DescriptionLength) + '...' AS Description,\n Price, Image1FileName, Image2FileName, OnDepartmentPromotion, OnCatalogPromotion\nFROM Product INNER JOIN ProductCategory\n ON Product.ProductID = ProductCategory.ProductID\nWHERE ProductCategory.CategoryID = @CategoryID\n\n-- return the total number of products using an OUTPUT variable\nSELECT @HowManyProducts = COUNT(ProductID) FROM @Products\n\n-- extract the requested page of products\nSELECT ProductID, Name, Description, Price, Image1FileName,\n Image2FileName, OnDepartmentPromotion, OnCatalogPromotion\nFROM @Products\nWHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage\n AND RowNumber <= @PageNumber * @ProductsPerPage\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460/"
] |
117,589
|
<p>When we are developing new sites or testing changes in new ones that involve css after the new code is committed and someone goes to check the changes they always see a cached version of the old css. This is causing a lot of problems in testing because people never are sure if they have the latest css on screen (I know shift and clicking refresh clears this cache but I can't expect end users to know to do this). What are my possible solutions?</p>
|
[
{
"answer_id": 117622,
"author": "Michael Cox",
"author_id": 372698,
"author_profile": "https://Stackoverflow.com/users/372698",
"pm_score": 2,
"selected": false,
"text": " <link href=\"/css/global.css?id=3939\" type=\"text/css\" rel=\"stylesheet\" />\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
] |
117,590
|
<p>Does anyone have a good guide to capabilities of Windows Services under XP? In particular, I am trying to find out what happens when a program being run as a service tries to open windows, but hasn't been given permission to interact with the desktop.</p>
<p>Basically, I have a program that is/was a GUI application, that should be able to run as a service for long term background processing. Rewriting the program to not display the GUI elements when doing background processing is a major effort, so I'd like to see if there is just a way to ignore the UI elements. It is sort of working now, as long as too many windows aren't opened. I'm trying to figure out what limits I might be running into. Ideally, there would be an MSDN page that discusses this, but I've had no luck finding one yet.</p>
|
[
{
"answer_id": 117605,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 2,
"selected": false,
"text": "Control Panel --> Administrative Tools"
},
{
"answer_id": 117692,
"author": "Max Caceres",
"author_id": 4842,
"author_profile": "https://Stackoverflow.com/users/4842",
"pm_score": 1,
"selected": false,
"text": "hWinstation = OpenWindowStation(\"winsta0\", FALSE, MAXIMUM_ALLOWED);\nSetProcessWindowStation(hWinstation);\nhDesktop = OpenDesktop(\"default\", 0, FALSE, MAXIMUM_ALLOWED);\nSetThreadDesktop(hDesk);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7909/"
] |
117,623
|
<p>Backstory: I'm using <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">log4net</a> to handle all logging for a project I'm working on. One particular method can be called under several different circumstances -- some that warrant the log messages to be errors and others that warrant the log messages to be warnings.</p>
<p>So, as an example, how could I turn</p>
<pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer)
If (B - A) > 5 Then
log.ErrorFormat("Difference ({0}) is outside of acceptable range.", (B - A))
End If
End Sub
</code></pre>
<p>Into something more along the lines of:</p>
<pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here")
If (B - A) > 5 Then
**delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A))
End If
End Sub
</code></pre>
<p>So that I could call it and pass either log.ErrorFormat or log.WarnFormat as the delegate?</p>
<p>I'm using VB.NET with VS 2008 and .NET 3.5 SP1. Also, I'm fairly new to delegates in general, so if this question should be worded differently to remove any ambiguities, let me know.</p>
<p>EDIT: Also, how could I initialize the delegate to either the ErrorFormat or the WarnFormat in the class constructor? Would it be as easy as <code>myDelegate = log.ErrorFormat</code>? I would imagine there is more to it than that (pardon my ignorance on the subject -- delegates are really something I want to learn more about, but so far they have eluded my understanding).</p>
|
[
{
"answer_id": 117646,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 0,
"selected": false,
"text": "Public Delegate errorCall(ByVal error As String, Params objs As Objects())\nCheckDifference(10, 0, AddressOf log.ErrorFormat)\n"
},
{
"answer_id": 117653,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 1,
"selected": false,
"text": "Private Delegate Sub LogErrorDelegate(txt as string, byval paramarray fields() as string)\n Private _LogError\nPublic Property LogError as LogErrorDelegate\n Get \n Return _LogError\n End Get\n Set(value as LogErrorDelegate)\n _LogError = value\n End Set\nEnd Property\n Dim led as New LogErrorDelegate(AddressOf log.ErrorFormat)\n"
},
{
"answer_id": 117672,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 5,
"selected": true,
"text": "Public Delegate Sub Format(ByVal value As String)\n Public Sub CheckDifference(ByVal A As Integer, _\n ByVal B As Integer, _\n ByVal format As Format)\n If (B - A) > 5 Then\n format.Invoke(String.Format( _\n \"Difference ({0}) is outside of acceptable range.\", (B - A)))\n End If\nEnd Sub\n CheckDifference(Foo, Bar, AddressOf log.WriteWarn)\n CheckDifference(Foo, Bar, AddressOf log.WriteError)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
117,632
|
<p>What install tool can I use to create Virtual Directory on IIS? OpenSource, free or to do in C#. </p>
|
[
{
"answer_id": 132967,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 0,
"selected": false,
"text": "Set objMimeMap = GetObject(\"IIS://localhost/w3svc\")\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12514/"
] |
117,651
|
<h2>Problem</h2>
<p>Language: C# 2.0 or later</p>
<hr>
<p>I would like to register context handlers to create menues when the user right clicks certain files (in my case *.eic). What is the procedure to register, unregister (clean up) and handle events (clicks) from these menues?</p>
<p>I have a clue it's something to do with the windows registry, but considering how much stuff there is in .net, I wouldn't be surprised if there are handy methods to do this clean and easy.</p>
<p>Code snippets, website references, comments are all good. Please toss them at me.</p>
<h2>Update</h2>
<hr>
<p>Obviously there is a slight problem creating context menues in managed languages, as several users have commented. Is there any other preferred way of achieving the same behaviour, or should I spend time looking into these workarounds? I don't mind doing that at all, I'm glad people have put effort into making this possible - but I still want to know if there is a "proper/clean" way of achieving this.</p>
|
[
{
"answer_id": 611126,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 1,
"selected": false,
"text": "HKEY_CLASSES_ROOT\\.eic\\ShellEx\\ContextMenuHandlers\\MyShellExt\n (Default) -> {YOUR-COMPONENTS-CLSID}\n HKEY_CLASSES_ROOT\\CLSID\\{YOUR-COMPONENTS-CLSID}\n InprocServer32\n (Default) -> C:\\WINDOWS\\system32\\mscoree.dll\n Class -> YourImplClass\n assembly -> YourAssembly, version=..., Culture=neutral, PublicKey=...\n ...\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166173/"
] |
117,665
|
<p>I got this bad feeling about how I insert larger amounts of HTML.
Lets assume we got:</p>
<p><code>var html="<table>..<a-lot-of-other-tags />..</table>"</code></p>
<p>and I want to put this into</p>
<p><code>$("#mydiv")</code></p>
<p>previously I did something like</p>
<p><code>var html_obj = $(html);</code>
<code>$("#mydiv").append(html_obj);</code></p>
<p>Is it correct that jQuery is parsing <code>html</code> to create DOM-Objects ? Well this is what I read somewhere <strong>(UPDATE:</strong> I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?!<strong>)</strong>, so I changed my code:</p>
<p><code>$("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html);</code></p>
<p>Feels faster, is it ? And is it correct that this is equivalent to:</p>
<p><code>document.getElementById("mydiv").innerHTML += html</code> ? or is jquery doing some additional expensive stuff in the background ?</p>
<p>Would love to learn alternatives as well.</p>
|
[
{
"answer_id": 117705,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 3,
"selected": false,
"text": "document.createElement()"
},
{
"answer_id": 117988,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 6,
"selected": true,
"text": "var frag = document.createDocumentFragment();\nfrag.innerHTML = html;\n$(\"#mydiv\").append(frag);\n var frag = document.createElement('table');\nfrag.innerHTML = tableInnerHtml;\n$(\"#mydiv\").append(frag);\n"
},
{
"answer_id": 4421104,
"author": "gblazex",
"author_id": 378024,
"author_profile": "https://Stackoverflow.com/users/378024",
"pm_score": 5,
"selected": false,
"text": "$(\"#mydiv\").append(html);\n innerHTML <table>"
},
{
"answer_id": 6301746,
"author": "Robert Hurst",
"author_id": 243568,
"author_profile": "https://Stackoverflow.com/users/243568",
"pm_score": 2,
"selected": false,
"text": "//Returns a new Buffer object\nfunction Buffer() {\n\n //the framgment\n var domFragment = document.createDocumentFragment();\n\n //Adds a node to the dom fragment\n function add(node) {\n domFragment.appendChild(node);\n }\n\n //Flushes the buffer to a node\n function flush(targetNode) {\n\n //if the target node is not given then use the body\n var targetNode = targetNode || document.body;\n\n //append the domFragment to the target\n targetNode.appendChild(domFragment);\n\n }\n\n //return the buffer\n return {\n \"add\": add,\n \"flush\": flush\n }\n}\n\n\n//to make a buffer do this\nvar buffer = Buffer();\n\n//to add elements to the buffer do the following\nbuffer.add(someNode1);\n\n//continue to add elements to the buffer\nbuffer.add(someNode2);\nbuffer.add(someNode3);\nbuffer.add(someNode4);\nbuffer.add(someN...);\n\n//when you are done adding nodes flush the nodes to the containing div in the dom\nbuffer.flush(myContainerNode);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20711/"
] |
117,667
|
<p>I know this is probably the dumbest question ever, however I am a total beginner when it comes to CSS; how do you hyperlink an image on a webpage using an image which is sourced from CSS? I am trying to set the title image on my website linkable to the frontpage. Thanks!</p>
<p><strong>Edit:</strong> Just to make it clear, I'm sourcing my image <em>from CSS</em>, the CSS code for the header div is as follows:-</p>
<pre><code>#header
{
width: 1000px;
margin: 0px auto;
padding: 0px 15px 0px 15px;
border: none;
background: url(images/title.png) no-repeat bottom;
width: 1000px;
height: 100px;
}
</code></pre>
<p>I want to know how to make this <em>div</em> hyperlinked on my webpage without having to make it an anchor rather than a div.</p>
|
[
{
"answer_id": 117675,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "<a href=\"index.html\"><img src=\"foo\" class=\"whatever\" alt=\"foo alt\" /></a>\n <a href=\"index.html\"><img id=\"header\" alt=\"foo alt\" /></a>\n"
},
{
"answer_id": 117680,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 2,
"selected": false,
"text": "<div id=\"header\" onclick=\"window.location='http://google.com';\">My Header</div>\n cursor: pointer;"
},
{
"answer_id": 117695,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 4,
"selected": false,
"text": "<a id=\"header\" href=\"[your link]\">Logo</a> a#header {\n background-image: url(...);\n display: block;\n width: ..;\n height: ...;\n}\n div <a> <a> <a> <a> <div> <div> Document.getElementById(\"header\").onclick = function() {\n window.location='...'; \n}\n"
},
{
"answer_id": 117697,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 0,
"selected": false,
"text": "<a href=\"\">"
},
{
"answer_id": 117699,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 2,
"selected": false,
"text": "<a href=\"linkto_title_page.html\" class=\"titleLink\"></a>\n .titleLink {\n background-image: url(imageUrl);\n}\n"
},
{
"answer_id": 117707,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 3,
"selected": false,
"text": "#header { \ndisplay:block;\n\nmargin: 0px auto;\npadding: 0px 15px 0px 15px;\nborder: none;\nbackground: url(images/title.png) no-repeat bottom;\nwidth: 1000px;\nheight: 100px; \n} \n\n<a id=\"header\" href=\"blah.html\" class=\"linkedImage\">\n"
},
{
"answer_id": 117756,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 0,
"selected": false,
"text": "<a/> <div/> $(\"div#header\").click(function() {window.location=XXXXXX;});\n"
},
{
"answer_id": 123531,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 0,
"selected": false,
"text": "<h1 id=\"title\"><a title=\"Home\" href=\"index.html>My Title</a></h1>\n<div id=\"title\"><a title=\"Home\" href=\"index.html>My Title</a></div>\n #title {\nposition:relative; /*Makes this a containing element*/\n}\n#title a {\nbackground: transparent url(../images/logo.png) no-repeat scroll 0 0;\ndisplay:block;\ntext-indent:-9999px; /*Hides the anchor text*/\nheight:50px; /*Set height and width to the exact size of your image*/\nwidth:200px;\n}\n"
},
{
"answer_id": 213581,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 0,
"selected": false,
"text": "<h1 class=\"technique-six\">\n CSS-Tricks\n</h1>\n\nh1.technique-six {\n width: 350px;\n padding: 75px 0 0 0;\n height: 0;\n background: url(\"images/header-image.jpg\") no-repeat;\n overflow: hidden;\n}\n"
},
{
"answer_id": 18246863,
"author": "Spoilsport",
"author_id": 2684875,
"author_profile": "https://Stackoverflow.com/users/2684875",
"pm_score": 2,
"selected": false,
"text": "Write in your header: [link](http://\"link here\")\n\nthen in your css:\n\n#header a[href=\"https://link here\"] {\n display: inline-block;\n width: 75px;\n height: 75px;\n font-size: 0;\n }\n .side .md a[href=\"link here\"] {\n background: url(%%picture here%%) no-repeat;\n }\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
117,690
|
<p>I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).
Currently they are presented as Future, so I need something like</p>
<pre><code>/**
* Blocks current thread until one of specified futures is done and returns it.
*/
public static <T> Future<T> waitForAny(Collection<Future<T>> futures)
throws AllFuturesFailedException
</code></pre>
<p>Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance.</p>
<p>I could try using </p>
<pre><code>new CountDownLatch(1)
</code></pre>
<p>and decrease countdown when task is complete and do </p>
<pre><code>countdown.await()
</code></pre>
<p>, but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override </p>
<pre><code><T> RunnableFuture<T> AbstractExecutorService.newTaskFor(Callable<T> callable)
</code></pre>
<p>and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures.</p>
<p>All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like </p>
<pre><code>WaitHandle.WaitAny(WaitHandle[] waitHandles)
</code></pre>
<p>in c#. Are there any well known solutions for such kind of problem?</p>
<p>UPDATE:</p>
<p>Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine.
Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.</p>
|
[
{
"answer_id": 117711,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 3,
"selected": true,
"text": "WaitHandle.WaitAny public WaitableFuture<T>\n extends Future<T>\n{\n private CountDownLatch countDownLatch;\n\n WaitableFuture(CountDownLatch countDownLatch)\n {\n super();\n\n this.countDownLatch = countDownLatch;\n }\n\n void doTask()\n {\n super.doTask();\n\n this.countDownLatch.countDown();\n }\n}\n doTask() /**\n * Extremely ugly way of implementing WaitHandle.WaitAny for Thread.Join().\n */\npublic static joinAny(Collection<Thread> threads, int numberToWaitFor)\n{\n CountDownLatch countDownLatch = new CountDownLatch(numberToWaitFor);\n\n foreach(Thread thread in threads)\n {\n (new Thread(new JoinThreadHelper(thread, countDownLatch))).start();\n }\n\n countDownLatch.await();\n}\n\nclass JoinThreadHelper\n implements Runnable\n{\n Thread thread;\n CountDownLatch countDownLatch;\n\n JoinThreadHelper(Thread thread, CountDownLatch countDownLatch)\n {\n this.thread = thread;\n this.countDownLatch = countDownLatch;\n }\n\n void run()\n {\n this.thread.join();\n this.countDownLatch.countDown();\n }\n}\n"
},
{
"answer_id": 118158,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 3,
"selected": false,
"text": "package com.javadude.sample;\n\npublic class Lock {}\n package com.javadude.sample;\n\npublic class Worker extends Thread {\n private Lock lock_;\n private long timeToSleep_;\n private String name_;\n public Worker(Lock lock, String name, long timeToSleep) {\n lock_ = lock;\n timeToSleep_ = timeToSleep;\n name_ = name;\n }\n @Override\n public void run() {\n // do real work -- using a sleep here to simulate work\n try {\n sleep(timeToSleep_);\n } catch (InterruptedException e) {\n interrupt();\n }\n System.out.println(name_ + \" is done... notifying\");\n // notify whoever is waiting, in this case, the client\n synchronized (lock_) {\n lock_.notify();\n }\n }\n}\n package com.javadude.sample;\n\npublic class Client {\n public static void main(String[] args) {\n Lock lock = new Lock();\n Worker worker1 = new Worker(lock, \"worker1\", 15000);\n Worker worker2 = new Worker(lock, \"worker2\", 10000);\n Worker worker3 = new Worker(lock, \"worker3\", 5000);\n Worker worker4 = new Worker(lock, \"worker4\", 20000);\n\n boolean started = false;\n int numNotifies = 0;\n while (true) {\n synchronized (lock) {\n try {\n if (!started) {\n // need to do the start here so we grab the lock, just\n // in case one of the threads is fast -- if we had done the\n // starts outside the synchronized block, a fast thread could\n // get to its notification *before* the client is waiting for it\n worker1.start();\n worker2.start();\n worker3.start();\n worker4.start();\n started = true;\n }\n lock.wait();\n } catch (InterruptedException e) {\n break;\n }\n numNotifies++;\n if (numNotifies == 4) {\n break;\n }\n System.out.println(\"Notified!\");\n }\n }\n System.out.println(\"Everyone has notified me... I'm done\");\n }\n}\n"
},
{
"answer_id": 423759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "public class WaitForAnyRedux {\n\nprivate static final int POOL_SIZE = 10;\n\npublic static <T> T waitForAny(Collection<T> collection) throws InterruptedException, ExecutionException {\n\n List<Callable<T>> callables = new ArrayList<Callable<T>>();\n for (final T t : collection) {\n Callable<T> callable = Executors.callable(new Thread() {\n\n @Override\n public void run() {\n synchronized (t) {\n try {\n t.wait();\n } catch (InterruptedException e) {\n }\n }\n }\n }, t);\n callables.add(callable);\n }\n\n BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(POOL_SIZE);\n ExecutorService executorService = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0, TimeUnit.SECONDS, queue);\n return executorService.invokeAny(callables);\n}\n\nstatic public void main(String[] args) throws InterruptedException, ExecutionException {\n\n final List<Integer> integers = new ArrayList<Integer>();\n for (int i = 0; i < POOL_SIZE; i++) {\n integers.add(i);\n }\n\n (new Thread() {\n public void run() {\n Integer notified = null;\n try {\n notified = waitForAny(integers);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n System.out.println(\"notified=\" + notified);\n }\n\n }).start();\n\n\n synchronized (integers) {\n integers.wait(3000);\n }\n\n\n Integer randomInt = integers.get((new Random()).nextInt(POOL_SIZE));\n System.out.println(\"Waking up \" + randomInt);\n synchronized (randomInt) {\n randomInt.notify();\n }\n }\n}\n"
},
{
"answer_id": 64568687,
"author": "Alex - GlassEditor.com",
"author_id": 3179759,
"author_profile": "https://Stackoverflow.com/users/3179759",
"pm_score": 2,
"selected": false,
"text": "CompletableFuture CompletableFuture.anyOf CompletableFuture.anyOf(futures).join()\n CompletableFuture CompletableFuture.supplyAsync runAsync"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5507/"
] |
117,691
|
<p>Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:</p>
<pre><code>$numbers = array(1,3,4,5,6,8,11,12,14,15,16);
</code></pre>
<p>The ranges would be:</p>
<pre><code> 1,3-6,8,11-12,14-16
</code></pre>
|
[
{
"answer_id": 117722,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "numbers = [1,3,4,5,6,8,11,12,14,15,16];\n\ndef is_predecessor(i1, i2):\n if i1 == i2 - 1:\n return True;\n else:\n return False;\n\ndef make_range(i1, i2):\n if i1 == i2:\n return str(i1);\n else:\n return str(i1) + \"-\" + str(i2);\n\nprevious_element = None;\ncurrent_start_element = None;\n\nfor number in numbers:\n if not is_predecessor(previous_element, number):\n if current_start_element is not None:\n print make_range(current_start_element, previous_element);\n current_start_element = number;\n previous_element = number;\n\n# handle last pair\nif current_start_element is not None:\n print make_range(current_start_element, previous_element);\n 1\n3-6\n8\n11-12\n14-16\n"
},
{
"answer_id": 117723,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 5,
"selected": true,
"text": "Range Range.end Range.begin"
},
{
"answer_id": 117747,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "startRange = array[0]; \nfor(i=0;i<array.length;i++)\n{\n if (array[i + 1] - array[i] > 1)\n {\n endRange = array[i];\n pushRangeOntoArray(startRange,endRange);\n i++;\n startRange = array[i]\n // need to check for end of array here\n }\n}\n"
},
{
"answer_id": 117779,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 0,
"selected": false,
"text": "# Just in case it's not sorted...\nmy @list = sort { $a <=> $b } ( 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16 );\n\nmy $range = [ $list[0] ];\n\nfor(@list[1 .. $#list]) {\n if($_ == $range->[-1] + 1) {\n push @$range, $_;\n }\n else {\n print $#$range ? $range->[0] . '-' . $range->[-1] : $range->[0], \"\\n\";\n $range = [ $_ ];\n }\n}\n"
},
{
"answer_id": 117796,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 0,
"selected": false,
"text": "public static List<String> getRanges(int... in) {\n List<String> result = new ArrayList<String>();\n int last = -1;\n for (int i : in) {\n if (i != (last + 1)) {\n if (!result.isEmpty()) {\n addRange(result, last);\n }\n result.add(String.valueOf(i));\n } \n last = i;\n }\n addRange(result, last);\n return result;\n}\n\nprivate static void addRange(List<String> result, int last) {\n int lastPosition = result.size() - 1;\n String lastResult = result.get(lastPosition);\n if (!lastResult.equals(String.valueOf(last))) {\n result.set(lastPosition, lastResult + \"-\" + last);\n }\n}\n\npublic static void main(String[] args) {\n List<String> ranges = getRanges(1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16);\n System.out.println(ranges);\n}\n [1, 3-6, 8, 11-12, 14-16]\n"
},
{
"answer_id": 117811,
"author": "Morikal",
"author_id": 18272,
"author_profile": "https://Stackoverflow.com/users/18272",
"pm_score": 2,
"selected": false,
"text": "CL-USER> (defun print-ranges (integer-list)\n (let ((sorted-list (sort integer-list #'<)))\n (loop with buckets = ()\n with current-bucket\n for int in sorted-list\n initially (setf current-bucket (cons (first sorted-list) (first sorted-list)))\n do (cond ((= int (cdr current-bucket))) ; do nothing, this number is already in range\n ((= (1- int) (cdr current-bucket)) ; number is 1 higher--update bucket's max\n (setf (cdr current-bucket) int))\n (t\n (push current-bucket buckets)\n (setf current-bucket (cons int int)))) ; set up a new bucket\n finally (push current-bucket buckets)\n (loop for firstp = t then nil\n for bucket in (nreverse buckets) do\n (cond ((= (car bucket) (cdr bucket))\n (format t \"~:[,~;~]~D\" firstp (car bucket)))\n (t\n (format t \"~:[,~;~]~D-~D\" firstp (car bucket) (cdr bucket))))))))\nPRINT-RANGES\nCL-USER> (print-ranges (list 1 3 4 5 6 8 11 12 14 15 16))\n1,3-6,8,11-12,14-16\nNIL\nCL-USER> \n"
},
{
"answer_id": 118113,
"author": "axblount",
"author_id": 1729005,
"author_profile": "https://Stackoverflow.com/users/1729005",
"pm_score": 0,
"selected": false,
"text": "module Main where\n\nranges :: [Int] -> [[Int]]\nranges [] = []\nranges list@(x:xs) = let adj = adjacent list in\n let len = length adj in\n if length adj == 1\n then [[x]] ++ ranges xs\n else [[x,(last adj)]] ++ ranges (drop ((length adj) - 1) xs)\n where adjacent [] = []\n adjacent (x:xs) = if (xs /= []) && (x + 1) == head xs\n then [x] ++ adjacent (xs)\n else [x]\n\nmain = do putStrLn $ show $ ranges [1,2,3,4,5,6,8,11,12,14,15,16]\n\n-- Output: [[1,6],[8],[11,12],[14,16]]\n"
},
{
"answer_id": 120349,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "class Demo\n{\n private class Range\n {\n public int Begin { get; set; }\n public int End { get; set; }\n\n public override string ToString()\n {\n if (Begin == End)\n return string.Format(\"{0}\", Begin);\n else\n return string.Format(\"{0}-{1}\", Begin, End);\n }\n }\n\n static void Main(string[] args)\n {\n var list = new List<int> { 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16 };\n // list.Sort();\n var ranges = GetRangesForSortedList(list);\n\n PrintRange(ranges);\n\n Console.Read();\n }\n\n private static void PrintRange(IEnumerable<Range> ranges)\n {\n if (ranges.Count() == 0)\n return;\n\n Console.Write(\"[{0}\", ranges.First());\n\n foreach (Range range in ranges.Skip(1))\n {\n Console.Write(\", {0}\", range);\n }\n\n Console.WriteLine(\"]\");\n }\n\n private static IEnumerable<Range> GetRangesForSortedList(IList<int> sortedList)\n {\n if (sortedList.Count < 1) \n yield break;\n\n int firstItem = sortedList.First();\n Range currentRange = new Range { Begin = firstItem, End = firstItem };\n\n foreach (int item in sortedList.Skip(1))\n {\n if (item == currentRange.End + 1)\n {\n currentRange.End = item;\n }\n else\n {\n yield return currentRange;\n currentRange = new Range { Begin = item, End = item };\n }\n }\n\n yield return currentRange;\n }\n}\n"
},
{
"answer_id": 130632,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "sub to_ranges( Int *@data ){\n my @ranges;\n \n OUTER: for @data -> $item {\n for @ranges -> $range {\n # short circuit if the $item is in a range\n next OUTER if $range[0] <= $item <= $range[1];\n \n given( $item ){\n when( $range[0]-1 ){ $range[0] = $item }\n when( $range[1]+1 ){ $range[1] = $item }\n }\n }\n \n push @ranges, [$item,$item];\n }\n \n return @ranges;\n}\n"
},
{
"answer_id": 233529,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "from __future__ import print_function\n\ndef ranges(a):\n a.sort()\n i = 0\n while i < len(a):\n start = i\n while i < len(a)-1 and a[i] >= a[i+1]-1:\n i += 1\n print(a[start] if a[start] == a[i] else \"%d-%d\" % (a[start], a[i]),\n end=\",\" if i < len(a)-1 else \"\\n\")\n i += 1\n import random\nr = range(10)\nrandom.shuffle(r)\nranges(r)\nranges([1,3,4,5,6,8,11,12,14,15,16]);\nranges([])\nranges([1])\nranges([1, 2])\nranges([1, 3])\nranges([1, 3, 4])\nranges([1, 2, 4])\nranges([1, 1, 2, 4])\nranges([1, 2, 2, 4])\nranges([1, 2, 2, 3, 5, 5])\n 0-9\n1,3-6,8,11-12,14-16\n1\n1-2\n1,3\n1,3-4\n1-2,4\n1-2,4\n1-2,4\n1-3,5\n"
},
{
"answer_id": 233811,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "void ranges(int n; int a[n], int n)\n{\n qsort(a, n, sizeof(*a), intcmp);\n for (int i = 0; i < n; ++i) {\n const int start = i;\n while(i < n-1 and a[i] >= a[i+1]-1)\n ++i;\n printf(\"%d\", a[start]);\n if (a[start] != a[i])\n printf(\"-%d\", a[i]);\n if (i < n-1)\n printf(\",\");\n }\n printf(\"\\n\");\n}\n /**\n * $ gcc -std=c99 -Wall ranges.c -o ranges && ./ranges\n */\n#include <iso646.h> // and\n#include <stdio.h>\n#include <stdlib.h>\n\n#define T(args...) \\\n { \\\n int array[] = {args}; \\\n ranges(array, sizeof(array) / sizeof(*array)); \\\n }\n\nint intcmp(const void* a, const void* b)\n{\n const int *ai = a;\n const int *bi = b;\n\n if (*ai < *bi)\n return -1;\n else if (*ai > *bi)\n return 1;\n else\n return 0;\n}\n\nint main(void)\n{\n T(1,3,4,5,6,8,11,12,14,15,16);\n T();\n T(1);\n T(1, 2);\n T(3, 1);\n T(1, 3, 4);\n T(1, 2, 4);\n T(1, 1, 2, 4);\n T(1, 2, 2, 4);\n T(1, 2, 2, 3, 5, 5);\n}\n 1,3-6,8,11-12,14-16\n\n1\n1-2\n1,3\n1,3-4\n1-2,4\n1-2,4\n1-2,4\n1-3,5\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
] |
117,708
|
<p>The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called. </p>
<p>This is an elegant idiom and I like to use it, but how does it work if the derived class is a base class in itself</p>
|
[
{
"answer_id": 117760,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 4,
"selected": true,
"text": "\nclass Parent\n{\npublic:\n int foo() {return bar();} // the non-virtual public interface\nprivate\n virtual int bar();\n};\n\nclass Child : public Parent\n{\nprivate:\n virtual int bar(); // overrides Parent::bar()\n};\n\nclass Grandchild : public Child\n{\nprivate:\n virtual int bar(); // overrides Child::bar();\n};\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] |
117,732
|
<p>Take this simple <em>C# LINQ</em> query, and imagine that <code>db.Numbers</code> is an <em>SQL</em> table with one column <code>Number</code>:</p>
<pre><code>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;
</code></pre>
<p>This will run very efficiently in <em>C#</em>, because it generates an <em>SQL</em> query something like</p>
<pre><code>select Number from Numbers where Number < 5
</code></pre>
<p>What it <strong>doesn't</strong> do is select <em>all</em> the numbers from the database, and then filter them in <em>C#</em>, as it might appear to do at first.</p>
<p><em>Python</em> supports a similar syntax:</p>
<pre><code>result = [n.Number for n in Numbers if n.Number < 5]
</code></pre>
<p>But it the <code>if</code> clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as <em>LINQ</em> in <em>Python</em>? (I'm currently evaluating <em>Python</em> vs. <em>IronPython</em> vs. <em>Boo</em>, so an answer that works in any of those languages is fine.)</p>
|
[
{
"answer_id": 118350,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 3,
"selected": true,
"text": "Queryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement) \n"
},
{
"answer_id": 118496,
"author": "David Raznick",
"author_id": 20842,
"author_profile": "https://Stackoverflow.com/users/20842",
"pm_score": 3,
"selected": false,
"text": "result = [n.Number for n in db.Numbers.filter(db.Numbers.Number < 5).all()]\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42219/"
] |
117,751
|
<p>I have a web application using JPA and JTA with Spring. I would like to support both JBoss and Tomcat. When running on JBoss, I'd like to use JBoss' own TransactionManager, and when running on Tomcat, I'd like to use JOTM.</p>
<p>I have both scenarios working, but I now find that I seem to need two separate Spring configurations for the two cases. With JOTM, I need to use Spring's <code>JotmFactoryBean</code>:</p>
<pre><code><bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransaction">
<bean class="org.springframework.transaction.jta.JotmFactoryBean"/>
</property>
</bean>
</code></pre>
<p>In JBoss, though, I just need to fetch "TransactionManager" from JNDI:</p>
<pre><code><bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="resourceRef" value="true" />
<property name="jndiName" value="TransactionManager" />
<property name="expectedType"
value="javax.transaction.TransactionManager" />
</bean>
</property>
</bean>
</code></pre>
<p>Is there a way to configure this so that the appropriate TransactionManager - JBoss or JOTM - is used, without the need for two different configuration files?</p>
|
[
{
"answer_id": 117871,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\">\n <property name=\"systemPropertiesModeName\" value=\"SYSTEM_PROPERTIES_MODE_OVERRIDE\">\n <property name=\"location\" value=\"classpath:/path/to/application.properties\"/>\n</bean>\n<bean id=\"jotm\">...</bean>\n<bean id=\"jboss\">...</bean>\n<bean id=\"bean-requiring-transaction-manager\">\n <property name=\"transactionManager\" ref=\"${transaction.strategy}\"/>\n</bean>\n"
},
{
"answer_id": 263157,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 2,
"selected": false,
"text": "<tx:jta-transaction-manager/>"
},
{
"answer_id": 5080761,
"author": "Darren Bishop",
"author_id": 133330,
"author_profile": "https://Stackoverflow.com/users/133330",
"pm_score": 1,
"selected": false,
"text": "<tx:jta-transaction-manager/> <Transaction factory=\"org.objectweb.jotm.UserTransactionFactory\" jotm.timeout=\"60\" /> conf/context.xml java:comp/UserTransaction javax.transaction:jta provided"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7034/"
] |
117,755
|
<p>Here's the code I want to speed up. It's getting a value from an ADO recordset and converting it to a char*. But this is slow. Can I skip the creation of the _bstr_t?</p>
<pre><code> _variant_t var = pRs->Fields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
char* p = (const char*) (_bstr_t) var;
</code></pre>
|
[
{
"answer_id": 117780,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "USES_CONVERSION;\nchar *p=W2A(var.bstrVal);\n char *p=CW2AEX<>(var.bstrVal);\n"
},
{
"answer_id": 117781,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "USES_CONVERSION;\nchar* p = strdup(OLE2A(var.bstrVal));\n\n// ...\n\nfree(p);\n"
},
{
"answer_id": 118442,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 3,
"selected": true,
"text": "W2A (LPCSTR)(_bstr_t)"
},
{
"answer_id": 2379121,
"author": "Peter Nimmo",
"author_id": 176690,
"author_profile": "https://Stackoverflow.com/users/176690",
"pm_score": 0,
"selected": false,
"text": "_variant_t var = pRs->Fields->GetItem(i)->GetValue(); \n _variant_t vara = pRs->Collect[i]->Value;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
117,772
|
<p>I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).</p>
<p>I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:</p>
<pre><code>@media print {
.noPageBreak {
page-break-inside : avoid;
}
}
</code></pre>
|
[
{
"answer_id": 117878,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 0,
"selected": false,
"text": "<div> page-break-inside <div> @media @media display: block"
},
{
"answer_id": 117908,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 0,
"selected": false,
"text": "page-break-inside"
},
{
"answer_id": 1213479,
"author": "Stop Slandering Monica Cellio",
"author_id": 146406,
"author_profile": "https://Stackoverflow.com/users/146406",
"pm_score": 3,
"selected": false,
"text": "page-break-after:always display:none"
},
{
"answer_id": 6859968,
"author": "AJ.",
"author_id": 287151,
"author_profile": "https://Stackoverflow.com/users/287151",
"pm_score": 0,
"selected": false,
"text": "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\" />\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20762/"
] |
117,776
|
<p>I've used <a href="http://ondras.zarovi.cz/sql/" rel="nofollow noreferrer">WWW SQL Designer</a> several times to design databases for applications. I'm now in charge of working on an application with a lot of tables (100+ mysql tables) and I would love to be able to look at the relations between tables in a manner similar to what WWW SQL Designer provides. It seems that it comes with the provisions to hook up to a database and provide a diagram of its structure, but I've not yet been able to figure out exactly how one would do that. </p>
|
[
{
"answer_id": 18035488,
"author": "Mickaël",
"author_id": 2649093,
"author_profile": "https://Stackoverflow.com/users/2649093",
"pm_score": 2,
"selected": false,
"text": "function setup_import() {\n define(\"SERVER\",\"localhost\");\n define(\"USER\",\"\");\n define(\"PASSWORD\",\"\");\n define(\"DB\",\"information_schema\");\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
117,792
|
<p>I'm interested to know the best / common way of storing a <code>this</code> pointer for use in the <code>WndProc</code>. I know of several approaches, but each as I understand it have their own drawbacks. My questions are:</p>
<p>What different ways are there of producing this kind of code:</p>
<pre><code>CWindow::WndProc(UINT msg, WPARAM wParam, LPARAM)
{
this->DoSomething();
}
</code></pre>
<p>I can think of Thunks, HashMaps, Thread Local Storage and the Window User Data struct.</p>
<p>What are the pros / cons of each of these approaches?</p>
<p>Points awarded for code examples and recommendations.</p>
<p>This is purely for curiosities sake. After using MFC I've just been wondering how that works and then got to thinking about ATL etc.</p>
<p><strong>Edit:</strong> What is the earliest place I can validly use the <code>HWND</code> in the window proc? It is documented as <code>WM_NCCREATE</code> - but if you actually experiment, that's <em>not</em> the first message to be sent to a window.</p>
<p><strong>Edit:</strong> ATL uses a thunk for accessing the this pointer. MFC uses a hashtable lookup of <code>HWND</code>s.</p>
|
[
{
"answer_id": 117832,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "GetWindowLongPtr() SetWindowLongPtr() GetWindowLong() SetWindowLong() SetWindowLongPtr() WM_NCCREATE"
},
{
"answer_id": 117876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT*)lParam)->lpCreateParams);\nSetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);\n MyWindowClass *wndptr = (MyWindowClass*) GetWindowLongPtr(hwnd, GWL_USERDATA);\n wndptr->DoSomething();\n wndptr->WndProc(msg, wparam, lparam);\n"
},
{
"answer_id": 7386287,
"author": "Vishal",
"author_id": 796017,
"author_profile": "https://Stackoverflow.com/users/796017",
"pm_score": 2,
"selected": false,
"text": "GetWindowLongPtr SetWindowLongPtr GWLP_USERDATA WNDCLASS::cbWndExtra wc.cbWndExtra = sizeof(Ctrl*); GetWindowLongPtr SetWindowLongPtr nIndex 0 GWLP_USERDATA GetProp SetProp"
},
{
"answer_id": 23944337,
"author": "paulm",
"author_id": 1124744,
"author_profile": "https://Stackoverflow.com/users/1124744",
"pm_score": 0,
"selected": false,
"text": "CreateWindowEx static std::map std::map::find SetWindowLongPtr DialogBoxParam"
},
{
"answer_id": 32916389,
"author": "adigostin",
"author_id": 451036,
"author_profile": "https://Stackoverflow.com/users/451036",
"pm_score": 2,
"selected": false,
"text": "thread_local CreateWindow WindowProc this WindowProc this HWND WM_CREATE WM_NCCREATE WM_GETMINMAXINFO class Window\n{\n // ...\n static thread_local Window* _windowBeingCreated;\n static thread_local std::unordered_map<HWND, Window*> _hwndMap;\n // ...\n HWND _hwnd;\n // ...\n // all error checking omitted\n // ...\n void Create (HWND parentHWnd, UINT nID, HINSTANCE hinstance)\n {\n // ...\n _windowBeingCreated = this;\n ::CreateWindow (YourWndClassName, L\"\", WS_CHILD | WS_VISIBLE, x, y, w, h, parentHWnd, (HMENU) nID, hinstance, NULL);\n }\n\n static LRESULT CALLBACK Window::WindowProcStatic (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)\n {\n Window* _this;\n if (_windowBeingCreated != nullptr)\n {\n _hwndMap[hwnd] = _windowBeingCreated;\n _windowBeingCreated->_hwnd = hwnd;\n _this = _windowBeingCreated;\n windowBeingCreated = NULL;\n }\n else\n {\n auto existing = _hwndMap.find (hwnd);\n _this = existing->second;\n }\n\n return _this->WindowProc (msg, wparam, lparam);\n }\n\n LRESULT Window::WindowProc (UINT msg, WPARAM wparam, LPARAM lparam)\n {\n switch (msg)\n {\n // ....\n"
},
{
"answer_id": 63434487,
"author": "SuperSim135",
"author_id": 8338615,
"author_profile": "https://Stackoverflow.com/users/8338615",
"pm_score": 0,
"selected": false,
"text": "BOOL GetMessage(\nLPMSG lpMsg,\nHWND hWnd, /*A handle to the window whose messages are to be retrieved.*/\nUINT wMsgFilterMin,\nUINT wMsgFilterMax\n);\n"
},
{
"answer_id": 65876605,
"author": "dialer",
"author_id": 653473,
"author_profile": "https://Stackoverflow.com/users/653473",
"pm_score": 4,
"selected": false,
"text": "WNDPROC WNDPROC CREATESTRUCT lpParam CreateWindow[ExW] WND WNDCLASSEX.cbWndExtra RegisterWindowClassEx WND GetWindowLong[Ptr] DialogBox WNDPROC DefDlgProc cbWndExtra DLGWINDOWEXTRA DLGWINDOWEXTRA cbWndExtra WND GetWindowLongPtr GWLP_USERDATA WND GWLP_USERDATA GWLP_USERDATA GWLP_USERDATA cbWndExtra BUTTON EDIT GWLP_USERDATA GWLP_USERDATA GWLP_USERDATA GWLP_USERDATA SetProp SetProp GWLP_USERDATA SetProp GlobalAddAtom SetProp ATOM GlobalAddAtom SetProp ATOM SetProp ATOM 0xC000 0xFFFF 0xC000 GlobalAddAtom RemoveProp WM_NCDESTROY GlobalDeleteAtom SetProp SetProp GetProp SetWindowSubclass WNDPROC WNDPROC EDIT SetWindowSubclass WNDPROC WNDPROC SUBCLASSPROC SUBCLASSPROC DWORD_PTR dwRefData SetWindowSubclass SUBCLASSPROC WNDPROC WM_CREATE dwRefData WM_NCDESTROY WNDPROC SUBCLASSPROC WM_INITDIALOG DialogParamW dwRefData SetWindowSubclass WM_INITDIALOG SUBCLASSPROC dwRefData SetWindowSubclass SetProp UxSubclassInfo SetWindowSubclass WNDPROC WNDPROC MasterSubclassProc UxSubclassInfo dwRefData SUBCLASSPROC UxSubclassInfo WNDPROC WNDPROC WNDPROC WNDPROC AtlThunk HWND WNDPROC HWND SetWindowSubclass WNDPROC WNDPROC WM_NCDESTROY WNDPROC HWND WNDPROC WM_PAINT SetProp cbWndExtra DLGWINDOWEXTRA DLGWINDOWEXTRA + sizeof(void*) GetWindowLongPtrW(hDlg, DLGWINDOWEXTRA) WNDPROC DefDlgProc CS_SAVEBITS | CS_DBLCLKS DLGWINDOEXTRA GetWindowLongPtr DWLP_USER GWLP_USERDATA DLGPROC DialogBox[Param] GWLP_USERDATA"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
117,800
|
<p>For our Django App, we'd like to get an <code>AutoField</code> to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas?</p>
|
[
{
"answer_id": 118402,
"author": "AdamKG",
"author_id": 16361,
"author_profile": "https://Stackoverflow.com/users/16361",
"pm_score": 5,
"selected": true,
"text": "ALTER SEQUENCE sequence_name RESTART WITH 12345;"
},
{
"answer_id": 6388329,
"author": "Gabriel Samfira",
"author_id": 785757,
"author_profile": "https://Stackoverflow.com/users/785757",
"pm_score": 4,
"selected": false,
"text": "from django.db.models.signals import post_syncdb\nfrom project.app import models as app_models\n\ndef auto_increment_start(sender, **kwargs):\n from django.db import connection, transaction\n cursor = connection.cursor()\n cursor = cursor.execute(\"\"\"\n ALTER table app_table AUTO_INCREMENT=2000\n \"\"\")\n transaction.commit_unless_managed()\n\npost_syncdb.connect(auto_increment_start, sender=app_models)\n"
},
{
"answer_id": 15317333,
"author": "rh0dium",
"author_id": 75888,
"author_profile": "https://Stackoverflow.com/users/75888",
"pm_score": 2,
"selected": false,
"text": "def update_auto_increment(value=5000, app_label=\"xxx_data\"):\n \"\"\"Update our increments\"\"\"\n from django.db import connection, transaction, router\n models = [m for m in get_models() if m._meta.app_label == app_label]\n cursor = connection.cursor()\n for model in models:\n _router = settings.DATABASES[router.db_for_write(model)]['NAME']\n alter_str = \"ALTER table {}.{} AUTO_INCREMENT={}\".format(\n _router, model._meta.db_table, value)\n cursor.execute(alter_str)\n transaction.commit_unless_managed()\n"
},
{
"answer_id": 48491224,
"author": "Sean",
"author_id": 7837036,
"author_profile": "https://Stackoverflow.com/users/7837036",
"pm_score": 0,
"selected": false,
"text": "id_no = models.AutoField(unique=True)\nmy_highvalue_id = models.IntegerField(null=True)\n"
},
{
"answer_id": 61242337,
"author": "micshapicsha",
"author_id": 12148856,
"author_profile": "https://Stackoverflow.com/users/12148856",
"pm_score": 2,
"selected": false,
"text": "class Product(models.Model):\n id = model.AutoField(primaryKey=True) # this is a dummy PK for now\n productID = models.IntegerField(default=0)\n productName = models.TextField()\n price = models.DecimalField(max_digits=6, decimal_places=2)\n from app.models import Product\n\ndummy = {\n 'productID': 100000,\n 'productName': 'Item name',\n 'price': 5.98,\n}\n\nProducts.objects.create(**product)\n class Product(models.Model):\n productID = models.AutoField(primary_key=True)\n productName = models.TextField()\n price = models.DecimalField(max_digits=6, decimal_places=2)\n"
},
{
"answer_id": 68626978,
"author": "Michael",
"author_id": 6815671,
"author_profile": "https://Stackoverflow.com/users/6815671",
"pm_score": 0,
"selected": false,
"text": "def save(self, *args, **kwargs):\n if not User.objects.count():\n self.id = 100\n else:\n self.id = User.objects.last().id + 1\n super(User, self).save(*args, **kwargs)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9845/"
] |
117,810
|
<p>My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth?</p>
|
[
{
"answer_id": 35478577,
"author": "sambit.albus",
"author_id": 1254010,
"author_profile": "https://Stackoverflow.com/users/1254010",
"pm_score": 2,
"selected": false,
"text": "using System\nusing System.Collections.Generic\nusing System.Linq\nusing System.Web\nusing Amazon\nusing Amazon.S3\nusing Amazon.S3.Transfer\n/// \n/// Summary description for AmazonUploader\n/// \npublic class AmazonUploader\n{\n public bool sendMyFileToS3(System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)\n {\n // input explained :\n // localFilePath = we will use a file stream , instead of path\n // bucketName : the name of the bucket in S3 ,the bucket should be already created\n // subDirectoryInBucket : if this string is not empty the file will be uploaded to\n // a subdirectory with this name\n // fileNameInS3 = the file name in the S3\n // create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1\n // you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1\n // SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not\n // store your file in a different cloud storage but (i think) it differ in performance\n // depending on your location\n\n\n IAmazonS3 client = new AmazonS3Client(\"Your Access Key\", \"Your Secrete Key\", Amazon.RegionEndpoint.USWest2);\n\n // create a TransferUtility instance passing it the IAmazonS3 created in the first step\n TransferUtility utility = new TransferUtility(client);\n // making a TransferUtilityUploadRequest instance\n TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();\n\n if (subDirectoryInBucket == \"\" || subDirectoryInBucket == null)\n {\n request.BucketName = bucketName; //no subdirectory just bucket name\n }\n else\n { // subdirectory and bucket name\n request.BucketName = bucketName + @\"/\" + subDirectoryInBucket;\n }\n request.Key = fileNameInS3 ; //file name up in S3\n //request.FilePath = localFilePath; //local file name\n request.InputStream = localFilePath;\n request.CannedACL = S3CannedACL.PublicReadWrite;\n utility.Upload(request); //commensing the transfer\n\n return true; //indicate that the file was sent\n}\n}\n"
},
{
"answer_id": 66894211,
"author": "Amit Poonia",
"author_id": 12647756,
"author_profile": "https://Stackoverflow.com/users/12647756",
"pm_score": 0,
"selected": false,
"text": "using Amazon;\nusing Amazon.S3;\nusing Amazon.S3.Model;\n\n var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey); \n try`\n {\n AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);\n // simple object put\n PutObjectRequest request = new PutObjectRequest()\n {\n ContentBody = \"put your plain text here\",\n ContentType = \"text/plain\",\n BucketName = \"put your bucket name here\",\n Key = \"1\"\n //put unique key to uniquly idenitify your data\n // you can pass here any data with unique id like primary key \n //in db\n }; \n PutObjectResponse response = client.PutObject(request);\n \n }\n catch(exception ex)\n {\n //\n }\n try\n { \n var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey);\n AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);\n GetObjectRequest request = new GetObjectRequest()\n {\n BucketName = bucketName,\n Key = \"1\"// because we pass 1 as unique key while save \n //data at the s3 bucket\n };\n\n using (GetObjectResponse response = client.GetObject(request))\n {\n StreamReader reader = new \n StreamReader(response.ResponseStream);\n vccEncryptedData = reader.ReadToEnd();\n }\n }\n catch (AmazonS3Exception)\n {\n throw;\n }\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067/"
] |
117,812
|
<p>Anybody have any good FizzBuzz type questions that are not <em>the</em> FizzBuzz problem?</p>
<p>I am interviewing someone and FB is relatively well known and not that hard to memorize, so my first stop in a search for ideas is my new addiction SO.</p>
|
[
{
"answer_id": 117949,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 5,
"selected": false,
"text": "Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\n F1 = 1\nF2 = 1\nF3 = 2\nF4 = 3\nF5 = 5\nF6 = 8\nF7 = 13\nF8 = 21\nF9 = 34\nF10 = 55\nF11 = 89\nF12 = 144\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683/"
] |
117,844
|
<p>I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?</p>
|
[
{
"answer_id": 117862,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": false,
"text": "char string[] = \"1101110100110100100000\";\nchar * end;\nlong int value = strtol (string,&end,2);\n"
},
{
"answer_id": 117870,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 6,
"selected": true,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void) {\n char * ptr;\n long parsed = strtol(\"11110111\", & ptr, 2);\n printf(\"%lX\\n\", parsed);\n return EXIT_SUCCESS;\n}\n long long strtoll"
},
{
"answer_id": 118009,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 4,
"selected": false,
"text": "#include <bitset>\n#include <iostream>\n\nint main()\n{\n std::bitset<5> x(std::string(\"01011\"));\n\n std::cout << x << \":\" << x.to_ulong() << std::endl;\n}\n"
},
{
"answer_id": 119446,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 3,
"selected": false,
"text": "boost::dynamic_bitset<> x(std::string(\"01011\"));\nstd::cout << x << \":\" << x.to_ulong() << std::endl;\n"
},
{
"answer_id": 63068058,
"author": "PentiumPro200",
"author_id": 3100538,
"author_profile": "https://Stackoverflow.com/users/3100538",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <stdio.h>\n#include <string>\n\nusing namespace std;\n\nstring getBinaryString(int value, unsigned int length, bool reverse) {\n string output = string(length, '0');\n if (!reverse) {\n for (unsigned int i = 0; i < length; i++) {\n if ((value & (1 << i)) != 0) {\n output[i] = '1';\n }\n }\n }\n else {\n for (unsigned int i = 0; i < length; i++) {\n if ((value & (1 << (length - i - 1))) != 0) {\n output[i] = '1';\n }\n }\n }\n return output;\n}\n\nunsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {\n unsigned long val = 0;\n unsigned int offset = 0;\n if (lsbindex > msbindex) {\n size_t length = lsbindex - msbindex;\n for (size_t i = msbindex; i <= lsbindex; i++, offset++) {\n if (input[i] == '1') {\n val |= (1 << (length - offset));\n }\n }\n }\n else { //lsbindex < msbindex\n for (size_t i = lsbindex; i <= msbindex; i++, offset++) {\n if (input[i] == '1') {\n val |= (1 << offset);\n }\n }\n }\n return val;\n}\n\nint main() {\n int value = 23;\n cout << value << \": \" << getBinaryString(value, 5, false) << endl;\n string str = \"01011\";\n cout << str << \": \" << getInteger(str, 1, 3) << endl;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1582/"
] |
117,851
|
<p>For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9.</p>
<p>The version number is very important...</p>
|
[
{
"answer_id": 117980,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 4,
"selected": true,
"text": "/// <summary>\n/// The GetForegroundWindow function returns a handle to the foreground window.\n/// </summary>\n[DllImport(\"user32.dll\")]\nstatic extern IntPtr GetForegroundWindow();\n [DllImport(\"user32.dll\", SetLastError=true)]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] |
117,864
|
<p>I'm a total newbie, but I was writing a little program that worked on strings in C# and I noticed that if I did a few things differently, the code executed significantly faster.</p>
<p>So it had me wondering, how do you go about clocking your code's execution speed? Are there any (free)utilities? Do you go about it the old-fashioned way with a System.Timer and do it yourself?</p>
|
[
{
"answer_id": 117883,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": false,
"text": "Stopwatch Assert"
},
{
"answer_id": 35558488,
"author": "Nikusha Kalatozi",
"author_id": 5397398,
"author_profile": "https://Stackoverflow.com/users/5397398",
"pm_score": 0,
"selected": false,
"text": "class Program {\n static void Main(string[] args) {\n const int steps = 10000;\n Stopwatch sw = new Stopwatch();\n\n ArrayList list1 = new ArrayList();\n sw.Start();\n for(int i = 0; i < steps; i++) {\n list1.Add(i);\n }\n sw.Stop();\n Console.WriteLine(\"ArrayList:\\tMilliseconds = {0},\\tTicks = {1}\", sw.ElapsedMilliseconds, sw.ElapsedTicks);\n\n MyList list2 = new MyList();\n sw.Start();\n for(int i = 0; i < steps; i++) {\n list2.Add(i);\n }\n sw.Stop();\n Console.WriteLine(\"MyList: \\tMilliseconds = {0},\\tTicks = {1}\", sw.ElapsedMilliseconds, sw.ElapsedTicks);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10288/"
] |
117,900
|
<p>I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the <a href="http://livedocs.adobe.com/flex/3/html/controls_15.html" rel="nofollow noreferrer">SWFLoader Flex component</a>. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:</p>
<pre><code>swfLoader.source = ""; // Removes the external link to the SWF.
swfLoader.load(null); // Forces the loader to try to load nothing.
// Note: At this point sound from the SWF is still playing, and
// seems to still be playing in memory.
flash.media.SoundMixer.stopAll();
// Stops the sound. This works on my development machine, but not
// on the client's.
</code></pre>
<p>If the SWFs are closed (hidden) this way, eventually the program crashes.</p>
<p>Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!</p>
<p><em>Edit 1</em>: I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?</p>
|
[
{
"answer_id": 118026,
"author": "user19264",
"author_id": 19264,
"author_profile": "https://Stackoverflow.com/users/19264",
"pm_score": 1,
"selected": false,
"text": "MovieClip(event.target.content).loaderInfo.addEventListener(Event.UNLOAD, unloadMovieClipHandler);\nprivate function unloadMovieClipHandler(event:Event) : void\n{\n SoundMixer.stopAll(); \n} \n"
},
{
"answer_id": 118461,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "try {\n new LocalConnection().connect('foo');\n new LocalConnection().connect('foo');\n} catch (e:*) {}\n unloadAndStop\n"
},
{
"answer_id": 118640,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 0,
"selected": false,
"text": "\nvar loader:Loader = new Loader();\nvar request:URLRequest = new URLRequest('test.swf');\nloader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoad, false, 0, true);\n\nfunction onSwfLoad(e:Event):void\n{\n addChild(loader);\n loader.contentLoaderInfo.addEventListener(Event.UNLOAD, onLoaderUnload, false, 0, true);\n\nloader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onSwfLoad, false);\n}\nfunction onLoaderUnload(e:Event):void\n{\n trace('LOADER WAS SUCCESSFULLY UNLOADED.');\n}\n//Now to remove this with the click of a button, assuming the buttons name is button_mc\nbutton_mc.addEventListener(MouseEvent.MOUSE_DOWN, onButtonDown, false, 0, true);\n\n function onButtonDown(e:MouseEvent):void\n{\n loader.unload();\n loader.contentLoaderInfo.removeEventListener(Event.UNLOAD, onLoaderUnload);\n //When you want to remove things completely from memory you simply set their value to null.\n loader = null;\n button_mc.removeEventListener(MouseEvent.MOUSE_DOWN, onButtonDown);\n}\n button_mc.removeEventListener(MouseEvent.MOUSE_DOWN, onButtonDown);"
},
{
"answer_id": 224447,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 4,
"selected": true,
"text": "Loader.unload() dispose() unload()"
},
{
"answer_id": 15096611,
"author": "Yury Euceda",
"author_id": 706435,
"author_profile": "https://Stackoverflow.com/users/706435",
"pm_score": 2,
"selected": false,
"text": "swfLoader.autoLoad = false;\nswfLoader.unloadAndStop();\nswfLoader.autoLoad = true;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] |
117,931
|
<p>I'm building a fairly large website and my .htaccess is starting to feel a bit bloated, is there a way of replacing my current system of - one rule for each of the possibile number of vars that could be passed, to one catch all expression that can account for varying numbers of inputs ?</p>
<p>for example I currently have:</p>
<pre><code>RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4&$5=$6
RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4
RewriteRule ^([a-z]+)/([^/]*)$ /index.php?mode=$1&id=$2
RewriteRule ^([a-z]+)$ /index.php?mode=$1
</code></pre>
<p>the first backreference is always the <em>mode</em> and (if any more exist) the second is always <em>id</em>, thereafter any further backreferences alternate between the name of the input and its value</p>
<pre><code>http://www.example.com/search
http://www.example.com/search/3039/sort_by/name_asc/page/23
</code></pre>
<p>I would love to be able to have one expression to gracefully handle all the inputs.</p>
|
[
{
"answer_id": 117968,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 4,
"selected": true,
"text": " RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]\n $pathmap = ();\nif ($_GET[\"q\"]){\n $path = split(\"/\", $_GET[\"q\"]);\n for ($i=0; $i+1<count($path); $i++){\n $pathmap[$path[$i]] = $path[$i+1];\n $i++;\n }\n}\n"
},
{
"answer_id": 117978,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 2,
"selected": false,
"text": "RewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n $path = split('/', $_SERVER['REQUEST_URI']);\narray_shift($path); // We always have a first null value\n$mode = array_shift($path);\n http://example.com/foo/bar/baz\n"
},
{
"answer_id": 119306,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 3,
"selected": false,
"text": "RewriteCond %{QUERY_STRING} ^(.*)$\n RewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [L]\nRewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^([^/]+)/ $1.php?%1 [L]\n /mypage/param1/val1/param2/val2/param3/val3/... --->\n/mypage.php?param1=val1¶m2=val2¶m3=val3&...\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083/"
] |
117,945
|
<p>I've written a simple app in C# 2.0 using the .Net Framework 2.0 Serialport class to communicate with a controller card via COM1. </p>
<p>A problem occurred recently were the bytes returned by the Read method are incorrect. It returned the right amount of bytes, only the values were incorrect. A similar app written in Delphi still returned the correct values though. </p>
<p>I used <a href="http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx" rel="nofollow noreferrer">Portmon</a> to log the activity on the serial port of both apps, compared the two logs and there where some (apparently) minor different settings and I tried to the imitate the Delphi app as closely as possible, but to no avail.</p>
<p>So, what could affect the byte values returned by Read method ? </p>
<p>Most settings between the two apps are identical. </p>
<p>Here is a list of the lines which differed in the Portmon log :</p>
<p><strong>Delphi App :</strong></p>
<blockquote>
<p>IOCTL_SERIAL_SET_CHAR Serial0 SUCCESS <strong>EOF:dc</strong>
ERR:0 BRK:0 <strong>EVT:0</strong> XON:11 XOFF:13<br>
IOCTL_SERIAL_SET_HANDFLOW Serial0 SUCCESS Shake:0
Replace:0 <strong>XonLimit:256</strong>
<strong>XoffLimit:256</strong> IOCTL_SERIAL_SET_TIMEOUTS Serial0 SUCCESS RI:-1
<strong>RM:100</strong> RC:1000 <strong>WM:100</strong> WC:1000 IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask:
RXCHAR RXFLAG <strong>TXEMPTY</strong> CTS DSR RLSD
BRK ERR RING <strong>RX80FULL</strong></p>
</blockquote>
<p><strong>C# App :</strong></p>
<blockquote>
<p>IOCTL_SERIAL_SET_CHAR Serial0 SUCCESS <strong>EOF:1a</strong>
ERR:0 BRK:0 <strong>EVT:1a</strong> XON:11 XOFF:13
IOCTL_SERIAL_SET_HANDFLOW Serial0 SUCCESS Shake:0
Replace:0 <strong>XonLimit:1024</strong>
<strong>XoffLimit:1024</strong> IOCTL_SERIAL_SET_TIMEOUTS Serial0 SUCCESS RI:-1
<strong>RM:-1</strong> RC:1000 <strong>WM:0</strong> WC:1000 IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask:
RXCHAR RXFLAG CTS DSR RLSD BRK ERR
RING</p>
</blockquote>
<p>UPDATE:</p>
<p>The correct returned bytes were : 91, 1, 1, 3, 48, 48, 50, 69, 66, 51, 70, 55, 52, 93 (14 bytes).
The last value being a simple checksum.</p>
<p>The incorrect values returned were : 91, 241, 254, 252, 242, 146, 42, 201, 51, 70, 55, 52, 93 (13 bytes).</p>
<p>As you can see the first and the last five bytes returned correspond.</p>
<p>The ErrorReceived event indicates that a framing error occurred, which could explain the incorrect values. But the question is why would SerialPort encounter a framing error when the Delphi app apparently does not ?</p>
|
[
{
"answer_id": 120525,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "SerialPort.Encoding = Encoding.GetEncoding(\"Latin1\")\n"
},
{
"answer_id": 183455,
"author": "jakdep",
"author_id": 20101,
"author_profile": "https://Stackoverflow.com/users/20101",
"pm_score": 3,
"selected": true,
"text": "_serialPort.DtrEnable = true"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20101/"
] |
117,962
|
<p>I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.</p>
<p>For example:</p>
<pre><code> <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->
</code></pre>
<p>Please phrase your answer in the form of a SQL <code>WHERE</code>-clause, AND consider the case where the end time in the second table may be <code>NULL</code>.</p>
<p>Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.</p>
|
[
{
"answer_id": 117977,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 7,
"selected": true,
"text": "SELECT * \nFROM table1,table2 \nWHERE table2.start <= table1.end \nAND (table2.end IS NULL OR table2.end >= table1.start)\n"
},
{
"answer_id": 117999,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 1,
"selected": false,
"text": "select * from table_1 \nright join \ntable_2 on \n(\ntable_1.start between table_2.start and table_2.[end]\nor\ntable_1.[end] between table_2.start and table_2.[end]\nor\n(table_1.[end] > table_2.start and table_2.[end] is null)\n)\n"
},
{
"answer_id": 44767600,
"author": "Mike S",
"author_id": 6158286,
"author_profile": "https://Stackoverflow.com/users/6158286",
"pm_score": 2,
"selected": false,
"text": "/*\n|--------| A \\___ CondA: b.ddStart > a.ddEnd\n |=========| B / \\____ CondB: a.ddS > b.ddE\n |+++++++++| A /\n*/\n--DROP TABLE ran\ncreate table ran ( mem_nbr int, ID int, ddS date, ddE date)\ninsert ran values \n(100, 1, '2012-1-1','2012-12-30'), ----\\ ovl\n(100, 11, '2012-12-12','2012-12-24'), ----/\n(100, 2, '2012-12-31','2014-1-1'),\n(100, 3, '2014-5-1','2014-12-14') ,\n\n(220, 1, '2015-5-5','2015-12-14') , ---\\ovl\n(220, 22, '2014-4-1','2015-5-25') , ---/\n(220, 3, '2016-6-1','2016-12-16') \n\nselect DISTINCT a.mem_nbr , a.* , '-' [ ], b.dds, b.dde, b.id \nFROM ran a\njoin ran b on a.mem_nbr = b.mem_nbr -- match by mem#\n AND a.ID <> b.ID -- itself\n AND b.ddS <= a.ddE -- NOT b.ddS > a.ddE \n AND a.ddS <= b.ddE -- NOT a.ddS > b.ddE \n"
},
{
"answer_id": 61834782,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 2,
"selected": false,
"text": "<overlaps predicate> ::=\n <row value constructor 1> OVERLAPS <row value constructor 2> \n SELECT 1\nWHERE ('2020-03-01'::DATE, '2020-04-15'::DATE) OVERLAPS \n ('2020-02-01'::DATE, '2020-03-15'::DATE) \n-- 1\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
] |
117,974
|
<p>In SQL you can use </p>
<p>SELECT * FROM INFORMATION_SCHEMA.TABLES </p>
<p>etc to get information about the database structure. I need to know how to achieve the same thing for an Access database.</p>
|
[
{
"answer_id": 27436989,
"author": "Terry",
"author_id": 1034974,
"author_profile": "https://Stackoverflow.com/users/1034974",
"pm_score": 1,
"selected": false,
"text": "#include <atldb.h>\n...\n // Standard way of obtaining table node info.\n CAccessorRowset<CDynamicAccessor, CBulkRowset> pRS;\n pRS.SetRows(100);\n\n CSchemaTables<CSession>* pBogus;\n hr = session.CreateSchemaRowset(NULL, 0, NULL, IID_IRowset, 0, NULL, (IUnknown**)&pRS.m_spRowset, pBogus);\n if (FAILED(hr))\n goto lblError;\n\n hr = pRS.Bind();\n if (FAILED(hr))\n goto lblError;\n\n hr = pRS.MoveFirst();\n if (FAILED(hr))\n goto lblError;\n\n while (S_OK == hr)\n {\n wstring sTableSchema(pRS.GetWCharValue(L\"TABLE_SCHEMA\"));\n wstring sTableName(pRS.GetWCharValue(L\"TABLE_NAME\"));\n wstring sTableType(pRS.GetWCharValue(L\"TABLE_TYPE\"));\n ...\n\n hr = pRS.MoveNext(); \n }\n pRS.Close();\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403/"
] |
117,986
|
<p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
|
[
{
"answer_id": 118037,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "import sys\n\ndef log_headers(app, stream=None):\n if stream is None:\n stream = sys.stdout\n def proxy(environ, start_response):\n for key, value in environ.iteritems():\n if key.startswith('HTTP_'):\n stream.write('%s: %s\\n' % (key[5:].title().replace('_', '-'), value))\n return app(environ, start_response)\n return proxy\n"
},
{
"answer_id": 118142,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": true,
"text": "from wsgiref.util import request_uri\nimport sys\n\ndef logging_middleware(application, stream=sys.stdout):\n def _logger(environ, start_response):\n stream.write('REQUEST\\n')\n stream.write('%s %s\\n' %(\n environ['REQUEST_METHOD'],\n request_uri(environ),\n ))\n\n for name, value in environ.items():\n if name.startswith('HTTP_'):\n stream.write(' %s: %s\\n' %(\n name[5:].title().replace('_', '-'),\n value,\n ))\n stream.flush()\n def _start_response(code, headers):\n stream.write('RESPONSE\\n')\n stream.write('%s\\n' % code)\n for data in headers:\n stream.write(' %s: %s\\n' % data)\n stream.flush()\n start_response(code, headers)\n return application(environ, _start_response)\n return _logger\n def application(environ, start_response):\n start_response('200 OK', [\n ('Content-Type', 'text/html')\n ])\n return ['Hello World']\n\nif __name__ == '__main__':\n logger = logging_middleware(application)\n from wsgiref.simple_server import make_server\n httpd = make_server('', 1234, logger)\n httpd.serve_forever()\n"
},
{
"answer_id": 307547,
"author": "ianb",
"author_id": 20218,
"author_profile": "https://Stackoverflow.com/users/20218",
"pm_score": 2,
"selected": false,
"text": "import webob, sys\nclass LogHeaders(object):\n def __init__(self, app, stream=sys.stderr):\n self.app = app\n self.stream = stream\n def __call__(self, environ, start_response):\n req = webob.Request(environ)\n resp = req.get_response(self.app)\n print >> self.stream, 'Request:\\n%s\\n\\nResponse:\\n%s\\n\\n\\n' % (req, resp)\n return resp(environ, start_response)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720/"
] |
118,051
|
<p>I have a grid that is binded to a collection. For some reason that I do not know, now when I do some action in the grid, the grid doesn't update.</p>
<p>Situation : When I click a button in the grid, it increase a value that is in the same line. When I click, I can debug and see the value increment but the value doesn't change in the grid. <strong>BUT</strong> when I click the button, minimize and restore the windows, the value are updated... what do I have to do to have the value updated like it was before?</p>
<p><strong>UPDATE</strong>
This is NOT SOLVED but I accepted the best answer around here.</p>
<p>It's not solved because it works as usuall when the data is from the database but not from the cache. Objects are serialized and threw the process the event are lost. This is why I build them back and it works for what I know because I can interact with them BUT it seem that it doesn't work for the update of the grid for an unkown reason.</p>
|
[
{
"answer_id": 118438,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": true,
"text": "public string Name \n{\n get\n {\n return this._Name;\n }\n set\n {\n if (value != this._Name)\n {\n this._Name= value;\n NotifyPropertyChanged(\"Name\");\n }\n }\n}\n public event EventHandler NameChanged;\n\npublic string Name \n{\n get\n {\n return this._Name;\n }\n set\n {\n if (value != this._Name)\n {\n this._Name= value;\n if (NameChanged != null) NameChanged(this, EventArgs.Empty);\n }\n }\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
118,091
|
<p>I am trying to learn how to use MSBuild so we can use it to build our project. There's what seems to be a very big hole in the documentation, and I find the hole everywhere I look, the hole being how do you name or otherwise designate the MSBuild project file? </p>
<p>For example, the tutorial on MSBuild that can be downloaded from Microsoft goes into some detail on the contents of the build file. For example, here's a little bit of their Hello World project file.</p>
<pre><code><Project MSBuildVersion = "1.0" DefaultTargets = "Compile">
<Property appname = "HelloWorldCS"/>
<Item Type = "CSFile" Include = "consolehwcs1.cs"/>
<Target Name = "Compile">
<Task Name = "CSC" Sources = "@(CSFile)">
<OutputItem TaskParameter = "OutputAssembly" Type = "EXEFile" Include = "$(appname).exe"/>
</Task>
<Message Text="The output file is @(EXEFile)"/>
</Target>
</Project>
</code></pre>
<p>And it goes on blah, blah, blah Items blah blah blah tasks, here's how you do this and here's how you do that. Useless, completely useless. Because they never get around to saying how this xml file is supposed to be recognized by the MSBuild app. Is it supposed to be named in a particular way? Is it supposed to be placed in a particular directory? Both? Neither? </p>
<p>It isn't just the MS tutorial where they don't tell about it. I haven't been able to find it on MSDN, or on any link I can wring out of Groups.Google, either.</p>
<p>Does someone here know? I sure hope so.</p>
<blockquote>
<p><strong>Edited to add:</strong> I mistook the
.proj file included in the tutorial
to be the .csproj file and that is what
one fed to MSBuild, but it took the answer below before I saw this.
It should have been rather obvious, but I missed it.</p>
</blockquote>
|
[
{
"answer_id": 118118,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 4,
"selected": true,
"text": "msbuild.exe /?\n\nMicrosoft (R) Build Engine Version 2.0.50727.3053\n[Microsoft .NET Framework, Version 2.0.50727.3053]\nCopyright (C) Microsoft Corporation 2005. All rights reserved.\n\nSyntax: MSBuild.exe [options] [project file]\n msbuild.exe mybuildfile.xml\n"
},
{
"answer_id": 233813,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "msbuild.exe project-file-name.vcproj /t:Rebuild /p:Configuration=Release\n"
},
{
"answer_id": 7039953,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 2,
"selected": false,
"text": ".msproj"
},
{
"answer_id": 15303704,
"author": "kkahl",
"author_id": 473014,
"author_profile": "https://Stackoverflow.com/users/473014",
"pm_score": 0,
"selected": false,
"text": ".msbuildproj"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16964/"
] |
118,092
|
<p>In PHP, replace one URL with another within a string e.g. </p>
<pre><code>New post on the site <a href="http://stackoverflow.com/xyz1">http://stackoverflow.com/xyz1</a></p>
</code></pre>
<p>becomes:</p>
<pre><code>New post on the site <a href="http://yahoo.com/abc1">http://yahoo.com/abc1</a></p>
</code></pre>
<p>Must work for repeating strings as above. Appreciate this is simple but struggling!</p>
|
[
{
"answer_id": 118099,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "$text = str_replace('http://stackoverflow.com/xyz1', 'http://yahoo.com/abc1', $text);\n"
},
{
"answer_id": 118101,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 0,
"selected": false,
"text": "preg_replace('#(https?://)(www\\.)?stackoverflow.com\\b#', '\\1\\2yahoo.com', $text);\n preg_replace_callabck"
},
{
"answer_id": 118112,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "function replace_url($text, $newurl) {\n $text = preg_replace('@(https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?)@', $newurl, $text);\n return $text;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
118,096
|
<p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
|
[
{
"answer_id": 118132,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 1,
"selected": false,
"text": ">>> import re\n>>> pattern = re.compile(r'\\s*(\"[^\"]*\"|.*?)\\s*,')\n>>> def split(line):\n... return [x[1:-1] if x[:1] == x[-1:] == '\"' else x\n... for x in pattern.findall(line.rstrip(',') + ',')]\n... \n>>> split(\"foo, bar, baz\")\n['foo', 'bar', 'baz']\n>>> split('foo, bar, baz, \"blub blah\"')\n['foo', 'bar', 'baz', 'blub blah']\n"
},
{
"answer_id": 118161,
"author": "Rodrigo Queiro",
"author_id": 20330,
"author_profile": "https://Stackoverflow.com/users/20330",
"pm_score": -1,
"selected": false,
"text": "def f(s, splitifeven):\n if splitifeven & 1:\n return [s]\n return [x.strip() for x in s.split(\",\") if x.strip() != '']\n\nss = 'foo, bar, \"one, two\", three four'\n\nprint sum([f(s, sie) for sie, s in enumerate(ss.split('\"'))], [])\n"
},
{
"answer_id": 118162,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 5,
"selected": false,
"text": "import csv\nreader = csv.reader(['''foo, bar, \"one, two\", three four'''], skipinitialspace=True)\nfor r in reader:\n print r\n ['foo', 'bar', 'one, two', 'three four']\n"
},
{
"answer_id": 118187,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 6,
"selected": true,
"text": ">>> import shlex\n>>> my_splitter = shlex.shlex('''foo, bar, \"one, two\", three four''', posix=True)\n>>> my_splitter.whitespace += ','\n>>> my_splitter.whitespace_split = True\n>>> print list(my_splitter)\n['foo', 'bar', 'one, two', 'three', 'four']\n >>> my_splitter = shlex.shlex('''\"test, a\",'foo,bar\",baz',bar \\xc3\\xa4 baz''',\n posix=True) \n>>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True \n>>> print list(my_splitter)\n['test, a', 'foo,bar\",baz', 'bar \\xc3\\xa4 baz']\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
118,100
|
<p>do you use a tool? or just manually make them?</p>
|
[
{
"answer_id": 692737,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 5,
"selected": true,
"text": "http://chart.apis.google.com/chart?\nchs=600x250& // the size of the chart\nchtt=Burndown& // Title\ncht=lc& // The chart type - \"lc\" means a line chart that only needs Y values\nchdl=estimated|actual& // The two legends\nchco=FF0000,00FF00& // The colours in hex of the two lines\nchxr=0,0,30,2|1,0,40,2& // The data range for the x,y (index,min,max,interval)\nchds=0,40 // The min and max values for the data. i.e. amount of features\nchd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data\n"
},
{
"answer_id": 7290547,
"author": "hlovdal",
"author_id": 23118,
"author_profile": "https://Stackoverflow.com/users/23118",
"pm_score": 2,
"selected": false,
"text": "http://apps.vanpuffelen.net/charts/burndown.jsp?days=17,18,19,22,23,24,25,26,29,30&work=125,112,104,99,95\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
] |
118,126
|
<p>Although ASP.NET MVC seems to have all the hype these days, WebForms are still quite pervasive. How do you keep your project sane? Let's collect some tips here.</p>
|
[
{
"answer_id": 118188,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<div>"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
118,130
|
<p>I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem.</p>
<p>So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler:</p>
<pre><code>this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
</code></pre>
<p>So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo.</p>
<p>I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program.</p>
<p>Anyone have any ideas how I can fix this?</p>
<p>EDIT: More details-
I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode.</p>
<p>In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will.</p>
<p>If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden.</p>
|
[
{
"answer_id": 118159,
"author": "Paul Beesley",
"author_id": 14333,
"author_profile": "https://Stackoverflow.com/users/14333",
"pm_score": 0,
"selected": false,
"text": " Rectangle screenRect = Screen.GetBounds(this);\n this.Location = screenRect.Location;\n this.Size = screenRect.Size;\n this.BringToFront();\n"
},
{
"answer_id": 118170,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": true,
"text": "this this.Bounds = Screen.PrimaryScreen.Bounds;\nthis.TopMost = true;\n"
},
{
"answer_id": 3577991,
"author": "Ronen",
"author_id": 432171,
"author_profile": "https://Stackoverflow.com/users/432171",
"pm_score": 1,
"selected": false,
"text": "private void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.KeyCode == Keys.F11)\n if (FormBorderStyle == FormBorderStyle.None)\n {\n FormBorderStyle = FormBorderStyle.Sizable;\n WindowState = FormWindowState.Normal;\n }\n else\n {\n SuspendLayout();\n FormBorderStyle = FormBorderStyle.None;\n WindowState = FormWindowState.Maximized;\n ResumeLayout();\n }\n}\n"
},
{
"answer_id": 8868785,
"author": "mammadalius",
"author_id": 91055,
"author_profile": "https://Stackoverflow.com/users/91055",
"pm_score": 2,
"selected": false,
"text": "private void GoFullscreen(bool fullscreen)\n {\n if (fullscreen)\n {\n this.WindowState = FormWindowState.Normal;\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n this.Bounds = Screen.PrimaryScreen.Bounds;\n }\n else\n {\n this.WindowState = FormWindowState.Maximized;\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;\n }\n }\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
] |
118,143
|
<p>Not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated.</p>
|
[
{
"answer_id": 118163,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 4,
"selected": true,
"text": ">>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups()\n('127', '255', '0', '0')\n r'regex_here'"
},
{
"answer_id": 118165,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 1,
"selected": false,
"text": ">>> import re\n>>> x = re.compile(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|'\n... r'2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]'\n... r'[0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')\n>>> x.match(\"127.0.0.1\")\n<_sre.SRE_Match object at 0x5a8860>\n>>> x.match(\"127.255.0.1\")\n<_sre.SRE_Match object at 0x5a8910>\n>>> x.match(\"127.255.0.0\")\n<_sre.SRE_Match object at 0x5a8860>\n preg_match re.search re.match re.match"
},
{
"answer_id": 118181,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "def valid_ip(s):\n m = re.match(r\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$\", s)\n if m is None:\n return False\n parts = [int(m.group(1+x)) for x in range(4)]\n if max(parts) > 255:\n return False\n return True\n"
},
{
"answer_id": 118182,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 2,
"selected": false,
"text": "r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
118,144
|
<p>What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.</p>
|
[
{
"answer_id": 118169,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 7,
"selected": true,
"text": "SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n\n"
},
{
"answer_id": 118172,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table ORDER BY id DESC LIMIT n\n"
},
{
"answer_id": 11083649,
"author": "Sergey Telshevsky",
"author_id": 836646,
"author_profile": "https://Stackoverflow.com/users/836646",
"pm_score": 4,
"selected": false,
"text": "(SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5) \nORDER BY tbl.id ASC\n"
},
{
"answer_id": 27200520,
"author": "Marco",
"author_id": 4305959,
"author_profile": "https://Stackoverflow.com/users/4305959",
"pm_score": 1,
"selected": false,
"text": "select * \nfrom TableName \nwhere id > ((select max(id) from TableName)-(NumberOfRowsYouWant+1)) \norder by id desc|asc\n"
},
{
"answer_id": 35505304,
"author": "tron5",
"author_id": 2700360,
"author_profile": "https://Stackoverflow.com/users/2700360",
"pm_score": 3,
"selected": false,
"text": "SELECT whatever FROM mytable WHERE id > (SELECT max(id)-10 FROM mytable);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9076/"
] |
118,190
|
<p>I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?</p>
|
[
{
"answer_id": 118210,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 9,
"selected": true,
"text": "set define off\n 'StackOverflow &' || ' you'\n"
},
{
"answer_id": 118217,
"author": "user19387",
"author_id": 19387,
"author_profile": "https://Stackoverflow.com/users/19387",
"pm_score": 2,
"selected": false,
"text": "\\"
},
{
"answer_id": 4393005,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 5,
"selected": false,
"text": "|| Chr(38) || || '&' ||"
},
{
"answer_id": 13511214,
"author": "Cauca",
"author_id": 1451781,
"author_profile": "https://Stackoverflow.com/users/1451781",
"pm_score": 4,
"selected": false,
"text": "set escape on\n 'value_\\&_intert'"
},
{
"answer_id": 27345583,
"author": "tvCa",
"author_id": 4282156,
"author_profile": "https://Stackoverflow.com/users/4282156",
"pm_score": 3,
"selected": false,
"text": "SET DEFINE <1_CHARACTER> SQL> select '&var_ampersand #var_hash' from dual;\nEnter value for var_ampersand: a value\n\n'AVALUE#VAR_HASH'\n-----------------\na value #var_hash\n\nSQL> set define #\nSQL> r\n 1* select '&var_ampersand #var_hash' from dual\nEnter value for var_hash: another value\n\n'&VAR_AMPERSANDANOTHERVALUE'\n----------------------------\n&var_ampersand another value\n\nSQL>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
] |
118,199
|
<p>I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change?
I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global <strong>bool</strong> named <strong>dataUpdated</strong>):</p>
<p>Thread 1:</p>
<pre><code>while(1) {
if (dataUpdated)
updateScreen();
doSomethingElse();
}
</code></pre>
<p>Thread 2:</p>
<pre><code>while(1) {
if (doSomething())
dataUpdated = TRUE;
}
</code></pre>
<p>Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)?</p>
<p>PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.</p>
|
[
{
"answer_id": 118204,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "volatile int myInteger;\n"
},
{
"answer_id": 118266,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "bool _updated=false;\nboost::mutex _access;\nboost::condition _condition;\n\nbool updated()\n{\n return _updated;\n}\n\nvoid thread1()\n{\n boost::mutex::scoped_lock lock(_access);\n while (true)\n {\n boost::xtime xt;\n boost::xtime_get(&xt, boost::TIME_UTC);\n // note that the second parameter to timed_wait is a predicate function that is called - not the address of a variable to check\n if (_condition.timed_wait(lock, &updated, xt))\n updateScreen();\n doSomethingElse();\n }\n}\n\nvoid thread2()\n{\n while(true)\n {\n if (doSomething())\n _updated=true;\n }\n}\n"
},
{
"answer_id": 118296,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 1,
"selected": false,
"text": "volatile volatile"
},
{
"answer_id": 118345,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 3,
"selected": false,
"text": "volatile int myInteger;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2731698/"
] |
118,235
|
<p>I run my blog using Wordpress and all too recently became a <em>big</em> believer in SCM. I really want to put my site into subversion (that's what I'm using right now, maybe git will come later) but I can't think of the correct way to do it yet. Basically, my repository is set up currently with an 'implementation' directory and a 'resources' directory, with implementation holding what will eventually be published to the live site. I want to be able to preview my site locally without having to upload to the server for obvious reasons. However, to do this I found that I needed to actually install Wordpress locally (not just copy the remote site down to my local box). This was told to me over at Wordpress.org.</p>
<p>This brings up the problem of being able to use SCM with the install because I need to upgrade my local site every now and then but this generates inconsistencies with subversion because it can’t track what’s going on because an external system is messing with it’s repository structure. That just won’t work.</p>
<p>My initial inclination is to try to just SCM my theme information as this is really the only stuff that I ‘own’ while as everything else is really just part of my platform (no different than Apache or PHP, really). However, that’s where my understanding breaks down. How can I selectively SCM only part of that directory structure, and how can I maintain the configuration of Wordpress that I’m on?</p>
<p>Anyway, I’m sure other people have tackled this and the solution is probably applicable to many apps similar to Wordpress (Drupal, phpBB, phpMyAdmin, etc.). So, how do you do it?</p>
|
[
{
"answer_id": 118552,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 1,
"selected": false,
"text": "# svn co http://svn.automattic.com/wordpress/tags/2.6.2/ (replace the current rev here for the first check out).\n #svn sw http://svn.automattic.com/wordpress/tags/2.6.3/ (or whatever wordpress rev you're updating to)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16562/"
] |
118,241
|
<p>I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?</p>
<p>If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> and different type sizes (and all browsers for that matter).</p>
|
[
{
"answer_id": 118251,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 10,
"selected": true,
"text": "var fontSize = 12;\nvar test = document.getElementById(\"Test\");\ntest.style.fontSize = fontSize;\nvar height = (test.clientHeight + 1) + \"px\";\nvar width = (test.clientWidth + 1) + \"px\"\n\nconsole.log(height, width); #Test\n{\n position: absolute;\n visibility: hidden;\n height: auto;\n width: auto;\n white-space: nowrap; /* Thanks to Herb Caudill comment */\n} <div id=\"Test\">\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n</div>"
},
{
"answer_id": 118268,
"author": "Bryan Friedman",
"author_id": 16985,
"author_profile": "https://Stackoverflow.com/users/16985",
"pm_score": 3,
"selected": false,
"text": "<span id=\"text\">Text</span>\n\n<script>\nvar textWidth = document.getElementById(\"text\").offsetWidth;\n</script>\n"
},
{
"answer_id": 2117698,
"author": "Deepak Nadar",
"author_id": 256784,
"author_profile": "https://Stackoverflow.com/users/256784",
"pm_score": 5,
"selected": false,
"text": "(function($) {\n\n $.textMetrics = function(el) {\n\n var h = 0, w = 0;\n\n var div = document.createElement('div');\n document.body.appendChild(div);\n $(div).css({\n position: 'absolute',\n left: -1000,\n top: -1000,\n display: 'none'\n });\n\n $(div).html($(el).html());\n var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];\n $(styles).each(function() {\n var s = this.toString();\n $(div).css(s, $(el).css(s));\n });\n\n h = $(div).outerHeight();\n w = $(div).outerWidth();\n\n $(div).remove();\n\n var ret = {\n height: h,\n width: w\n };\n\n return ret;\n }\n\n})(jQuery);\n"
},
{
"answer_id": 3140086,
"author": "Techek",
"author_id": 231144,
"author_profile": "https://Stackoverflow.com/users/231144",
"pm_score": 2,
"selected": false,
"text": "div.places {\n width : 100px;\n}\ndiv.places span {\n white-space:nowrap;\n overflow:hidden;\n}\n <div class=\"places\">\n <span>This is my house</span>\n</div>\n<div class=\"places\">\n <span>And my house are your house</span>\n</div>\n<div class=\"places\">\n <span>This placename is most certainly too wide to fit</span>\n</div>\n // loops elements classed \"places\" and checks if their child \"span\" is too long to fit\n$(\".places\").each(function (index, item) {\n var obj = $(item).find(\"span\");\n if (obj.length) {\n var placename = $(obj).text();\n if ($(obj).width() > $(item).width() && placename.trim().length > 0) {\n var limit = 0;\n do {\n limit++;\n placename = placename.substring(0, placename.length - 1);\n $(obj).text(placename + \"...\");\n } while ($(obj).width() > $(item).width() && limit < 1000)\n }\n }\n});\n"
},
{
"answer_id": 4032497,
"author": "Pete",
"author_id": 488707,
"author_profile": "https://Stackoverflow.com/users/488707",
"pm_score": 5,
"selected": false,
"text": "// Handy JavaScript to measure the size taken to render the supplied text;\n// you can supply additional style information too if you have it.\n\nfunction measureText(pText, pFontSize, pStyle) {\n var lDiv = document.createElement('div');\n\n document.body.appendChild(lDiv);\n\n if (pStyle != null) {\n lDiv.style = pStyle;\n }\n lDiv.style.fontSize = \"\" + pFontSize + \"px\";\n lDiv.style.position = \"absolute\";\n lDiv.style.left = -1000;\n lDiv.style.top = -1000;\n\n lDiv.textContent = pText;\n\n var lResult = {\n width: lDiv.clientWidth,\n height: lDiv.clientHeight\n };\n\n document.body.removeChild(lDiv);\n lDiv = null;\n\n return lResult;\n}\n"
},
{
"answer_id": 5047712,
"author": "Bob Monteverde",
"author_id": 623933,
"author_profile": "https://Stackoverflow.com/users/623933",
"pm_score": 7,
"selected": false,
"text": "String.prototype.width = function(font) {\n var f = font || '12px arial',\n o = $('<div></div>')\n .text(this)\n .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})\n .appendTo($('body')),\n w = o.width();\n\n o.remove();\n\n return w;\n}\n \"a string\".width() white-space: nowrap"
},
{
"answer_id": 14291586,
"author": "rysama",
"author_id": 200363,
"author_profile": "https://Stackoverflow.com/users/200363",
"pm_score": 3,
"selected": false,
"text": "var canvas = document.createElement(\"canvas\");\nvar ctx = canvas.getContext(\"2d\");\nctx.font = \"20pt Arial\"; // This can be set programmaticly from the element's font-style if desired\nvar textWidth = ctx.measureText($(\"#myElement\").text()).width;\n"
},
{
"answer_id": 14411323,
"author": "Jason Bracey",
"author_id": 1992316,
"author_profile": "https://Stackoverflow.com/users/1992316",
"pm_score": 1,
"selected": false,
"text": "function GetTextRectToPixels(obj)\n{\nvar tmpRect = obj.getBoundingClientRect();\nobj.style.width = \"auto\"; \nobj.style.height = \"auto\"; \nvar Ret = obj.getBoundingClientRect(); \nobj.style.width = (tmpRect.right - tmpRect.left).toString() + \"px\";\nobj.style.height = (tmpRect.bottom - tmpRect.top).toString() + \"px\"; \nreturn Ret;\n}\n"
},
{
"answer_id": 17118176,
"author": "Gjaa",
"author_id": 2171254,
"author_profile": "https://Stackoverflow.com/users/2171254",
"pm_score": 1,
"selected": false,
"text": "clientWidth clientHeight var element = document.getElementById (\"mytext\");\n\nvar width = element.clientWidth;\nvar height = element.clientHeight;\n element.style.position = \"absolute\";\n div p span"
},
{
"answer_id": 18789999,
"author": "artnikpro",
"author_id": 1955709,
"author_profile": "https://Stackoverflow.com/users/1955709",
"pm_score": 2,
"selected": false,
"text": "function textWidth(text, fontProp) {\n var tag = document.createElement(\"div\");\n tag.style.position = \"absolute\";\n tag.style.left = \"-999em\";\n tag.style.whiteSpace = \"nowrap\";\n tag.style.font = fontProp;\n tag.innerHTML = text;\n\n document.body.appendChild(tag);\n\n var result = tag.clientWidth;\n\n document.body.removeChild(tag);\n\n return result;\n}\n if ( textWidth(\"Text\", \"bold 13px Verdana\") > elementWidth) {\n ...\n}\n"
},
{
"answer_id": 19994364,
"author": "kavun",
"author_id": 789893,
"author_profile": "https://Stackoverflow.com/users/789893",
"pm_score": -1,
"selected": false,
"text": "var textWidth = (function (el) {\n el.style.position = 'absolute';\n el.style.top = '-1000px';\n document.body.appendChild(el);\n\n return function (text) {\n el.innerHTML = text;\n return el.clientWidth;\n };\n})(document.createElement('div'));\n"
},
{
"answer_id": 21015393,
"author": "Domi",
"author_id": 2228771,
"author_profile": "https://Stackoverflow.com/users/2228771",
"pm_score": 9,
"selected": false,
"text": "/**\n * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.\n * \n * @param {String} text The text to be rendered.\n * @param {String} font The css font descriptor that text is to be rendered with (e.g. \"bold 14px verdana\").\n * \n * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393\n */\nfunction getTextWidth(text, font) {\n // re-use canvas object for better performance\n const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement(\"canvas\"));\n const context = canvas.getContext(\"2d\");\n context.font = font;\n const metrics = context.measureText(text);\n return metrics.width;\n}\n\nfunction getCssStyle(element, prop) {\n return window.getComputedStyle(element, null).getPropertyValue(prop);\n}\n\nfunction getCanvasFont(el = document.body) {\n const fontWeight = getCssStyle(el, 'font-weight') || 'normal';\n const fontSize = getCssStyle(el, 'font-size') || '16px';\n const fontFamily = getCssStyle(el, 'font-family') || 'Times New Roman';\n \n return `${fontWeight} ${fontSize} ${fontFamily}`;\n}\n\nconsole.log(getTextWidth(\"hello there!\", \"bold 12pt arial\")); // close to 86\n myEl getCanvasFont const fontSize = getTextWidth(text, getCanvasFont(myEl));\n// do something with fontSize here...\n getCanvasFontSize body textAlign textBaseline Math.floor Math.ceil"
},
{
"answer_id": 21961146,
"author": "schickling",
"author_id": 2418739,
"author_profile": "https://Stackoverflow.com/users/2418739",
"pm_score": 4,
"selected": false,
"text": "var size = calculateSize(\"Hello world!\", {\n font: 'Arial',\n fontSize: '12px'\n});\n\nconsole.log(size.width); // 65\nconsole.log(size.height); // 14\n"
},
{
"answer_id": 23665686,
"author": "Mauricio Mora",
"author_id": 1863494,
"author_profile": "https://Stackoverflow.com/users/1863494",
"pm_score": 0,
"selected": false,
"text": "(function($){\n\n $.fn.autofit = function() { \n\n var hiddenDiv = $(document.createElement('div')),\n content = null;\n\n hiddenDiv.css('display','none');\n\n $('body').append(hiddenDiv);\n\n $(this).bind('fit keyup keydown blur update focus',function () {\n content = $(this).val();\n\n content = content.replace(/\\n/g, '<br>');\n hiddenDiv.html(content);\n\n $(this).css('width', hiddenDiv.width());\n\n });\n\n return this;\n\n };\n })(jQuery);\n"
},
{
"answer_id": 28199324,
"author": "v1r00z",
"author_id": 821888,
"author_profile": "https://Stackoverflow.com/users/821888",
"pm_score": 0,
"selected": false,
"text": "String.prototype.width = function (fontSize) {\n var el,\n f = fontSize + \" px arial\" || '12px arial';\n el = document.createElement('div');\n el.style.position = 'absolute';\n el.style.float = \"left\";\n el.style.whiteSpace = 'nowrap';\n el.style.visibility = 'hidden';\n el.style.font = f;\n el.innerHTML = this;\n el = document.body.appendChild(el);\n w = el.offsetWidth;\n el.parentNode.removeChild(el);\n return w;\n}\n\n// Usage\n\"MyString\".width(12);\n"
},
{
"answer_id": 30945077,
"author": "Jason Williams",
"author_id": 2733283,
"author_profile": "https://Stackoverflow.com/users/2733283",
"pm_score": 0,
"selected": false,
"text": "<h1 id=\"test1\">\n How wide is this text?\n</h1>\n<div id=\"result1\"></div>\n<hr/>\n<p id=\"test2\">\n How wide is this text?\n</p>\n<div id=\"result2\"></div>\n<hr/>\n<p id=\"test3\">\n How wide is this text?<br/><br/>\n f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j\n</p>\n<div id=\"result3\"></div>\n function getTextWidth(text, font) {\n var canvas = getTextWidth.canvas ||\n (getTextWidth.canvas = document.createElement(\"canvas\"));\n var context = canvas.getContext(\"2d\");\n context.font = font;\n var metrics = context.measureText(text);\n return metrics.width;\n};\n\n$(\"#result1\")\n.text(\"answer: \" +\n getTextWidth(\n $(\"#test1\").text(),\n $(\"#test1\").css(\"font\")) + \" px\");\n\n$(\"#result2\")\n .text(\"answer: \" +\n getTextWidth(\n $(\"#test2\").text(),\n $(\"#test2\").css(\"font\")) + \" px\");\n\n$(\"#result3\")\n .text(\"answer: \" +\n getTextWidth(\n $(\"#test3\").text(),\n $(\"#test3\").css(\"font\")) + \" px\");\n"
},
{
"answer_id": 36403029,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 1,
"selected": false,
"text": "fontOptions (function($) {\n $.format = function(format) {\n return (function(format, args) {\n return format.replace(/{(\\d+)}/g, function(val, pos) {\n return typeof args[pos] !== 'undefined' ? args[pos] : val;\n });\n }(format, [].slice.call(arguments, 1)));\n };\n $.measureText = function(html, fontOptions) {\n fontOptions = $.extend({\n fontSize: '1em',\n fontStyle: 'normal',\n fontWeight: 'normal',\n fontFamily: 'arial'\n }, fontOptions);\n var $el = $('<div>', {\n html: html,\n css: {\n position: 'absolute',\n left: -1000,\n top: -1000,\n display: 'none'\n }\n }).appendTo('body');\n $(fontOptions).each(function(index, option) {\n $el.css(option, fontOptions[option]);\n });\n var h = $el.outerHeight(), w = $el.outerWidth();\n $el.remove();\n return { height: h, width: w };\n };\n}(jQuery));\n\nvar dimensions = $.measureText(\"Hello World!\", { fontWeight: 'bold', fontFamily: 'arial' });\n\n// Font Dimensions: 94px x 18px\n$('body').append('<p>').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height)); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>"
},
{
"answer_id": 48172630,
"author": "Toph",
"author_id": 120290,
"author_profile": "https://Stackoverflow.com/users/120290",
"pm_score": 5,
"selected": false,
"text": "const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]\nconst avg = 0.5279276315789471\n\nfunction measureText(str, fontSize) {\n return Array.from(str).reduce(\n (acc, cur) => acc + (widths[cur.charCodeAt(0)] ?? avg), 0\n ) * fontSize\n}\n"
},
{
"answer_id": 50661478,
"author": "transistor09",
"author_id": 420597,
"author_profile": "https://Stackoverflow.com/users/420597",
"pm_score": 1,
"selected": false,
"text": "Element.getClientRects() DOMRect DOMRect DOMRect left top right bottom document.getElementById('in').addEventListener('input', function (event) {\n var span = document.getElementById('text-render')\n span.innerText = event.target.value\n var rects = span.getClientRects()\n var widthSum = 0\n for (var i = 0; i < rects.length; i++) {\n widthSum += rects[i].right - rects[i].left\n }\n document.getElementById('width-sum').value = widthSum\n}) <p><textarea id='in'></textarea></p>\n<p><span id='text-render'></span></p>\n<p>Sum of all widths: <output id='width-sum'>0</output>px</p>"
},
{
"answer_id": 50813259,
"author": "M Katz",
"author_id": 384670,
"author_profile": "https://Stackoverflow.com/users/384670",
"pm_score": 2,
"selected": false,
"text": "/**\n * Find the largest font size (in pixels) that allows the string to fit in the given width.\n * \n * @param {String} text - The text to be rendered.\n * @param {String} font - The css font descriptor that text is to be rendered with (e.g. \"bold ?px verdana\") -- note the use of ? in place of the font size.\n * @param {Number} width - The width in pixels the string must fit in\n * @param {Number} minFontPx - The smallest acceptable font size in pixels\n * @param {Number} maxFontPx - The largest acceptable font size in pixels\n **/\nfunction GetTextSizeForWidth(text, font, width, minFontPx, maxFontPx) {\n for (;;) {\n var s = font.replace(\"?\", maxFontPx);\n var w = GetTextWidth(text, s);\n if (w <= width) {\n return maxFontPx;\n }\n\n var g = (minFontPx + maxFontPx) / 2;\n\n if (Math.round(g) == Math.round(minFontPx) || Math.round(g) == Math.round(maxFontPx)) {\n return g;\n }\n\n s = font.replace(\"?\", g);\n w = GetTextWidth(text, s);\n if (w >= width) {\n maxFontPx = g;\n } else {\n minFontPx = g;\n }\n }\n}\n"
},
{
"answer_id": 53958056,
"author": "Roman86",
"author_id": 4892968,
"author_profile": "https://Stackoverflow.com/users/4892968",
"pm_score": 1,
"selected": false,
"text": "function getSpan(){\n const span = document.createElement('span')\n span.style.position = 'fixed';\n span.style.visibility = 'hidden';\n document.body.appendChild(span);\n return span;\n}\n\nfunction textWidth(str, css) {\n const span = getSpan();\n Object.assign(span.style, css || {});\n span.innerText = str;\n const w = Math.round(span.getBoundingClientRect().width);\n \n span.remove();\n \n return w;\n}\n\n\nconst testStyles = [\n {fontSize: '10px'},\n {fontSize: '12px'},\n {fontSize: '60px'},\n {fontSize: '120px'},\n {fontSize: '120px', padding: '10px'},\n {fontSize: '120px', fontFamily: 'arial'},\n {fontSize: '120px', fontFamily: 'tahoma'},\n {fontSize: '120px', fontFamily: 'tahoma', padding: '5px'},\n];\n\nconst ul = document.getElementById('output');\ntestStyles.forEach(style => {\n const li = document.createElement('li');\n li.innerText = `${JSON.stringify(style)} > ${textWidth('abc', style)}`;\n ul.appendChild(li);\n}); <ul id=\"output\"></ul>"
},
{
"answer_id": 59647192,
"author": "Inc33",
"author_id": 986419,
"author_profile": "https://Stackoverflow.com/users/986419",
"pm_score": 2,
"selected": false,
"text": "function getNodeTextWidth(nodeWithText) {\n var textNode = $(nodeWithText).contents().filter(function () {\n return this.nodeType == Node.TEXT_NODE;\n })[0];\n var range = document.createRange();\n range.selectNode(textNode);\n return range.getBoundingClientRect().width;\n}\n"
},
{
"answer_id": 63309811,
"author": "Darex1991",
"author_id": 3012785,
"author_profile": "https://Stackoverflow.com/users/3012785",
"pm_score": 0,
"selected": false,
"text": "textMetrics.init(document.querySelector('h1'), { fontSize: '20px' });\n\ntextMetrics.init({\n fontSize: '14px',\n lineHeight: '20px',\n fontFamily: 'Helvetica, Arial, sans-serif',\n fontWeight: 400,\n width: 100,\n});\n"
},
{
"answer_id": 70178495,
"author": "Red Mercury",
"author_id": 2133888,
"author_profile": "https://Stackoverflow.com/users/2133888",
"pm_score": 1,
"selected": false,
"text": "max-content font-size letter-spacing function measureTextPxWidth(\n text,\n template = document.createElement(\"span\")\n) {\n const measurer = template.cloneNode();\n measurer.style.setProperty(\"all\", \"revert\", \"important\");\n measurer.style.setProperty(\"position\", \"position\", \"important\");\n measurer.style.setProperty(\"visibility\", \"hidden\", \"important\");\n measurer.style.setProperty(\"width\", \"max-content\", \"important\");\n measurer.innerText = text;\n\n document.body.appendChild(measurer);\n const { width } = measurer.getBoundingClientRect();\n document.body.removeChild(measurer);\n return width;\n}\n\ndocument.querySelector('.spanTextWidth').innerText = \n `${measureTextPxWidth('one two three')}px`\n \ndocument.querySelector('.h1TextWidth').innerText = \n `${measureTextPxWidth('one two three', document.querySelector('h1'))}px` h1 {\n letter-spacing: 3px;\n} <span>one two three</span>\n<div class=\"spanTextWidth\"></div>\n \n<h1>one two three</h1>\n<div class=\"h1TextWidth\"></div>"
},
{
"answer_id": 72148318,
"author": "V. Rubinetti",
"author_id": 2180570,
"author_profile": "https://Stackoverflow.com/users/2180570",
"pm_score": 2,
"selected": false,
"text": "import { load } from \"opentype.js\";\n\nconst getWidth = async (text = \"Hello World\") => {\n const font = await load(\"path/to/some/font\");\n const { x1, x2 } = font.getPath(text, 0, 0, 12).getBoundingBox();\n return x2 - x1;\n};\n load 5ms 3ms 4ms"
},
{
"answer_id": 72222681,
"author": "Felipe Chernicharo",
"author_id": 13111779,
"author_profile": "https://Stackoverflow.com/users/13111779",
"pm_score": 1,
"selected": false,
"text": "export default function App() {\n const spanRef = useRef<HTMLSpanElement>(null);\n const [textWidth, setTextWidth] = useState(0);\n\n const getTextWidthInPixels = (ref: HTMLSpanElement) =>\n ref.getBoundingClientRect().width;\n\n useEffect(() => {\n setTextWidth(getTextWidthInPixels(spanRef.current!));\n }, [spanRef]);\n\n return (\n <div className=\"App\">\n <span\n ref={spanRef}\n contentEditable\n suppressContentEditableWarning\n onInput={() => setTextWidth(getTextWidthInPixels(spanRef.current!))}\n >\n Edit Me!!!\n </span>\n {`textWidth: ${textWidth}px`}\n </div>\n );\n}\n\n <span> useRef <span> getBoundingClientRect contentEditable suppressContentEditableWarning"
},
{
"answer_id": 73213192,
"author": "JOHNNY SHAHIN",
"author_id": 17499951,
"author_profile": "https://Stackoverflow.com/users/17499951",
"pm_score": 0,
"selected": false,
"text": "window.addEventListener(\"error\",function(e){ alert(e.message); });\nvar canvas = new OffscreenCanvas(400, 50);\nvar ctx = canvas.getContext(\"2d\");\nctx.font = \"16px Ariel\"; //this can be dynamic using getComputedStyle\nconst chars = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\" \",\" \"];\nconst charWidths = new Map();\nwhile(chars.length > 0){\n var char = chars.shift();\n var wide = ctx.measureText(char).width;\n charWidths.set(char,wide);\n}\n var pixelWidth = charWidths.get(\"0\");\n//fyi css properties like letter-spacing need to be accounted for\n"
},
{
"answer_id": 73342405,
"author": "Vikash Madhow",
"author_id": 576437,
"author_profile": "https://Stackoverflow.com/users/576437",
"pm_score": 1,
"selected": false,
"text": "scrollWidth function measureText(text) {\n let div = document.createElement(\"div\");\n div.innerText = text;\n div.style.whiteSpace = 'nowrap';\n body.appendChild(div);\n let width = div.scrollWidth;\n body.removeChild(div);\n return width;\n}\n scrollWidth scrollHeight"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8119/"
] |
118,243
|
<p>How can I open multiple Eclipse workspaces at the same time on the Mac?</p>
<p>On other platforms, I can just launch extra Eclipse instances, but the Mac will not let me open the same application twice. Is there a better way than keeping two copies of Eclipse?</p>
|
[
{
"answer_id": 118286,
"author": "Tim Visher",
"author_id": 16562,
"author_profile": "https://Stackoverflow.com/users/16562",
"pm_score": 8,
"selected": true,
"text": "cd /Applications/eclipse/ cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS ./eclipse &"
},
{
"answer_id": 386470,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 8,
"selected": false,
"text": "cd /Applications/eclipse/\n\nopen -n Eclipse.app\n open -n eclipse com.apple.quarantine"
},
{
"answer_id": 1833600,
"author": "devewm",
"author_id": 149191,
"author_profile": "https://Stackoverflow.com/users/149191",
"pm_score": 1,
"selected": false,
"text": "-data\n/Users/eric/Workspaces/projectb\n"
},
{
"answer_id": 2390324,
"author": "aaron",
"author_id": 21211,
"author_profile": "https://Stackoverflow.com/users/21211",
"pm_score": 4,
"selected": false,
"text": "#!/bin/sh\n# open, as suggested by Milhous\nopen -n $(dirname $0)/Eclipse.app --args -data /path/to/your/other/workspace\n"
},
{
"answer_id": 5292100,
"author": "sijju",
"author_id": 657864,
"author_profile": "https://Stackoverflow.com/users/657864",
"pm_score": -1,
"selected": false,
"text": "Window -> New Window\n"
},
{
"answer_id": 33361225,
"author": "Johan Witters",
"author_id": 5123299,
"author_profile": "https://Stackoverflow.com/users/5123299",
"pm_score": 2,
"selected": false,
"text": "cd /Applications/Eclipse.app/Contents/MacOS\n./eclipse &\n"
},
{
"answer_id": 35837693,
"author": "A. K. Sahu",
"author_id": 4128409,
"author_profile": "https://Stackoverflow.com/users/4128409",
"pm_score": 5,
"selected": false,
"text": "open -n Eclipse.app\n"
},
{
"answer_id": 50321398,
"author": "Agustí Sánchez",
"author_id": 791694,
"author_profile": "https://Stackoverflow.com/users/791694",
"pm_score": 2,
"selected": false,
"text": "do shell script \"open '/path/to/your/Eclipse/installation' -n --args -data /path/to/your/workspace\"\n do shell script \"open '/Applications/Eclipse.app' -n --args -data /MyWorkspaces/Personal\" \n"
},
{
"answer_id": 56752974,
"author": "Jayant Varshney",
"author_id": 1520640,
"author_profile": "https://Stackoverflow.com/users/1520640",
"pm_score": 2,
"selected": false,
"text": "open -n /Applications/Eclipse.app"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
118,260
|
<p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE_(Python)" rel="noreferrer">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
|
[
{
"answer_id": 118275,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 7,
"selected": true,
"text": "idle.py Lib\\idlelib\\idle.py"
},
{
"answer_id": 118308,
"author": "Dara Kong",
"author_id": 11292,
"author_profile": "https://Stackoverflow.com/users/11292",
"pm_score": 3,
"selected": false,
"text": "C:\\Python25\\Lib\\idlelib\\idle.pyw\n"
},
{
"answer_id": 7394470,
"author": "2rs2ts",
"author_id": 691859,
"author_profile": "https://Stackoverflow.com/users/691859",
"pm_score": 4,
"selected": false,
"text": "\\Python32\\Lib\\idlelib\\idle.bat"
},
{
"answer_id": 8237399,
"author": "Roger",
"author_id": 1050824,
"author_profile": "https://Stackoverflow.com/users/1050824",
"pm_score": 3,
"selected": false,
"text": "import idlelib.PyShell\nidlelib.PyShell.main()\n"
},
{
"answer_id": 33572951,
"author": "cbeytas",
"author_id": 5534627,
"author_profile": "https://Stackoverflow.com/users/5534627",
"pm_score": 1,
"selected": false,
"text": "..\\..\\..\\..\\..\\Python27\\pythonw.exe \"C:\\Python27\\Lib\\idlelib\\idle.pyw\""
},
{
"answer_id": 35535565,
"author": "Ohad Cohen",
"author_id": 2601521,
"author_profile": "https://Stackoverflow.com/users/2601521",
"pm_score": 2,
"selected": false,
"text": "c:\\Python27\\Lib\\idlelib\\idle.bat\n"
},
{
"answer_id": 43357652,
"author": "1amdadmt",
"author_id": 7852046,
"author_profile": "https://Stackoverflow.com/users/7852046",
"pm_score": 1,
"selected": false,
"text": "C:\\Python36\\pythonw.exe c:/python36/Lib/idlelib/idle.py\n with open('FILE.py') as f:\n exec(f.read())\n"
},
{
"answer_id": 59516101,
"author": "Dennis",
"author_id": 11461120,
"author_profile": "https://Stackoverflow.com/users/11461120",
"pm_score": 1,
"selected": false,
"text": "pyw -m idlelib"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5113/"
] |
118,261
|
<p>E.g. we this code in the asp.net form codebihind:</p>
<pre><code>private void btnSendEmails_OnClick()
{
Send100000EmailsAndWaitForReplies();
}
</code></pre>
<p>This code execution will be killed by the timeout reason.
For resolving the problem I'd like to see something like this:</p>
<pre><code>private void btnSendEmails_OnClick()
{
var taskId = AsyncTask.Run( () => Send100000EmailsAndWaitForReplies() );
// Store taskId for future task execution status checking.
}
</code></pre>
<p>And this method will be executed for some way outside the w3wp.exe process within a special enveronment.</p>
<p>Does anybody know a framework/toolset for resolving this kind of issues?</p>
<p><strong>Update:</strong> The emails sending method is only an example of what I mean. In fact, I could have a lot of functionality need to be executed outside the asp.net working process. </p>
<p>E.g. this point is very important for an application which aggregates data from a couple of 3rd party services, do something with it and send it back to another service.</p>
|
[
{
"answer_id": 118295,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<%@ Page Language=\"C#\" Async=\"true\" %>\n<script runat=\"server\">\n\n protected void Page_Load(object sender, EventArgs e)\n {\n BeginEventHandler begin = new BeginEventHandler(BeginMethod);\n EndEventHandler end = new EndEventHandler(EndMethod);\n\n AddOnPreRenderCompleteAsync(begin, end);\n }\n</script>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9198/"
] |
118,280
|
<p>I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. </p>
<p>I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?</p>
<pre><code><html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 120050,
"author": "Dave Richardson",
"author_id": 3392,
"author_profile": "https://Stackoverflow.com/users/3392",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<title>Example of IE6 resize issue</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"?.css\" />\n<script src=\"http://www.google.com/jsapi\"></script>\n<script>\n google.load(\"jquery\", \"1\");\n google.load(\"jqueryui\", \"1\");\n\n google.setOnLoadCallback(\n function() {\n $(document).ready(function()\n {\n $(\"#main-dialog\").dialog();\n });\n });\n</script>\n</head>\n<body>\n<div id=\"main-dialog\">\n This is just some simple content that will fill the dialog. This example is\n sufficient to reproduce the problem in IE6. It does not seem to occur in IE7\n or FF. I haven't tried with Opera or Safari.\n</div>\n</body> \n</html>\n"
},
{
"answer_id": 130100,
"author": "Harry Steinhilber",
"author_id": 6118,
"author_profile": "https://Stackoverflow.com/users/6118",
"pm_score": 3,
"selected": true,
"text": ".ui-dialog .ui-dialog-container {\n overflow: hidden;\n}\n if ($.browser.msie && $.browser.version == 6)\n{\n $(\".ui-dialog-container\").css({ overflow: 'hidden' });\n} \n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6118/"
] |
118,289
|
<p>I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long.</p>
<p>To elaborate:</p>
<p>I have a string</p>
<pre><code>$str = '--infile /tmp/infile_location --outfile /tmp/outfile'
</code></pre>
<p>I want it to be parsed by GetOptions so that it is easier for me to add new options.</p>
<p>One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ...</p>
<pre><code>my @arg_arr = split (/\s/, $input_line);
# This is done so that GetOptions reads these new arguments
@ARGV = @arg_arr;
print "ARGV is : @ARGV\n";
GetOptions (
'infile=s' => \$infile,
'outfile=s' => \$outfile
);
</code></pre>
<p>Is there any good/better way?</p>
|
[
{
"answer_id": 118392,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 3,
"selected": false,
"text": "GetOptionsFromArray ([glob ($input_line)]);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
118,292
|
<p>So I was writing some code today that basically looks like this:</p>
<pre><code>string returnString = s.Replace("!", " ")
.Replace("@", " ")
.Replace("#", " ")
.Replace("$", " ")
.Replace("%", " ")
.Replace("^", " ")
.Replace("*", " ")
.Replace("_", " ")
.Replace("+", " ")
.Replace("=", " ")
.Replace("\", " ")
</code></pre>
<p>Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the <code>Replace()</code> function?</p>
|
[
{
"answer_id": 118306,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "var returnString = Regex.Replace(s,@\"[!@#\\$%\\^*_\\+=\\\\]\",\" \");\n"
},
{
"answer_id": 118314,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "s/[!@#$%^*_+=\\]/ /\n Regex.Replace(yourstring, \"[!@#$%^*_+=\\]\", \"\" ); \n"
},
{
"answer_id": 118660,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "static public string ReplaceCharsWithSpace(this string original, string chars)\n{\n var result = new StringBuilder();\n foreach (var ch in original)\n {\n result.Append(chars.Contains(ch) ? ' ' : ch);\n }\n return result.ToString();\n}\n char IsLetter IsDigit IsPunctuation IsSymbol static public string ReplaceNonLetterCharsWithSpace(this string original)\n{\n var result = new StringBuilder();\n foreach (var ch in original)\n {\n result.Append(char.IsLetter(ch) ? ch : ' ');\n }\n return result.ToString();\n}\n string s = \"ab!2c\";\ns = s.ReplaceCharsWithSpace(@\"!@#$%^*_+=/\"); // s contains \"ab c\"\n\nstring t = \"ab3*c\";\nt = t.ReplaceNonLetterCharsWithSpace(); // t contains \"ab c\"\n"
},
{
"answer_id": 210940,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "List<>, ForEach using System.Collections.Generic;\n\nnamespace ReplaceWithSpace \n {\n class Program \n {\n static void Main(string[] args) \n {\n string someString = \"#1, 1+1=2 $string$!\";\n\n var charsToRemove = new List<char>(@\"!@#$%^*_+=\\\");\n charsToRemove.ForEach(c => someString = someString.Replace(c, ' '));\n\n System.Diagnostics.Debug.Print(someString); //\" 1, 1 1 2 string \"\n }\n }\n\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
118,305
|
<p>How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?</p>
<p>i.e. an <code>encode()</code> function such that:</p>
<pre><code>encode("“£”") -> "&#8220;&#163;&#8221;"
</code></pre>
<p><code>decode()</code> would also be useful:</p>
<pre><code>decode("&#8220;&#163;&#8221;") -> "“£”"
</code></pre>
<p>PHP's <code>htmlenties()</code>/<code>html_entity_decode()</code> pair does not do the right thing:</p>
<pre><code>htmlentities(html_entity_decode("&#8220;&#163;&#8221;")) ->
"&amp;#8220;&pound;&amp;#8221;"
</code></pre>
<p>Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:</p>
<pre><code>htmlentities(html_entity_decode("&#8220;&#163;&#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
"&ldquo;&pound;&rdquo;"
</code></pre>
|
[
{
"answer_id": 193057,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 0,
"selected": false,
"text": "iconv() function decode( $string )\n{\n $doc = new DOMDocument( \"1.0\", \"UTF-8\" ); \n $doc->LoadXML( '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'.\"\\n\".'<x />', LIBXML_NOENT );\n $doc->documentElement->appendChild( $doc->createTextNode( $string ) );\n $output = $doc->saveXML( $doc );\n $output = preg_replace( '/<\\?([^>]+)\\?>/', '', $output ); \n $output = str_replace( array( '<x>', '</x>' ), array( '', '' ), $output );\n return trim( $output );\n}\n"
},
{
"answer_id": 194025,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "mb_encode_numericentity"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11543/"
] |
118,307
|
<p>Tools like 'ps' and 'top' report various kinds of memory usages, such as the VM size and the Resident Set Size. However, none of those are the "real" memory usage:</p>
<ul>
<li>Program code is shared between multiple instances of the same program.</li>
<li>Shared library program code is shared between all processes that use that library.</li>
<li>Some apps fork off processes and share memory with them (e.g. via shared memory segments).</li>
<li>The virtual memory system makes the VM size report pretty much useless.</li>
<li>RSS is 0 when a process is swapped out, making it not very useful.</li>
<li>Etc etc.</li>
</ul>
<p>I've found that the private dirty RSS, as reported by Linux, is the closest thing to the "real" memory usage. This can be obtained by summing all <code>Private_Dirty</code> values in <code>/proc/somepid/smaps</code>.</p>
<p>However, do other operating systems provide similar functionality? If not, what are the alternatives? In particular, I'm interested in FreeBSD and OS X.</p>
|
[
{
"answer_id": 1954774,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 6,
"selected": false,
"text": "sudo vmmap <pid>\n sudo vmmap -resident <pid>\n REGION TYPE [ VIRTUAL/RESIDENT]\n=========== [ =======/========]\nATS (font support) [ 33.8M/ 2496K]\nCG backing stores [ 5588K/ 5460K]\nCG image [ 20K/ 20K]\nCG raster data [ 576K/ 576K]\nCG shared images [ 2572K/ 2404K]\nCarbon [ 1516K/ 1516K]\nCoreGraphics [ 8K/ 8K]\nIOKit [ 256.0M/ 0K]\nMALLOC [ 256.9M/ 247.2M]\nMemory tag=240 [ 4K/ 4K]\nMemory tag=242 [ 12K/ 12K]\nMemory tag=243 [ 8K/ 8K]\nMemory tag=249 [ 156K/ 76K]\nSTACK GUARD [ 101.2M/ 9908K]\nStack [ 14.0M/ 248K]\nVM_ALLOCATE [ 25.9M/ 25.6M]\n__DATA [ 6752K/ 3808K]\n__DATA/__OBJC [ 28K/ 28K]\n__IMAGE [ 1240K/ 112K]\n__IMPORT [ 104K/ 104K]\n__LINKEDIT [ 30.7M/ 3184K]\n__OBJC [ 1388K/ 1336K]\n__OBJC/__DATA [ 72K/ 72K]\n__PAGEZERO [ 4K/ 0K]\n__TEXT [ 108.6M/ 63.5M]\n__UNICODE [ 536K/ 512K]\nmapped file [ 118.8M/ 50.8M]\nshared memory [ 300K/ 276K]\nshared pmap [ 6396K/ 3120K]\n ReadOnly portion of Libraries: Total=139.3M resident=66.6M(48%) swapped_out_or_unallocated=72.7M(52%)\nWritable regions: Total=595.4M written=201.8M(34%) resident=283.1M(48%) swapped_out=0K(0%) unallocated=312.3M(52%)\n"
},
{
"answer_id": 14191692,
"author": "Arvind",
"author_id": 291917,
"author_profile": "https://Stackoverflow.com/users/291917",
"pm_score": 1,
"selected": false,
"text": "mount -t linprocfs none /proc\ncat /proc/PROCESSID/status\n"
},
{
"answer_id": 16597463,
"author": "BMDan",
"author_id": 598625,
"author_profile": "https://Stackoverflow.com/users/598625",
"pm_score": 2,
"selected": false,
"text": "awk bc find /proc/ -maxdepth 1 -name '[0-9]*' -print0 | while read -r -d $'\\0' pidpath; do\n [ -f \"${pidpath}/smaps\" ] || continue\n awk '!/^Private_Dirty:/ {next;}\n $3==\"kB\" {pd += $2 * (1024^1); next}\n $3==\"mB\" {pd += $2 * (1024^2); next}\n $3==\"gB\" {pd += $2 * (1024^3); next}\n $3==\"tB\" {pd += $2 * (1024^4); next}\n $3==\"pB\" {pd += $2 * (1024^5); next}\n {print \"ERROR!! \"$0 >\"/dev/stderr\"; exit(1)}\n END {printf(\"%10d: %d\\n\", '\"${pidpath##*/}\"', pd)}' \"${pidpath}/smaps\" || break\ndone\n | sort -n -k 2 56: 106496\n 1: 147456\n 55: 155648\n"
},
{
"answer_id": 18815222,
"author": "http8086",
"author_id": 1356874,
"author_profile": "https://Stackoverflow.com/users/1356874",
"pm_score": 1,
"selected": false,
"text": "info->mem info->memxserver info->memwritable static void\nget_process_memory_writable (ProcInfo *info)\n{\n glibtop_proc_map buf;\n glibtop_map_entry *maps;\n\n maps = glibtop_get_proc_map(&buf, info->pid);\n\n gulong memwritable = 0;\n const unsigned number = buf.number;\n\n for (unsigned i = 0; i < number; ++i) {\n#ifdef __linux__\n memwritable += maps[i].private_dirty;\n#else\n if (maps[i].perm & GLIBTOP_MAP_PERM_WRITE)\n memwritable += maps[i].size;\n#endif\n }\n\n info->memwritable = memwritable;\n\n g_free(maps);\n}\n\nstatic void\nget_process_memory_info (ProcInfo *info)\n{\n glibtop_proc_mem procmem;\n WnckResourceUsage xresources;\n\n wnck_pid_read_resource_usage (gdk_screen_get_display (gdk_screen_get_default ()),\n info->pid,\n &xresources);\n\n glibtop_get_proc_mem(&procmem, info->pid);\n\n info->vmsize = procmem.vsize;\n info->memres = procmem.resident;\n info->memshared = procmem.share;\n\n info->memxserver = xresources.total_bytes_estimate;\n\n get_process_memory_writable(info);\n\n // fake the smart memory column if writable is not available\n info->mem = info->memxserver + (info->memwritable ? info->memwritable : info->memres);\n}\n"
},
{
"answer_id": 52118812,
"author": "Edward Tomasz Napierala",
"author_id": 3390390,
"author_profile": "https://Stackoverflow.com/users/3390390",
"pm_score": 2,
"selected": false,
"text": "DESCRIPTION\n The mincore() system call determines whether each of the pages in the\n region beginning at addr and continuing for len bytes is resident. The\n status is returned in the vec array, one character per page. Each\n character is either 0 if the page is not resident, or a combination of\n the following flags (defined in <sys/mman.h>):\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/118307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20816/"
] |
118,341
|
<p>I have a Linq to objects statement</p>
<pre><code> var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
select l;
</code></pre>
<p>The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()</p>
<p>If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?</p>
<p><strong>EDIT</strong> When I said <em>I know for a fact that there are no null objects</em> it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'</p>
<p>LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool</p>
|
[
{
"answer_id": 118871,
"author": "Steve Steiner",
"author_id": 3892,
"author_profile": "https://Stackoverflow.com/users/3892",
"pm_score": 4,
"selected": false,
"text": "where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)\n"
},
{
"answer_id": 716060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": " var query = dataset.Tables[0].AsEnumerable()\n .Where (i=> i.Field<string>(\"Project\").Contains(\"070932.01\"))\n // .Select(i =>\n // {return i;}\n // )\n .Select (i=>i.Field<string>(\"City\"));\n"
},
{
"answer_id": 38815604,
"author": "user1414213562",
"author_id": 6659843,
"author_profile": "https://Stackoverflow.com/users/6659843",
"pm_score": 3,
"selected": false,
"text": "var confirm = from l in lines.Lines \n where (l.LineNumber == startline.LineNumber)\n || (l.LineNumber == endline.LineNumber) \n select l;\n\n confirm.ToArray(); // Press F11 (\"Step into\") when you reach this statement\n\n foreach(var o in q) // Press F11 when \"in\" keyword is highlighted as \"next statement\"\n // ...\n"
},
{
"answer_id": 54784747,
"author": "Sha",
"author_id": 5891216,
"author_profile": "https://Stackoverflow.com/users/5891216",
"pm_score": 0,
"selected": false,
"text": "using (var db = new AppContext())\n {\n db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);\n // Rest of code\n }\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
118,342
|
<p>I am aware of this command:
<code>cvs log -N -w<userid> -d"1 day ago"</code></p>
<p>Unfortunately this generates a formatted report with lots of newlines in it, such that the file-path, the file-version, and the comment-text are all on separate lines. Therefore it is difficult to scan it for all occurrences of comment text, (eg, grep), and correlate the matches to file/version.</p>
<p>(Note that the log output would be perfectly acceptable, if only cvs could perform the filtering natively.)</p>
<p>EDIT: Sample output. A block of text like this is reported for each repository file:</p>
<pre>
RCS file: /data/cvs/dps/build.xml,v
Working file: build.xml
head: 1.49
branch:
locks: strict
access list:
keyword substitution: kv
total revisions: 57; selected revisions: 1
description:
----------------------------
revision 1.48
date: 2008/07/09 17:17:32; author: noec; state: Exp; lines: +2 -2
Fixed src.jar references
----------------------------
revision 1.47
date: 2008/07/03 13:13:14; author: noec; state: Exp; lines: +1 -1
Fixed common-src.jar reference.
=============================================================================
</pre>
|
[
{
"answer_id": 118397,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<Cmd> | egrep 'Filename:|Version:|Comment:'\n # Assume the sections are of the format:\n# Filename: <filename>\n# Version: <version>\n# Comment: <comment>\n# <more comment>\n\nSet echo to false\nWhile more lines left\n Get line\n If line starts with \"Filename: \" and <filename> is of interest\n Set echo to true\n If line starts with \"Filename: \" and <filename> is not of interest\n Set echo to false\n If echo is true\n Output line\nEnd while\n"
},
{
"answer_id": 381972,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 4,
"selected": true,
"text": "-w -S cvs log -N -S -w<userid> -d\"1 day ago\"\n cvs log -N -S -w<userid> -d\"1 day ago\" | grep -B14 \"some text\" > afile\n /dev/null"
},
{
"answer_id": 538867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "import java.io.IOException;\n\n\npublic class ParseCVSLog\n{\n\n public static final String CVS_LOG_FILE_SEPARATOR = \"=============================================================================\";\n public static final String CVS_LOG_REVISION_SEPARATOR = \"----------------------------\";\n public static final String CVS_LOG_HEADER_FILE_NAME = \"Working file\";\n public static final String CVS_LOG_VERSION_PREFIX = \"revision\";\n\n public static void main(String[] args) throws IOException\n {\n String searchString = args[0];\n\n System.out.println( \"SEARCHING FOR: \" + searchString );\n\n StringBuffer cvsLogOutputBuffer = new StringBuffer();\n byte[] bytes = new byte[1024];\n int numBytesRead = 0;\n while( (numBytesRead = System.in.read( bytes )) > 0 )\n {\n String bytesString = new String(bytes, 0, numBytesRead);\n cvsLogOutputBuffer.append( bytesString );\n }\n\n String cvsLogOutput = cvsLogOutputBuffer.toString();\n\n String newLine = System.getProperty(\"line.separator\");\n String[] fileArray = cvsLogOutput.split( CVS_LOG_FILE_SEPARATOR );\n\n\n for ( String fileRecord : fileArray )\n {\n if ( !fileRecord.contains( searchString ) )\n {\n continue;\n }\n\n String[] revisionArray = fileRecord.split( CVS_LOG_REVISION_SEPARATOR );\n String[] fileHeaderLineArray = revisionArray[ 0 ].split( newLine );\n String fileName = \"\";\n for ( String fileHeadeLine : fileHeaderLineArray )\n {\n if ( fileHeadeLine.contains( CVS_LOG_HEADER_FILE_NAME ) )\n {\n fileName = fileHeadeLine.split( \": \" )[ 1 ];\n break;\n }\n }\n System.out.print( fileName );\n for ( int i = 1; i < revisionArray.length; i++ )\n {\n String versionRecord = revisionArray[ i ];\n if ( !versionRecord.contains( searchString ) )\n {\n continue;\n }\n String[] versionLineArray = versionRecord.split( newLine );\n for ( String versionLine : versionLineArray )\n {\n if ( versionLine.contains( CVS_LOG_VERSION_PREFIX ) )\n {\n System.out.print( \" \" + versionLine.split( \" \" )[ 1 ] );\n }\n }\n\n }\n System.out.println();\n }\n }\n}\n cvs log -N -S -washamsut | java ParseCVSLog GS-242\n"
},
{
"answer_id": 34339088,
"author": "JochenJung",
"author_id": 351893,
"author_profile": "https://Stackoverflow.com/users/351893",
"pm_score": 1,
"selected": false,
"text": "cvs log -N -S -b -w<userid> -d \">1 day ago\" 2>/dev/null | gawk 'BEGIN{out=0;} /^Working file:/ { print $0; } /^date:/ { out=1; } /^===/ { print \"\"; out=0; } (out==1){print $0;}'\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
118,343
|
<p>Ruby on Rails has <a href="http://wiki.rubyonrails.com/rails/pages/Timestamping" rel="nofollow noreferrer">magic timestamping fields</a> that are automatically updated when a record is created or updated. I'm trying to find similar functionality in Entity Framework. I've considered database triggers and a SavingChanges event handler. Is there a more obvious method I'm overlooking?</p>
|
[
{
"answer_id": 118397,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<Cmd> | egrep 'Filename:|Version:|Comment:'\n # Assume the sections are of the format:\n# Filename: <filename>\n# Version: <version>\n# Comment: <comment>\n# <more comment>\n\nSet echo to false\nWhile more lines left\n Get line\n If line starts with \"Filename: \" and <filename> is of interest\n Set echo to true\n If line starts with \"Filename: \" and <filename> is not of interest\n Set echo to false\n If echo is true\n Output line\nEnd while\n"
},
{
"answer_id": 381972,
"author": "s_t_e_v_e",
"author_id": 21176,
"author_profile": "https://Stackoverflow.com/users/21176",
"pm_score": 4,
"selected": true,
"text": "-w -S cvs log -N -S -w<userid> -d\"1 day ago\"\n cvs log -N -S -w<userid> -d\"1 day ago\" | grep -B14 \"some text\" > afile\n /dev/null"
},
{
"answer_id": 538867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "import java.io.IOException;\n\n\npublic class ParseCVSLog\n{\n\n public static final String CVS_LOG_FILE_SEPARATOR = \"=============================================================================\";\n public static final String CVS_LOG_REVISION_SEPARATOR = \"----------------------------\";\n public static final String CVS_LOG_HEADER_FILE_NAME = \"Working file\";\n public static final String CVS_LOG_VERSION_PREFIX = \"revision\";\n\n public static void main(String[] args) throws IOException\n {\n String searchString = args[0];\n\n System.out.println( \"SEARCHING FOR: \" + searchString );\n\n StringBuffer cvsLogOutputBuffer = new StringBuffer();\n byte[] bytes = new byte[1024];\n int numBytesRead = 0;\n while( (numBytesRead = System.in.read( bytes )) > 0 )\n {\n String bytesString = new String(bytes, 0, numBytesRead);\n cvsLogOutputBuffer.append( bytesString );\n }\n\n String cvsLogOutput = cvsLogOutputBuffer.toString();\n\n String newLine = System.getProperty(\"line.separator\");\n String[] fileArray = cvsLogOutput.split( CVS_LOG_FILE_SEPARATOR );\n\n\n for ( String fileRecord : fileArray )\n {\n if ( !fileRecord.contains( searchString ) )\n {\n continue;\n }\n\n String[] revisionArray = fileRecord.split( CVS_LOG_REVISION_SEPARATOR );\n String[] fileHeaderLineArray = revisionArray[ 0 ].split( newLine );\n String fileName = \"\";\n for ( String fileHeadeLine : fileHeaderLineArray )\n {\n if ( fileHeadeLine.contains( CVS_LOG_HEADER_FILE_NAME ) )\n {\n fileName = fileHeadeLine.split( \": \" )[ 1 ];\n break;\n }\n }\n System.out.print( fileName );\n for ( int i = 1; i < revisionArray.length; i++ )\n {\n String versionRecord = revisionArray[ i ];\n if ( !versionRecord.contains( searchString ) )\n {\n continue;\n }\n String[] versionLineArray = versionRecord.split( newLine );\n for ( String versionLine : versionLineArray )\n {\n if ( versionLine.contains( CVS_LOG_VERSION_PREFIX ) )\n {\n System.out.print( \" \" + versionLine.split( \" \" )[ 1 ] );\n }\n }\n\n }\n System.out.println();\n }\n }\n}\n cvs log -N -S -washamsut | java ParseCVSLog GS-242\n"
},
{
"answer_id": 34339088,
"author": "JochenJung",
"author_id": 351893,
"author_profile": "https://Stackoverflow.com/users/351893",
"pm_score": 1,
"selected": false,
"text": "cvs log -N -S -b -w<userid> -d \">1 day ago\" 2>/dev/null | gawk 'BEGIN{out=0;} /^Working file:/ { print $0; } /^date:/ { out=1; } /^===/ { print \"\"; out=0; } (out==1){print $0;}'\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453303/"
] |
118,356
|
<p>I have a custom program which preprocesses a C# file and generates a new C# file as output. I would like to invoke this from msbuild on each of the C# files in the project, then compile the output files instead of the original C# files. How would I go about this?</p>
|
[
{
"answer_id": 119662,
"author": "Jivko Petiov",
"author_id": 11348,
"author_profile": "https://Stackoverflow.com/users/11348",
"pm_score": 0,
"selected": false,
"text": "<Exec Command=\"your executable\" />\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13193/"
] |
118,370
|
<p>This came up in <a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
|
[
{
"answer_id": 118395,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "Ellipsis ... >>> class TestEllipsis(object):\n... def __getitem__(self, item):\n... if item is Ellipsis:\n... return \"Returning all items\"\n... else:\n... return \"return %r items\" % item\n... \n>>> x = TestEllipsis()\n>>> print x[2]\nreturn 2 items\n>>> print x[...]\nReturning all items\n"
},
{
"answer_id": 118508,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": false,
"text": ": >>> from numpy import arange\n>>> a = arange(16).reshape(2,2,2,2)\n >>> a[..., 0].flatten()\narray([ 0, 2, 4, 6, 8, 10, 12, 14])\n >>> a[:,:,:,0].flatten()\narray([ 0, 2, 4, 6, 8, 10, 12, 14])\n"
},
{
"answer_id": 50732784,
"author": "Mauricio Perez",
"author_id": 4363295,
"author_profile": "https://Stackoverflow.com/users/4363295",
"pm_score": 4,
"selected": false,
"text": ": >>> from numpy import arange\n>>> a = arange(4).reshape(2,2)\n >>> a[:,0,:]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIndexError: too many indices for array\n a[...,0,:]\narray([0, 1])\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15677/"
] |
118,371
|
<p>When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?</p>
<p>Is this safe:</p>
<pre><code>public class SomeClass {
private int val;
public synchronized int getVal() {
return val;
}
private void setVal(int val) {
this.val = val;
}
}
</code></pre>
<p>or does the setter introduce further complications?</p>
|
[
{
"answer_id": 118388,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 5,
"selected": true,
"text": " int old = someThing.getVal();\n if (old == 1) {\n someThing.setVal(2);\n }\n"
},
{
"answer_id": 118452,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "synchronized(someThing) {\n int old = someThing.getVal();\n if (old == 1) {\n someThing.setVal(2);\n }\n}\n"
},
{
"answer_id": 120261,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 0,
"selected": false,
"text": "public class SomeClass {\n\n private Object mutex = new Object();\n private int val = -1; // TODO: Adjust initialization to a reasonable start\n // value\n public int getVal() {\n synchronized ( mutex ) {\n return val;\n }\n }\n\n private void setVal( int val ) {\n synchronized ( mutex ) {\n this.val = val;\n }\n }\n}\n"
},
{
"answer_id": 1245596,
"author": "CaptainHastings",
"author_id": 135740,
"author_profile": "https://Stackoverflow.com/users/135740",
"pm_score": 1,
"selected": false,
"text": "public class ThreadSafeSomeClass {\n\n private final AtomicInteger value = new AtomicInteger(0);\n\n public void setValue(int x){\n value.set(x);\n }\n\n public int getValue(){\n return value.get();\n }\n\n}\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
] |
118,374
|
<p>For years, maybe 10, I've been fascinated with cryptography. I read a book about XOR bit-based encryption, and have been hooked ever since thing.</p>
<p>I guess it's more fair to say that I'm fascinated by those who can break various encryption methods, but I digress.</p>
<p>To the point -- what methods do you use when writing cryptography? Is obfuscation good in cryptography? </p>
<p>I use two key-based XOR encryption, various hashing techniques (SHA1) on the keys, and simple things such as reversing strings here and there, etc.</p>
<p>I'm interested to see what others think of and try when writing a not-so-out-of-the-box encryption method. Also -- any info on how the pros go about "breaking" various cryptography techniques would be interesting as well.</p>
<p><strong>To clarify -- I have no desire to use this in any production code, or any code of mine for that matter. I'm interesting in learning how it works through toying around, not reinventing the wheel. :)</strong></p>
<p>Ian</p>
|
[
{
"answer_id": 118453,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "CipherTextArray = PlainTextArray ^ KeyArray;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10853/"
] |
118,415
|
<p>My database is located in e.g. california.
My user table has all the user's timezone e.g. -0700 UTC </p>
<p>How can I adjust the time from my database server whenever I display a date to the user who lives in e.g. new york? UTC/GMT -4 hours</p>
|
[
{
"answer_id": 118432,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "DateTime.ToUniversalTime() -> server;\nDateTime.ToLocalTime() -> client\n"
},
{
"answer_id": 118437,
"author": "Laurent",
"author_id": 10786,
"author_profile": "https://Stackoverflow.com/users/10786",
"pm_score": 0,
"selected": false,
"text": "yourDate.AddHours(3) yourDate.AddHours(-3)"
},
{
"answer_id": 1183172,
"author": "jpbochi",
"author_id": 123897,
"author_profile": "https://Stackoverflow.com/users/123897",
"pm_score": 2,
"selected": false,
"text": "TimeZoneInfo TimeZoneInfo //This will get EST time zone\nTimeZoneInfo clientTimeZone\n = TimeZoneInfo.FindSystemTimeZoneById(\"Eastern Standard Time\");\n\n//This will get the local time zone, might be useful\n// if your application is a fat client\nTimeZoneInfo clientTimeZone = TimeZoneInfo.Local;\n DateTime Kind DateTime DateTime aDateTime = dataBaseSource.ReadADateTime();\nDateTime utcDateTime = DateTime.SpecifyKind(aDateTime, DateTimeKind.Utc);\n DateTime clientTime = TimeZoneInfo.ConvertTime(utcDateTime, clientTimeZone);\n TimeZoneInfo TimeZoneInfo"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
118,423
|
<p>I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?</p>
<p>The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.</p>
<hr />
<p>Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.</p>
<p>I just found <a href="http://www.mamp.info/en/mamp-pro/" rel="nofollow noreferrer">MAMP Pro</a> which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a <code>httpd.conf</code> file that can be edited and dropped into a project directory?</p>
<p>Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.</p>
|
[
{
"answer_id": 118522,
"author": "Bazman",
"author_id": 18521,
"author_profile": "https://Stackoverflow.com/users/18521",
"pm_score": 2,
"selected": false,
"text": "NameVirtualHost *:80\n\n<virtualhost *:80>\nServerName site1.mydyndns.dyndns.org\nDocumentRoot /site1/documentroot\n</virtualhost>\n\n<virtualhost *:80>\nServerName site2.mydyndns.dyndns.org\nDocumentRoot /site2/documentroot\n</virtualhost>\n"
},
{
"answer_id": 118559,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 1,
"selected": false,
"text": "/etc/apache2/apache2.conf ports.conf Listen 8080\n"
},
{
"answer_id": 118616,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 3,
"selected": false,
"text": "ports.conf NameVirtualHost *\n\n<virtualhost *:80>\nDocumentRoot /site1/documentroot\n</virtualhost>\n\n<virtualhost *:81>\nDocumentRoot /site2/documentroot\n</virtualhost>\n\n<virtualhost *:82>\nDocumentRoot /site3/documentroot\n</virtualhost>\n\n<virtualhost *:83>\nDocumentRoot /site4/documentroot\n</virtualhost>\n"
},
{
"answer_id": 118682,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 6,
"selected": true,
"text": ".dev .localhost 127.0.0.1 www.example.localhost\n127.0.0.1 example.localhost\n sudo apachectl graceful\n sudo apachectl configtest\n #NameVirtualHost * \n <VirtualHost *>\n DocumentRoot /Users/username/Sites/example.localhost\n ServerName example.localhost\n ServerAlias www.example.localhost\n</VirtualHost>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] |
118,443
|
<p>I have an application that tracks high scores in a game. </p>
<p>I have a <strong>user_scores</strong> table that maps a user_id to a score.</p>
<p>I need to return the 5 highest scores, but only 1 high score for any <em>specific</em> user.</p>
<p>So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.</p>
<p>I have tried to use:</p>
<pre><code>SELECT user_id, score
FROM user_scores
ORDER BY score DESC
GROUP BY user_id
LIMIT 5
</code></pre>
<p>But it seems that MySQL drops any user_id with more than 1 score. </p>
|
[
{
"answer_id": 118451,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT(user_id), score\nFROM user_scores\nORDER BY score DESC\nLIMIT 5\n"
},
{
"answer_id": 118457,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": true,
"text": "SELECT user_id, MAX(score)\nFROM user_scores \nGROUP BY user_id \nORDER BY MAX(score) DESC \nLIMIT 5\n"
},
{
"answer_id": 118485,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "SELECT user_id, max(score) FROM user_scores\nGROUP BY user_id\n"
},
{
"answer_id": 118489,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 1,
"selected": false,
"text": "SELECT user_id, MAX(score) AS score\nFROM user_scores \nGROUP BY user_id\nORDER BY score DESC\nLIMIT 5\n"
},
{
"answer_id": 118562,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 0,
"selected": false,
"text": "SELECT s1.user_id, \n (SELECT score FROM user_scores s2 WHERE s2.user_id = s1.user_id ORDER BY score DESC LIMIT 1) AS score \nFROM user_scores s1 \nGROUP BY s1.user_id\nORDER BY s1.score DESC \nLIMIT 5\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14971/"
] |
118,458
|
<p>Along the lines of my previous <a href="https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>
<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>
<p>into:</p>
<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>
<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
|
[
{
"answer_id": 118462,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 4,
"selected": true,
"text": "csv import csv\nwriter = csv.writer(open(\"some.csv\", \"wb\"))\nwriter.writerow(the_list)\n StringIO f = StringIO.StringIO()\nwriter = csv.writer(f)\nwriter.writerow(the_list)\nprint f.getvalue()\n a,\"one \"\"two\"\" three\",\"foo, bar\",\"both\"\"'\" csv dialect quotechar escapechar class SomeDialect(csv.excel):\n delimiter = ','\n quotechar = '\"'\n escapechar = \"\\\\\"\n doublequote = False\n lineterminator = '\\n'\n quoting = csv.QUOTE_MINIMAL\n\nf = cStringIO.StringIO()\nwriter = csv.writer(f, dialect=SomeDialect)\nwriter.writerow(the_list)\nprint f.getvalue()\n a,one \\\"two\\\" three,\"foo, bar\",both\\\"'"
},
{
"answer_id": 118625,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "def quote(s):\n if \"'\" in s or '\"' in s or \",\" in str(s):\n return repr(s)\n return s\n >>> x= ['a', 'one \"two\" three', 'foo, bar', 'both\"\\'']\n>>> print \", \".join( map(quote,x) )\na, 'one \"two\" three', 'foo, bar', 'both\"\\''\n"
},
{
"answer_id": 121745,
"author": "Alec Thomas",
"author_id": 7980,
"author_profile": "https://Stackoverflow.com/users/7980",
"pm_score": 2,
"selected": false,
"text": ">>> print \"that's interesting\".encode('string_escape')\nthat\\'s interesting\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
118,463
|
<p>We are looking to do some heavy security requirements on our project, and we need to do a lot of encryption that is highly performant.</p>
<p>I think that I know that PKI is much slower and more complex than symmetric encryption, but I can't find the numbers to back up my feelings.</p>
|
[
{
"answer_id": 118481,
"author": "Cristian Ciupitu",
"author_id": 12892,
"author_profile": "https://Stackoverflow.com/users/12892",
"pm_score": 4,
"selected": false,
"text": "speed [dave@hal9000 ~]$ openssl speed aes-128-cbc\nDoing aes-128 cbc for 3s on 16 size blocks: 26126940 aes-128 cbc's in 3.00s\nDoing aes-128 cbc for 3s on 64 size blocks: 7160075 aes-128 cbc's in 3.00s\n...\nThe 'numbers' are in 1000s of bytes per second processed.\ntype 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes\naes-128 cbc 139343.68k 152748.27k 155215.70k 155745.61k 157196.29k\n\n\n[dave@hal9000 ~]$ openssl speed rsa2048\nDoing 2048 bit private rsa's for 10s: 9267 2048 bit private RSA's in 9.99s\nDoing 2048 bit public rsa's for 10s: 299665 2048 bit public RSA's in 9.99s\n...\n sign verify sign/s verify/s\nrsa 2048 bits 0.001078s 0.000033s 927.6 29996.5\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150/"
] |
118,474
|
<p>Has anybody established a good naming convention for action in MVC? I was specifically looking at ASP.net MVC but it is a general question. For instance I have an action which displays the login screen (Login) and one which process the login request from that page (LoginTest). I'm not keen on the names and I have a lot of the applicaiton left to write. </p>
|
[
{
"answer_id": 120227,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 7,
"selected": true,
"text": "* Index - the main \"landing\" page. This is also the default endpoint.\n* List - a list of whatever \"thing\" you're showing them - like a list of Products.\n* Show - a particular item of whatever \"thing\" you're showing them (like a Product)\n* Edit - an edit page for the \"thing\"\n* New - a create page for the \"thing\"\n* Create - creates a new \"thing\" (and saves it if you're using a DB)\n* Update - updates the \"thing\"\n* Delete - deletes the \"thing\"\n * http://mysite/forum/group/list - shows all the groups in my forum\n* http://mysite/forum/forums/show/1 - shows all the topics in forum id=1\n* http://mysite/forums/topic/show/20 - shows all the posts for topic id=20\n"
},
{
"answer_id": 30370417,
"author": "Grilse",
"author_id": 1171227,
"author_profile": "https://Stackoverflow.com/users/1171227",
"pm_score": 2,
"selected": false,
"text": "\nHTTP Verb Path Controller#Action Used for\nGET /photos photos#index display a list of all photos\nGET /photos/new photos#new return an HTML form for creating a new photo\nPOST /photos photos#create create a new photo\nGET /photos/:id photos#show display a specific photo\nGET /photos/:id/edit photos#edit return an HTML form for editing a photo\nPATCH/PUT /photos/:id photos#update update a specific photo\nDELETE /photos/:id photos#destroy delete a specific photo\n"
},
{
"answer_id": 38994001,
"author": "Murat Yıldız",
"author_id": 1604048,
"author_profile": "https://Stackoverflow.com/users/1604048",
"pm_score": 1,
"selected": false,
"text": "MVC Action"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
118,487
|
<p>Sorry the title isn't more help. I have a database of media-file URLs that came from two sources: </p>
<p>(1) RSS feeds and (2) manual entries. </p>
<p>I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '<code>urls</code>' has columns <code>'url, feed_id, timestamp'</code>. </p>
<p><code>feed_id=''</code> for any URL that was entered manually.</p>
<p>How would I write the query? Remember, I want the ten most-recent urls, but only one from any single <code>feed_id</code>.</p>
|
[
{
"answer_id": 118523,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": " (SELECT \n url, feed_id, timestamp \n FROM rss_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nUNION\n (SELECT \n url, feed_id, timestamp \n FROM manual_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nORDER BY timestamp DESC\nLIMIT 10\n"
},
{
"answer_id": 118621,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "select p.* from programs p\nleft join \n(\n select max(id) id1 from programs\n where feed_id <> 0\n group by feed_id\n order by max(id) desc\n limit 10\n) t on id1 = id\nwhere id1 is not null or feed_id = 0 \norder by id desc\nlimit 10;\n (\nselect \n feed_id, url, dt \n from feeds \n where feed_id = ''\n order by dt desc \n limit 10\n)\nunion\n(\n\nselect feed_id, min(url), max(dt) \n from feeds\n where feed_id <> '' \n group by feed_id\n order by dt desc \n limit 10\n)\norder by dt desc\nlimit 10\n"
},
{
"answer_id": 118690,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": " CREATE TABLE feed (\n feed varchar(20) NOT NULL,\n add_date datetime NOT NULL,\n info varchar(45) NOT NULL,\n PRIMARY KEY (feed,add_date);\n select f2.*\n from (select feed, max(add_date) max_date\n from feed f1\n group by feed\n order by add_date desc\n limit 10) f1\n left join feed f2 on f1.feed=f2.feed and f1.max_date=f2.add_date;\n"
},
{
"answer_id": 118722,
"author": "Doug Kaye",
"author_id": 17307,
"author_profile": "https://Stackoverflow.com/users/17307",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE programs (\n id int(11) NOT NULL auto_increment,\n feed_id int(11) NOT NULL,\n `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,\n PRIMARY KEY (id)\n) ENGINE=InnoDB;\n (SELECT feed_id,id,timestamp \n FROM programs WHERE feed_id='' \n ORDER BY timestamp DESC LIMIT 10)\nUNION\n (SELECT feed_id,min(id),max(timestamp) \n FROM programs WHERE feed_id<>'' GROUP BY feed_id \n ORDER BY timestamp DESC LIMIT 10)\nORDER BY timestamp DESC LIMIT 10;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
] |
118,490
|
<p>Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.</p>
<p>Cheers</p>
<p>Andreas</p>
|
[
{
"answer_id": 118523,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": " (SELECT \n url, feed_id, timestamp \n FROM rss_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nUNION\n (SELECT \n url, feed_id, timestamp \n FROM manual_items \n GROUP BY feed_id \n ORDER BY timestamp DESC \n LIMIT 10)\nORDER BY timestamp DESC\nLIMIT 10\n"
},
{
"answer_id": 118621,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "select p.* from programs p\nleft join \n(\n select max(id) id1 from programs\n where feed_id <> 0\n group by feed_id\n order by max(id) desc\n limit 10\n) t on id1 = id\nwhere id1 is not null or feed_id = 0 \norder by id desc\nlimit 10;\n (\nselect \n feed_id, url, dt \n from feeds \n where feed_id = ''\n order by dt desc \n limit 10\n)\nunion\n(\n\nselect feed_id, min(url), max(dt) \n from feeds\n where feed_id <> '' \n group by feed_id\n order by dt desc \n limit 10\n)\norder by dt desc\nlimit 10\n"
},
{
"answer_id": 118690,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": " CREATE TABLE feed (\n feed varchar(20) NOT NULL,\n add_date datetime NOT NULL,\n info varchar(45) NOT NULL,\n PRIMARY KEY (feed,add_date);\n select f2.*\n from (select feed, max(add_date) max_date\n from feed f1\n group by feed\n order by add_date desc\n limit 10) f1\n left join feed f2 on f1.feed=f2.feed and f1.max_date=f2.add_date;\n"
},
{
"answer_id": 118722,
"author": "Doug Kaye",
"author_id": 17307,
"author_profile": "https://Stackoverflow.com/users/17307",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE programs (\n id int(11) NOT NULL auto_increment,\n feed_id int(11) NOT NULL,\n `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,\n PRIMARY KEY (id)\n) ENGINE=InnoDB;\n (SELECT feed_id,id,timestamp \n FROM programs WHERE feed_id='' \n ORDER BY timestamp DESC LIMIT 10)\nUNION\n (SELECT feed_id,min(id),max(timestamp) \n FROM programs WHERE feed_id<>'' GROUP BY feed_id \n ORDER BY timestamp DESC LIMIT 10)\nORDER BY timestamp DESC LIMIT 10;\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
118,501
|
<p>If I was, for example, going to <em>count</em> "activities" across many computers and show a rollup of that activity, what would the database look like to store the data? </p>
<p>Simply this? Seems too simple. I'm overthinking this.</p>
<pre><code>ACTIVITYID COUNT
---------- -----
</code></pre>
|
[
{
"answer_id": 118672,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 4,
"selected": true,
"text": "LOGID (PK) ACTIVITYID SOURCE DATELOGGED\n---------- ---------- ------ ----------\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6380/"
] |
118,506
|
<p>The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.</p>
<p>I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.</p>
|
[
{
"answer_id": 118582,
"author": "Gleb Popoff",
"author_id": 18076,
"author_profile": "https://Stackoverflow.com/users/18076",
"pm_score": 2,
"selected": false,
"text": "$mysqli = new MySQLI(user,pass,db);\n\n$result = $mysqli->query(\"CALL sp_mysp()\");\n $stmt = $mysqli->prepare(\"SELECT Phone FROM MyTable WHERE Name=?\");\n\n $stmt->bind_param(\"s\", $myName);\n\n $stmt->execute();\n"
},
{
"answer_id": 120252,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": 3,
"selected": true,
"text": "mysqli fetchAll $stmt = $dbh->prepare(\"CALL sp_takes_string_returns_string(?)\");\n$value = 'hello';\n$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); \n\n// call the stored procedure\n$stmt->execute();\n\nprint \"procedure returned $value\\n\";\n"
},
{
"answer_id": 347393,
"author": "SuperRoach",
"author_id": 25031,
"author_profile": "https://Stackoverflow.com/users/25031",
"pm_score": 0,
"selected": false,
"text": "$query = \"Call HeatMatchInsert('$mMatch', '$mOpponent', '$mDate', $mPlayers, $mRound, '$mMap', '$mServer', '$mPassword', '$mGame', $mSeason, $mMatchType)\";\n"
},
{
"answer_id": 4502524,
"author": "Dan Straw",
"author_id": 345918,
"author_profile": "https://Stackoverflow.com/users/345918",
"pm_score": 3,
"selected": false,
"text": "$stmt = $dbh->prepare(\"CALL sp_takes_string_returns_string(:in_string, @out_string)\");\n$stmt->bindParam(':in_string', 'hello'); \n\n// call the stored procedure\n$stmt->execute();\n\n// fetch the output\n$outputArray = $this->dbh->query(\"select @out_string\")->fetch(PDO::FETCH_ASSOC);\n\nprint \"procedure returned \" . $outputArray['@out_string'] . \"\\n\";\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4665/"
] |
118,516
|
<p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages" rel="nofollow noreferrer">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties" rel="nofollow noreferrer">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq" rel="nofollow noreferrer">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
|
[
{
"answer_id": 118803,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": -1,
"selected": false,
"text": "import pyExcelerator\nbook = pyExcelerator.parse_xls('DJIAMovers.xls')\n"
},
{
"answer_id": 125001,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 1,
"selected": false,
"text": "import pyExcelerator\nbook = pyExcelerator.parse_xls(filename)\n data = book[0][1]\nprint 'Cell A1 of worksheet %s is: %s' % (book[0][0], repr(data[(0, 0)]))\n"
},
{
"answer_id": 694688,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 5,
"selected": false,
"text": ">>> open('ComponentReport-DJI.xls', 'rb').read(200)\n'COMPANY NAME\\tPRIMARY EXCHANGE\\tTICKER\\tSTYLE\\tICB SUBSECTOR\\tMARKET CAP RANGE\\\ntWEIGHT PCT\\tUSD CLOSE\\t\\r\\n3M Co.\\tNew York SE\\tMMM\\tN/A\\tDiversified Industria\nls\\tBroad\\t5.15676229508\\t50.33\\t\\r\\nAlcoa Inc.\\tNew York SE\\tA'\n delimiter=\"\\t\" csv.reader()"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
118,526
|
<p>How do you support optimistic / pessimistic concurrency using NHibernate?</p>
|
[
{
"answer_id": 118539,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": true,
"text": "ISession.Lock()"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
118,528
|
<h2>I've actually solved this, but I'm posting it for posterity.</h2>
<p>I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (<em>like 30 seconds for a full repaint</em>), but only when it is on one of my screens. When on the other, the repaint speed is fine.</p>
<p>I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)</p>
<p>The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.</p>
<p>I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the <em>Visible</em> property is true.</p>
<p>I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.</p>
<p>This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).</p>
<p>After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!</p>
<hr>
<p>So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>
<pre><code>class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
</code></pre>
<p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (<em>although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency</em>).</p>
<p>It is sad that such a trivially simple thing ate up so much of my time...</p>
|
[
{
"answer_id": 157386,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 7,
"selected": true,
"text": "\nclass CustomDataGridView: DataGridView\n{\n public CustomDataGridView()\n {\n DoubleBuffered = true;\n } \n}\n"
},
{
"answer_id": 1506066,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 6,
"selected": false,
"text": "typeof(DataGridView).InvokeMember(\n \"DoubleBuffered\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,\n null, \n myDataGridViewObject, \n new object[] { true });\n"
},
{
"answer_id": 10304220,
"author": "GELR",
"author_id": 1354522,
"author_profile": "https://Stackoverflow.com/users/1354522",
"pm_score": 4,
"selected": false,
"text": "DataGridView1.GetType.InvokeMember(\"DoubleBuffered\", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.SetProperty, Nothing, DataGridView1, New Object() {True})\n"
},
{
"answer_id": 15990262,
"author": "Kev",
"author_id": 745813,
"author_profile": "https://Stackoverflow.com/users/745813",
"pm_score": 3,
"selected": false,
"text": "class CustomDataGridView: DataGridView\n{\n public CustomDataGridView()\n {\n // if not remote desktop session then enable double-buffering optimization\n if (!System.Windows.Forms.SystemInformation.TerminalServerSession)\n DoubleBuffered = true;\n } \n}\n"
},
{
"answer_id": 16625788,
"author": "brtmckn",
"author_id": 2396973,
"author_profile": "https://Stackoverflow.com/users/2396973",
"pm_score": 4,
"selected": false,
"text": "DrawingControl.SetDoubleBuffered(control)\nDrawingControl.SuspendDrawing(control)\nDrawingControl.ResumeDrawing(control)\n IDisposable SuspendDrawing() ResumeDrawing() Dispose() using System.Runtime.InteropServices;\n\npublic static class DrawingControl\n{\n [DllImport(\"user32.dll\")]\n public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);\n\n private const int WM_SETREDRAW = 11;\n\n /// <summary>\n /// Some controls, such as the DataGridView, do not allow setting the DoubleBuffered property.\n /// It is set as a protected property. This method is a work-around to allow setting it.\n /// Call this in the constructor just after InitializeComponent().\n /// </summary>\n /// <param name=\"control\">The Control on which to set DoubleBuffered to true.</param>\n public static void SetDoubleBuffered(Control control)\n {\n // if not remote desktop session then enable double-buffering optimization\n if (!System.Windows.Forms.SystemInformation.TerminalServerSession)\n {\n\n // set instance non-public property with name \"DoubleBuffered\" to true\n typeof(Control).InvokeMember(\"DoubleBuffered\",\n System.Reflection.BindingFlags.SetProperty |\n System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.NonPublic,\n null,\n control,\n new object[] { true });\n }\n }\n\n /// <summary>\n /// Suspend drawing updates for the specified control. After the control has been updated\n /// call DrawingControl.ResumeDrawing(Control control).\n /// </summary>\n /// <param name=\"control\">The control to suspend draw updates on.</param>\n public static void SuspendDrawing(Control control)\n {\n SendMessage(control.Handle, WM_SETREDRAW, false, 0);\n }\n\n /// <summary>\n /// Resume drawing updates for the specified control.\n /// </summary>\n /// <param name=\"control\">The control to resume draw updates on.</param>\n public static void ResumeDrawing(Control control)\n {\n SendMessage(control.Handle, WM_SETREDRAW, true, 0);\n control.Refresh();\n }\n}\n"
},
{
"answer_id": 24146731,
"author": "user3727004",
"author_id": 3727004,
"author_profile": "https://Stackoverflow.com/users/3727004",
"pm_score": 1,
"selected": false,
"text": "Private Declare Function SendMessage Lib \"user32\" _\n Alias \"SendMessageA\" _\n (ByVal hWnd As Integer, ByVal wMsg As Integer, _\n ByVal wParam As Integer, ByRef lParam As Object) _\n As Integer\n\nConst WM_SETREDRAW As Integer = &HB\n\nPublic Sub SuspendControl(this As Control)\n SendMessage(this.Handle, WM_SETREDRAW, 0, 0)\nEnd Sub\n\nPublic Sub ResumeControl(this As Control)\n RedrawControl(this, True)\nEnd Sub\n\nPublic Sub RedrawControl(this As Control, refresh As Boolean)\n SendMessage(this.Handle, WM_SETREDRAW, 1, 0)\n If refresh Then\n this.Refresh()\n End If\nEnd Sub\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/118528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5927/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.