qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
310,518 | <p>I'm digging into Reflection for the first time and I'm truely stuck. I've googled everything I can think of. I'm 90% where I wanna be now.</p>
<p>I'm trying to return the value of a Property in a custom class through Reflection.</p>
<p>Here's my class declaration:</p>
<pre><code>Public Class Class2
Private newPropertyValue2 As String
Public Property NewProperty2() As String
Get
Return newPropertyValue2
End Get
Set(ByVal value As String)
newPropertyValue2 = value
End Set
End Property
End Class
</code></pre>
<p>The class I've written to look at the class through reflection looks like this:</p>
<pre><code>Public Class ObjectCompare
Private _OriginalObject As PropertyInfo()
Public Property OriginalObject() As PropertyInfo()
Get
Return _OriginalObject
End Get
Set(ByVal value As PropertyInfo())
_OriginalObject = value
End Set
End Property
Public Sub CompareObjects()
Dim property_value As Object
For i As Integer = 0 To OriginalObject.Length - 1
If OriginalObject(i).GetIndexParameters().Length = 0 Then
Dim propInfo As PropertyInfo = OriginalObject(i)
Try
property_value = propInfo.GetValue(Me, Nothing)
Catch ex As TargetException
End Try
End If
Next
End Sub
End Class
</code></pre>
<p>I put a breakpoint on the property_value = propInfo.GetValue(Me, Nothing) line to see what the result is.</p>
<p>Here's how I call my code:</p>
<pre><code>Dim test As New Class2
test.NewProperty2 = "2"
Dim go As New ObjectCompare
Dim propInf As PropertyInfo()
propInf = test.GetType.GetProperties()
go.OriginalObject = propInf
go.CompareObjects()
</code></pre>
<p>Through reflection I can see the PropertyName and Type, all I need is the value of the Property! Now when I get to the breakpoint, I get a TargetException and the error message says "Object does not match target type." Its now 1AM in the morning and I'm wrecked, any help right now would be appreciated. I've searched MSDN and Google to death and then on last time for fun ;)</p>
| [
{
"answer_id": 310639,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "Me ObjectCompare PropertyInfo Class2 PropertyInfo Public Sub CompareObjects(ByVal It as Object)\n Dim property_value As Object\n\n For i As Integer = 0 To OriginalObject.Length - 1\n If OriginalObject(i).GetIndexParameters().Length = 0 Then\n Dim propInfo As PropertyInfo = OriginalObject(i)\n\n Try\n property_value = propInfo.GetValue(It, Nothing)\n Catch ex As TargetException\n End Try \n End If\n Next\nEnd Sub\n\ngo.CompareObjects(test)\n"
},
{
"answer_id": 310648,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 1,
"selected": false,
"text": " Dim test As New Class2\n test.NewProperty2 = \"2\"\n\n\n Dim go As New ObjectCompare\n go.CompareObjects(test)\n Public Class Class2\n Private newPropertyValue2 As String\n\n Public Property NewProperty2() As String\n Get\n Return newPropertyValue2\n End Get\n Set(ByVal value As String)\n newPropertyValue2 = value\n End Set\n End Property\nEnd Class\n Public Class ObjectCompare\n\n Public Sub CompareObjects(ByVal MyType As Object)\n\n For Each Prop In MyType.GetType().GetProperties()\n Dim value = Prop.GetValue(MyType, Nothing)\n Console.WriteLine(value)\n Next\n Console.ReadLine()\n End Sub\nEnd Class\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38595/"
] |
310,540 | <p>Are there any good references for best practices for storing postal addresses in an RDBMS? It seems there are lots of tradeoffs that can be made and lots of pros and cons to each to be evaluated -- surely this has been done time and time again? Maybe someone has at least written done some lessons learned somewhere?</p>
<p>Examples of the tradeoffs I am talking about are storing the zipcode as an integer vs a char field, should house number be stored as a separate field or part of address line 1, should suite/apartment/etc numbers be normalized or just stored as a chunk of text in address line 2, how do you handle zip +4 (separate fields or one big field, integer vs text)? etc. </p>
<p>I'm primarily concerned with U.S. addresses at this point but I imagine there are some best practices in regards to preparing yourself for the eventuality of going global as well (e.g. naming fields appropriately like region instead of state or postal code instead of zip code, etc.</p>
| [
{
"answer_id": 310605,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "postal-code"
},
{
"answer_id": 14954313,
"author": "GWed",
"author_id": 1085343,
"author_profile": "https://Stackoverflow.com/users/1085343",
"pm_score": 3,
"selected": false,
"text": "*********************************\n Field Type\n*********************************\n address_id (PK) int\n unit string\n building string \n street string\n city string\n region string\n country string\n address_code string\n*********************************\n"
},
{
"answer_id": 27963647,
"author": "Jowen",
"author_id": 48953,
"author_profile": "https://Stackoverflow.com/users/48953",
"pm_score": 1,
"selected": false,
"text": "Line1\nLine2\nLine3\nCity\nCountry_Province\nPostalCode\nCountryId\nOtherDetails\n"
},
{
"answer_id": 27995469,
"author": "Samm Cooper",
"author_id": 1719643,
"author_profile": "https://Stackoverflow.com/users/1719643",
"pm_score": 6,
"selected": false,
"text": "country => Country (always required, 2 character ISO code)\nname_line => Full name (default name entry)\nfirst_name => First name\nlast_name => Last name\norganisation_name => Company\nadministrative_area => State / Province / Region (ISO code when available)\nsub_administrative_area => County / District (unused)\nlocality => City / Town\ndependent_locality => Dependent locality (unused)\npostal_code => Postal code / ZIP Code\nthoroughfare => Street address\npremise => Apartment, Suite, Box number, etc.\nsub_premise => Sub premise (unused)\n locality thoroughfare"
},
{
"answer_id": 72623841,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 1,
"selected": false,
"text": "*****************************************************************\nType Field name Displayed name in your form \n*****************************************************************\nINT id (PK) \nVARCHAR(100) building Apt, office, suite, etc. (Optional)\nVARCHAR(100) street Street address \nVARCHAR(100) city City\nVARCHAR(100) state State, province or prefecture\nVARCHAR(100) zip_code Zip code \nVARCHAR(100) country Country\n*****************************************************************\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] |
310,548 | <p>I have a thread that, when its function exits its loop (the exit is triggered by an event), it does some cleanup and then sets a different event to let a master thread know that it is done.</p>
<p>However, under some circumstances, SetEvent() seems not to return after it sets the thread's 'I'm done' event.</p>
<p>This thread is part of a DLL and the problem seems to occur after the DLL has been loaded/attached, the thread started, the thread ended and the DLL detached/unloaded a number of times without the application shutting down in between. The number of times this sequence has to be repeated before this problem happens is variable.</p>
<p>In case you are skeptical that I know what I'm talking about, I have determined what's happening by bracketing the SetEvent() call with calls to OutputDebugString(). The output before SetEvent() appears. Then, the waiting thread produces output that indicates that the Event has been set.</p>
<p>However, the second call to OutputDebugString() in the exiting thread (the one AFTER SetEvent() ) never occurs, or at least its string never shows up. If this happens, the application crashes a few moments later.</p>
<p>(Note that the calls to OutputDebugString() were added after the problem started occurring, so it's unlikely to be hanging there, rather than in SetEvent().)</p>
<p>I'm not entirely sure what causes the crash, but it occurs in the same thread in which SetEvent() didn't return immediately (I've been tracking/outputting the thread IDs). I suppose it's possible that SetEvent() is finally returning, by which point the context to which it is returning is gone/invalid, but what could cause such a delay?</p>
<p>It turns out that I've been blinded by looking at this code for so long, and it didn't even occur to me to check the return code. I'm done looking at it for today, so I'll know what it's returning (<em>if</em> it's returning) on Monday and I'll edit this question with that info then.</p>
<p>Update: I changed the (master) code to wait for the thread to exit rather than for it to set the event, and removed the SetEvent() call from the slave thread. This changed the nature of the bug: now, instead of failing to return from SetEvent(), it doesn't exit the thread at all and the whole thing hangs.</p>
<p>This indicates that the problem is not with SetEvent(), but something deeper. No idea what, yet, but it's good not to be chasing down that blind alley.</p>
<p>Update (Feb 13/09):<br>
It turned out that the problem was deeper than I thought when I asked this question. jdigital (and probably others) has pretty much nailed the underlying problem: we were trying to unload a thread as part of the process of detaching a DLL.</p>
<p>This, as I didn't realize at the time, but have since found out through research here and elsewhere (Raymond Chen's blog, for example), is a Very Bad Thing.</p>
<p>The problem was, because of the way it was coded and the way it was behaving, it not obvious that that was the underlying problem - it was camouflaged as all sorts of other Bad Behaviours that I had to wade through.</p>
<p>Some of the suggestions here helped me do that, so I'm grateful to everyone who contributed. Thank you!</p>
| [
{
"answer_id": 310585,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 2,
"selected": false,
"text": "HANDLE * SetEvent"
},
{
"answer_id": 310860,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 0,
"selected": false,
"text": "Master\n{\n TerminateEvent = CreateEvent ( ... ) ;\n ThreadHandle = BeginThread ( Slave, (LPVOID) TerminateEvent ) ;\n ...\n Do some work\n ...\n SetEvent ( TerminateEvent ) ;\n WaitForSingleObject ( ThreadHandle, SOME_TIME_OUT ) ;\n CloseHandle ( TerminateEvent ) ;\n CloseHandle ( ThreadHandle ) ; \n}\n\nSlave ( LPVOID ThreadParam )\n{\n TerminateEvent = (HANDLE) ThreadParam ;\n while ( WaitForSingleObject ( TerminateEvent, SOME__SHORT_TIME_OUT ) == WAIT_TIMEOUT )\n { \n ... \n Do some work \n ...\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35305/"
] |
310,551 | <p>Omnicompletion is working, but it automatically inserts the first result.</p>
<p>What I'd like to do is open the omnicomplete menu, then be able to type to narrow down the results, then hit enter or tab or space or something to insert the selected menu item.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 310567,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 0,
"selected": false,
"text": ":he compl-current\n compl<C-X><C-P><BS>letion\n"
},
{
"answer_id": 311607,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 4,
"selected": false,
"text": ":set completeopt+=longest\n"
},
{
"answer_id": 327420,
"author": "Alexey Romanov",
"author_id": 9204,
"author_profile": "https://Stackoverflow.com/users/9204",
"pm_score": 2,
"selected": false,
"text": "set wildmenu\nset wildmode=list:longest,full\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367022/"
] |
310,557 | <p>I am trying to declare and use a class B inside of a class A
and define B outside A.<br>
I know for a fact that this is possible because Bjarne Stroustrup<br>
uses this in his book "The C++ programming language"<br>
(page 293,for example the String and Srep classes).</p>
<p>So this is my minimal piece of code that causes problems</p>
<pre><code>class A{
struct B; // forward declaration
B* c;
A() { c->i; }
};
struct A::B {
/*
* we define struct B like this becuase it
* was first declared in the namespace A
*/
int i;
};
int main() {
}
</code></pre>
<p>This code gives the following compilation errors in g++ :</p>
<pre><code>tst.cpp: In constructor ‘A::A()’:
tst.cpp:5: error: invalid use of undefined type ‘struct A::B’
tst.cpp:3: error: forward declaration of ‘struct A::B’
</code></pre>
<p>I tried to look at the C++ Faq and the closeset I got was <a href="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.12" rel="nofollow noreferrer">here</a> and <a href="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.13" rel="nofollow noreferrer">here</a> but<br>
those don't apply to my situation.<br>
I also <a href="https://stackoverflow.com/questions/237064/c-nested-classes-driving-me-crazy">read this</a> from here but it's not solving my problem.</p>
<p>Both gcc and MSVC 2005 give compiler errors on this</p>
| [
{
"answer_id": 310562,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 4,
"selected": false,
"text": "c->i struct A::B A struct A::B"
},
{
"answer_id": 310578,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 3,
"selected": false,
"text": "A::A() struct A::B class A\n{\n struct B;\n B* c;\n A();\n};\n\nstruct A::B\n{\n int i;\n};\n\nA::A() { c->i; }\n\nint main()\n{\n return 0;\n}"
},
{
"answer_id": 3965066,
"author": "Conan the Fishmonger",
"author_id": 480002,
"author_profile": "https://Stackoverflow.com/users/480002",
"pm_score": 1,
"selected": false,
"text": "class String {\n // ...\n void check(int i) const { if (i<0 || rep->sz <=i) throw Range(); }\n char read(int i) const { return rep->s[i]; }\n void write(int i, char c) { rep=rep->get_own_copy(); rep->s[i]=c; }\n ...etc...\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34051/"
] |
310,558 | <p>I have a RVDS project for a certain video decoder (its all C code),
created for ARM926EJ-S target, executed using the RVDS 2.2 simulator.
I am not using any scatterload / <configuration file> / <map file> to
mention the various memory segments in the code like Stack segment,
Heap, Data segment, Code Segment for RVDS Simulator environment.</p>
<ul>
<li>When I add or comment some code (redundant/dead code), then compile the project and execute it, the decoder exits gracefully after mentioning that an error condition has occured , which should not have been the case, as the commented/added code is redundant and does not affect the functionality at all.</li>
<li>Now if i do the operation opposite to that done in 1.) i.e. uncomment code that was commented in step 1.) and compile and execute, the decoder works perfectly fine till its logically end.</li>
<li>Same C source/header files work in a MSVC workspace just fine.</li>
</ul>
<p>I tried to debug a lot through this behaviour but i am not able to pinpoint the cause and the fix for it.</p>
<ul>
<li>Is it a case of stack corruption as i add/remove code?</li>
<li>Is any segment getting overwritten, like Stack segment overflowing into the Data segment, or code segment overflowing into the Data segment?</li>
</ul>
| [
{
"answer_id": 310562,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 4,
"selected": false,
"text": "c->i struct A::B A struct A::B"
},
{
"answer_id": 310578,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 3,
"selected": false,
"text": "A::A() struct A::B class A\n{\n struct B;\n B* c;\n A();\n};\n\nstruct A::B\n{\n int i;\n};\n\nA::A() { c->i; }\n\nint main()\n{\n return 0;\n}"
},
{
"answer_id": 3965066,
"author": "Conan the Fishmonger",
"author_id": 480002,
"author_profile": "https://Stackoverflow.com/users/480002",
"pm_score": 1,
"selected": false,
"text": "class String {\n // ...\n void check(int i) const { if (i<0 || rep->sz <=i) throw Range(); }\n char read(int i) const { return rep->s[i]; }\n void write(int i, char c) { rep=rep->get_own_copy(); rep->s[i]=c; }\n ...etc...\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
310,561 | <p>I'm looking at the MySQL docs <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html" rel="noreferrer">here</a> and trying to sort out the distinction between FOREIGN KEYs and CONSTRAINTs. I thought an FK <strong>was</strong> a constraint, but the docs seem to talk about them like they're separate things.</p>
<p>The syntax for creating an FK is (in part)...</p>
<pre><code>[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
</code></pre>
<p>So the "CONSTRAINT" clause is optional. Why would you include it or not include it? If you leave it out does MySQL create a foreign key but not a constraint? Or is it more like a "CONSTRAINT" is nothing more than a name for you FK, so if you don't specify it you get an anonymous FK?</p>
<p>Any clarification would be greatly appreciated.</p>
<p>Thanks,</p>
<p>Ethan</p>
| [
{
"answer_id": 310586,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 7,
"selected": true,
"text": "PRIMARY KEY FOREIGN KEY CHECK UNIQUE NOT NULL DEFERRABLE CONSTRAINT CONSTRAINT"
},
{
"answer_id": 34298305,
"author": "RxBx",
"author_id": 5683718,
"author_profile": "https://Stackoverflow.com/users/5683718",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE my_dbschema.my_table (\n id INT unsigned auto_increment PRIMARY KEY,\n account_nbr INT NOT NULL,\n account_name VARCHAR(50) NOT NULL,\n active_flg CHAR(1) NOT NULL DEFAULT 'Y',\n vendor_nbr INT NOT NULL,\n create_ts TIMESTAMP NOT NULL DEFAULT current_timestamp,\n create_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',\n last_upd_ts TIMESTAMP NOT NULL DEFAULT current_timestamp ON UPDATE current_timestamp,\n last_upd_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',\n UNIQUE KEY uk1_my_table(account_nbr, account_name),\n FOREIGN KEY fk1_my_table(vendor_nbr) REFERENCES vendor(vendor_nbr)\n );\n ALTER TABLE my_table DROP FOREIGN KEY fk1_my_table CREATE TABLE my_dbschema.my_table (\n id INT unsigned auto_increment PRIMARY KEY,\n account_nbr INT NOT NULL,\n account_name VARCHAR(50) NOT NULL,\n active_flg CHAR(1) NOT NULL DEFAULT 'Y',\n vendor_nbr INT NOT NULL,\n create_ts TIMESTAMP NOT NULL DEFAULT current_timestamp,\n create_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',\n last_upd_ts TIMESTAMP NOT NULL DEFAULT current_timestamp ON UPDATE current_timestamp,\n last_upd_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',\n CONSTRAINT uk1_my_table UNIQUE KEY (account_nbr, account_name),\n CONSTRAINT fk1_my_table FOREIGN KEY (vendor_nbr) REFERENCES vendor(vendor_nbr)\n );\n ALTER TABLE my_table DROP FOREIGN KEY fk1_my_table ALTER TABLE my_table DROP INDEX fk1_my_table"
},
{
"answer_id": 66265822,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "fk1_rule_child_column fk_bst_child_to_parent_column parent_table parent_column my_foreign_key customers products attributes orders customers products product_attributes customer_product_orders cust prod prod_attr cust_prod_ord"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,572 | <p>Here's the goal: to replace all standalone ampersands with &amp; but NOT replace those that are already part of an HTML entity such as &nbsp;.</p>
<p>I think I need a regular expression for PHP (preferably for preg_ functions) that will match only standalone ampersands. I just don't know how to do that with preg_replace.</p>
| [
{
"answer_id": 310577,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 4,
"selected": true,
"text": "html_entity_decode htmlentities"
},
{
"answer_id": 310632,
"author": "Doug Kaye",
"author_id": 17307,
"author_profile": "https://Stackoverflow.com/users/17307",
"pm_score": 2,
"selected": false,
"text": "//decode all entities\n$string=html_entity_decode($string,ENT_COMPAT,'UTF-8');\n\n//entity-encode only &<> and double quotes\n$string=htmlspecialchars($string,ENT_COMPAT,'UTF-8');\n"
},
{
"answer_id": 311890,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "& # an ampersand\n( \\# # a '#' character\n [1-9] # followed by a non-zero digit, \n [0-9]{1,3} # with between 2 and 4 (\\d{1,3} or \\p{IsDigit}{1,3})\n| [A-Za-z] # OR a letter (\\p{IsAlpha})\n [0-9A-Za-z]+ # followed by letters or numbers (\\p{IsAlnum}+)\n)\n; # all capped with a ';'\n & # an ampersand\n( amp | apos | gt | lt | nbsp | quot \n # standard entities\n| bull | hellip | [lr][ds]quo | [mn]dash | permil \n # some fancier ones\n| \\# # a '#' character\n [1-9] # followed by a non-zero digit, \n [0-9]{1,3} # with between 2 and 4 \n| [A-Za-z] # OR a letter\n [0-9A-Za-z]+ # followed by letters or numbers\n)\n; # all capped with a ';'\n"
},
{
"answer_id": 311904,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "htmlentities() double_encode preg_replace('/&(?!(?:[[:alpha:]][[:alnum:]]*|#(?:[[:digit:]]+|[Xx][[:xdigit:]]+));)/', '&', $txt);\n"
},
{
"answer_id": 2526290,
"author": "WhoIsRich",
"author_id": 302813,
"author_profile": "https://Stackoverflow.com/users/302813",
"pm_score": 1,
"selected": false,
"text": "$string = htmlspecialchars($string, ENT_QUOTES, \"UTF-8\", FALSE); \nfunction htmlspecialchars_custom($string)\n{\n $string = str_replace(\"\\x05\\x06\", \"\", $string);\n $string = preg_replace(\"/&([a-z\\d]{2,7}|#\\d{2,5});/i\", \"\\x05\\x06$1\", $string);\n $string = htmlspecialchars($string, ENT_QUOTES);\n $string = str_replace(\"\\x05\\x06\", \"&\", $string);\n\n return $string;\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
] |
310,576 | <p>What win32 calls can be used to detect key press events globally (not just for 1 window, I'd like to get a message EVERY time a key is pressed), from a windows service?</p>
| [
{
"answer_id": 310602,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": "LRESULT CALLBACK KeyboardProc( \n int code,\n WPARAM wParam,\n LPARAM lParam\n);\n"
},
{
"answer_id": 25185441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "using System.Runtime.InteropServices;\n [DllImport(\"user32.dll\")]\nstatic uint GetKeyState(byte virtualKeyCode);\n\n//or\n\n[DllImport(\"user32.dll\")]\nstatic uint GetAsyncKeyState(byte virtualKeyCode);\n\n//or\n\n[DllImport(\"user32.dll\")]\nstatic uint GetKeyboardState(byte[] virtualKeyCodes);\n//NOTE: The length of the byte array parameter must be always 256 bytes!\n [MarshalAs(UnmanagedType.Bool)]\n [return: MarshalAs(UnmanagedType.Bool)]\n while (boolean exression that will return false when you want to quit this loop)\n{\n if (boolean expression that will return true when particular key is **held down**) //This boolean expression calls either GetKeyState or GetAsyncKeyState with the & 0x8000 or & 0x80 after the call, and then != 0 to check for **held down** key\n while (true) //It's purpose is to wait for the same key that was held down to be released. After code execution, it will encounter the break keyword that will finish him, even though that his enter condition is true.\n if (boolean expression that will return true when the **same** particular key is **NOT** held down! (NOT held down, means that at that time, that key was released). You can copy the same condition from the first if statement, and just change **!=**, which is next to 0, to **==**, or instead add brackets to the condition '(' and ')', and in left of '(' add '!').\n {\n //Put here the code that you want to execute once, when paticular key was pressed and then released.\n break; //the while (true), which is the only way to get out of it\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3886/"
] |
310,580 | <p>Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?</p>
<p>NOTE: I don't want to set this up in my IIS settings.</p>
| [
{
"answer_id": 310636,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 7,
"selected": true,
"text": "routes.MapRoute(\n \"404-PageNotFound\",\n \"{*url}\",\n new { controller = \"StaticContent\", action = \"PageNotFound\" }\n );\n"
},
{
"answer_id": 311688,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 2,
"selected": false,
"text": "throw new HttpException(404);\n"
},
{
"answer_id": 7501840,
"author": "smdrager",
"author_id": 356550,
"author_profile": "https://Stackoverflow.com/users/356550",
"pm_score": 4,
"selected": false,
"text": "customErrors mode=\"On\" defaultRedirect=\"~/Error/Unknown\"\n error statusCode=\"404\" redirect=\"~/Error/NotFound\"\n <customErrors mode=\"On\" defaultRedirect=\"~/Error/\" redirectMode=\"ResponseRedirect\">\n <error statusCode=\"404\" redirect=\"~/Error/PageNotFound/\" />\n </customErrors>\n"
},
{
"answer_id": 12116601,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 1,
"selected": false,
"text": "Application_EndRequest MvcApplication"
},
{
"answer_id": 28577496,
"author": "Vicky",
"author_id": 2996372,
"author_profile": "https://Stackoverflow.com/users/2996372",
"pm_score": 2,
"selected": false,
"text": " <system.webServer>\n<httpErrors errorMode=\"Custom\" existingResponse=\"Replace\">\n <remove statusCode=\"404\" />\n <error statusCode=\"404\" responseMode=\"ExecuteURL\" path=\"/Test/PageNotFound\" />\n <remove statusCode=\"500\" />\n <error statusCode=\"500\" responseMode=\"ExecuteURL\" path=\"/Test/PageNotFound\" />\n</httpErrors>\n<modules>\n <remove name=\"FormsAuthentication\" />\n</modules>\n"
},
{
"answer_id": 30304457,
"author": "Laxmeesh Joshi",
"author_id": 2987014,
"author_profile": "https://Stackoverflow.com/users/2987014",
"pm_score": 0,
"selected": false,
"text": "public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {\n public void OnException(ExceptionContext filterContext) {\n filterContext.Result = new RedirectResult(\"~/Content/RouteNotFound.html\");\n }\n}\n"
},
{
"answer_id": 32985780,
"author": "solanki dev",
"author_id": 4782481,
"author_profile": "https://Stackoverflow.com/users/4782481",
"pm_score": 1,
"selected": false,
"text": "RouterConfig.cs routes.MapRoute(\n name: \"Error\",\n url: \"{id}\",\n defaults: new\n {\n controller = \"Error\",\n action = \"PageNotFound\"\n\n });\n"
},
{
"answer_id": 35826097,
"author": "MSDs",
"author_id": 3090094,
"author_profile": "https://Stackoverflow.com/users/3090094",
"pm_score": 3,
"selected": false,
"text": "protected void Application_Error(object sender, EventArgs e)\n{\n Exception lastErrorInfo = Server.GetLastError();\n Exception errorInfo = null;\n\n bool isNotFound = false;\n if (lastErrorInfo != null)\n {\n errorInfo = lastErrorInfo.GetBaseException();\n var error = errorInfo as HttpException;\n if (error != null)\n isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;\n }\n if (isNotFound)\n {\n Server.ClearError();\n Response.Redirect(\"~/Error/NotFound\");// Do what you need to render in view\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
310,583 | <p>I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.</p>
| [
{
"answer_id": 310588,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": -1,
"selected": false,
"text": "<script src=\"...\">"
},
{
"answer_id": 310590,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "function loadJSInclude(scriptPath, callback)\n{\n var scriptNode = document.createElement('SCRIPT');\n scriptNode.type = 'text/javascript';\n scriptNode.src = scriptPath;\n\n var headNode = document.getElementsByTagName('HEAD');\n if (headNode[0] != null)\n headNode[0].appendChild(scriptNode);\n\n if (callback != null) \n {\n scriptNode.onreadystagechange = callback; \n scriptNode.onload = callback;\n }\n}\n var callbackMethod = function ()\n{\n // Code to do after loading swfObject\n}\n\n// Include SWFObject if its needed\nif (typeof(SWFObject) == 'undefined') \n loadJSInclude('/js/swfObject.js', callbackMethod);\nelse\n callbackMethod();\n"
},
{
"answer_id": 603982,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 0,
"selected": false,
"text": "function mapsLoaded() {\n var map = new google.maps.Map2(document.getElementById(\"map\"));\n map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);\n}\n\nfunction loadMaps() {\n google.load(\"maps\", \"2\", {\"callback\" : mapsLoaded});\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/310583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
310,589 | <p>In our MOSS '07 site we have a page that contains just a Page Viewer web part in it that points to a site on another server. However, I've noticed that on that page (and any others that have a Page Viewer web part on it) our drop down menus and hover effects are <strong>super slow</strong> and completely max out the CPU on the visitor's computer (process is <strong>IExplorer</strong>.)</p>
<p>Through testing, I was able to determine that it doesn't matter what URL the web part is pointed to...just having the Iframe on the page seems to cause it (just setting the viewer to load Google's homepage--which is probably the simplest site I know--still causes the problem). If I go and remove the web part, the menus start functioning just fine again.</p>
<p>I attached a debugger to the process and stepped through the <code>Menu_HoverStatic</code> and called functions and it seems to have a hard time when assigning <code>panel.scrollTop</code> to zero in the <code>PopOut_Show</code> function.</p>
<p>Has anyone else noticed this? ...perhaps found a solution to it? I can't find where to edit <code>PopOut_Show</code> function on our server (I think it's a resource in one of the .NET DLLs) or else I'd just comment out that line as I don't think it's really important anyway...at least on our site.</p>
<p>I really like the ability to have web pages from another server hosted in our SharePoint site, but the performance on the hovers is agonizing... and, honestly, unacceptable. Depending on the resources of the user's computer, the hover effects can take 15 seconds to complete at times!!!!</p>
<p>Any suggestions would be really appreciated!</p>
| [
{
"answer_id": 310588,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": -1,
"selected": false,
"text": "<script src=\"...\">"
},
{
"answer_id": 310590,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "function loadJSInclude(scriptPath, callback)\n{\n var scriptNode = document.createElement('SCRIPT');\n scriptNode.type = 'text/javascript';\n scriptNode.src = scriptPath;\n\n var headNode = document.getElementsByTagName('HEAD');\n if (headNode[0] != null)\n headNode[0].appendChild(scriptNode);\n\n if (callback != null) \n {\n scriptNode.onreadystagechange = callback; \n scriptNode.onload = callback;\n }\n}\n var callbackMethod = function ()\n{\n // Code to do after loading swfObject\n}\n\n// Include SWFObject if its needed\nif (typeof(SWFObject) == 'undefined') \n loadJSInclude('/js/swfObject.js', callbackMethod);\nelse\n callbackMethod();\n"
},
{
"answer_id": 603982,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 0,
"selected": false,
"text": "function mapsLoaded() {\n var map = new google.maps.Map2(document.getElementById(\"map\"));\n map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);\n}\n\nfunction loadMaps() {\n google.load(\"maps\", \"2\", {\"callback\" : mapsLoaded});\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30866/"
] |
310,595 | <p>I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both.</p>
<p>A few complications include that I it could be in a zip file (in this cases the path will be an internal path)</p>
| [
{
"answer_id": 310625,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 5,
"selected": true,
"text": "/// <summary>\n/// Returns whether the given path/file is a link\n/// </summary>\n/// <param name=\"shortcutFilename\"></param>\n/// <returns></returns>\npublic static bool IsLink(string shortcutFilename)\n{\n string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);\n string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);\n\n Shell32.Shell shell = new Shell32.ShellClass();\n Shell32.Folder folder = shell.NameSpace(pathOnly);\n Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);\n if (folderItem != null)\n {\n return folderItem.IsLink;\n }\n return false; // not found\n}\n /// <summary>\n /// If path/file is a link returns the full pathname of the target,\n /// Else return the original pathnameo \"\" if the file/path can't be found\n /// </summary>\n /// <param name=\"shortcutFilename\"></param>\n /// <returns></returns>\n public static string GetShortcutTarget(string shortcutFilename)\n {\n string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);\n string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);\n\n Shell32.Shell shell = new Shell32.ShellClass();\n Shell32.Folder folder = shell.NameSpace(pathOnly);\n Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);\n if (folderItem != null)\n {\n if (folderItem.IsLink)\n {\n Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;\n return link.Path;\n }\n return shortcutFilename;\n }\n return \"\"; // not found\n }\n"
},
{
"answer_id": 71645116,
"author": "Obsidian",
"author_id": 10150864,
"author_profile": "https://Stackoverflow.com/users/10150864",
"pm_score": 0,
"selected": false,
"text": "FileInfo DirectoryInfo LinkTarget LinkTarget null var info = new DirectoryInfo(\"path/to/the/folder/shortcut\");\nbool isShortcut = info.LinkTarget != null;\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
310,599 | <p>It's simple enough to code up a class to store/validate something like <code>192.168.0.0/16</code>, but I was curious if a native type for this already existed in .NET? I would imagine it would work a lot like <code>IPAddress</code>:</p>
<pre><code>CIDR subnet = CIDR.Parse("192.168.0.0/16");
</code></pre>
<p>Basically it just needs to make sure you're working with an IPv4 or IPv6 address and then that the number of bits your specifying is valid for that type.</p>
| [
{
"answer_id": 2239906,
"author": "Koen Zomers",
"author_id": 1271303,
"author_profile": "https://Stackoverflow.com/users/1271303",
"pm_score": 5,
"selected": false,
"text": "IPNetwork ipnetwork = IPNetwork.Parse(\"192.168.168.100/24\");\n\nConsole.WriteLine(\"Network : {0}\", ipnetwork.Network);\nConsole.WriteLine(\"Netmask : {0}\", ipnetwork.Netmask);\nConsole.WriteLine(\"Broadcast : {0}\", ipnetwork.Broadcast);\nConsole.WriteLine(\"FirstUsable : {0}\", ipnetwork.FirstUsable);\nConsole.WriteLine(\"LastUsable : {0}\", ipnetwork.LastUsable);\nConsole.WriteLine(\"Usable : {0}\", ipnetwork.Usable);\nConsole.WriteLine(\"Cidr : {0}\", ipnetwork.Cidr);\n Network : 192.168.168.0\nNetmask : 255.255.255.0\nBroadcast : 192.168.168.255\nFirstUsable : 192.168.168.1\nLastUsable : 192.168.168.254\nUsable : 254\nCidr : 24\n"
},
{
"answer_id": 63161497,
"author": "Mark G",
"author_id": 310601,
"author_profile": "https://Stackoverflow.com/users/310601",
"pm_score": 3,
"selected": false,
"text": "var addr = IPAddress.Parse(\"192.168.0.0\");\nvar mask = 16;\nvar test = new IPNetwork(addr, mask).Contains(context.Connection.RemoteIpAddress);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
310,629 | <p>I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.</p>
<p>In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.</p>
<p>Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?</p>
| [
{
"answer_id": 310635,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 4,
"selected": true,
"text": "from cStringIO import StringIO\n\ns = \"My very long string I want to read like a file\"\nfile_like_string = StringIO(s)\ndata = file_like_string.read(10)\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
310,634 | <p>PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just do</p>
<pre><code>foreach (array/hash as $key => $value)
</code></pre>
<p>In Ruby there are a bunch of ways to do this sort of thing:</p>
<pre><code>array.length.times do |i|
end
array.each
array.each_index
for i in array
</code></pre>
<p>Hashes make more sense, since I just always use</p>
<pre><code>hash.each do |key, value|
</code></pre>
<p>Why can't I do this for arrays? If I want to remember just one method, I guess I can use <code>each_index</code> (since it makes both the index and value available), but it's annoying to have to do <code>array[index]</code> instead of just <code>value</code>.</p>
<hr>
<p>Oh right, I forgot about <code>array.each_with_index</code>. However, this one sucks because it goes <code>|value, key|</code> and <code>hash.each</code> goes <code>|key, value|</code>! Is this not insane?</p>
| [
{
"answer_id": 310638,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 10,
"selected": true,
"text": "array = [1, 2, 3, 4, 5, 6]\narray.each { |x| puts x }\n\n# Output:\n\n1\n2\n3\n4\n5\n6\n array = [\"A\", \"B\", \"C\"]\narray.each_with_index {|val, index| puts \"#{val} => #{index}\" }\n\n# Output:\n\nA => 0\nB => 1\nC => 2\n"
},
{
"answer_id": 310644,
"author": "J Cooper",
"author_id": 38803,
"author_profile": "https://Stackoverflow.com/users/38803",
"pm_score": 4,
"selected": false,
"text": "ary.each_with_index { |val, idx| # ...\n"
},
{
"answer_id": 310661,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 7,
"selected": false,
"text": "each each_ with _index each_index map select inject"
},
{
"answer_id": 311364,
"author": "Brent.Longborough",
"author_id": 9634,
"author_profile": "https://Stackoverflow.com/users/9634",
"pm_score": 3,
"selected": false,
"text": "class Hash\n def each_pairwise\n self.each { | x, y |\n yield [x, y]\n }\n end\nend\n\nclass Array\n def each_pairwise\n self.each_with_index { | x, y |\n yield [y, x]\n }\n end\nend\n\n[\"a\",\"b\",\"c\"].each_pairwise { |x,y|\n puts \"#{x} => #{y}\"\n}\n\n{\"a\" => \"Aardvark\",\"b\" => \"Bogle\",\"c\" => \"Catastrophe\"}.each_pairwise { |x,y|\n puts \"#{x} => #{y}\"\n}\n"
},
{
"answer_id": 438041,
"author": "maxhawkins",
"author_id": 53589,
"author_profile": "https://Stackoverflow.com/users/53589",
"pm_score": 2,
"selected": false,
"text": "require 'enumerator' \n\n['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts \"#{x} => #{y}\" }\n\n# is equivalent to...\n\n{'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts \"#{x} => #{y}\" }\n # Ruby 1.8\n[1,2,[1,2,3]].flatten\n=> [1,2,1,2,3]\n\n# Ruby 1.9\n[1,2,[1,2,3]].flatten(0)\n=> [1,2,[1,2,3]]\n"
},
{
"answer_id": 691798,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "Array |value,index| Hash |key,value| |value,index| key => value hash[key] = value for index in 0 ... array.size\n puts \"array[#{index}] = #{array[index].inspect}\"\nend\n for key in hash.keys.sort\n puts \"hash[#{key.inspect}] = #{hash[key].inspect}\"\nend\n (1..10).each{|i| puts \"i=#{i}\" }\n (1..10).to_a.reverse.each{|i| puts \"i=#{i}\" }\n (a=*1..10).each{|i| puts \"i=#{i}\" }\n (a=*1..10).reverse.each{|i| puts \"i=#{i}\" }\n (*1..10).each{|i| puts \"i=#{i}\" }\n(*1..10).reverse.each{|i| puts \"i=#{i}\" }\n#\n(1..10).step(1){|i| puts \"i=#{i}\" }\n(1..10).step(-1){|i| puts \"i=#{i}\" }\n#\n(1..10).each{|i| puts \"i=#{i}\" }\n(10..1).each{|i| puts \"i=#{i}\" } # I don't want this though. It's dangerous\n class Range\n\n def each_reverse(&block)\n self.to_a.reverse.each(&block)\n end\n\nend\n pred"
},
{
"answer_id": 995448,
"author": "Dave Everitt",
"author_id": 123033,
"author_profile": "https://Stackoverflow.com/users/123033",
"pm_score": 3,
"selected": false,
"text": "each_slice ['Home', '/', 'Page two', 'two', 'Test', 'test'].each_slice(2) do|label,link|\n li {a label, :href => link}\nend\n"
},
{
"answer_id": 26099644,
"author": "Amjed Shareef",
"author_id": 2912467,
"author_profile": "https://Stackoverflow.com/users/2912467",
"pm_score": 2,
"selected": false,
"text": "a = [ \"a\", \"b\", \"c\" ]\na.each_index {|x| print x, \" -- \" }\n 0 -- 1 -- 2 --\n"
},
{
"answer_id": 32145814,
"author": "Jake",
"author_id": 4976373,
"author_profile": "https://Stackoverflow.com/users/4976373",
"pm_score": 4,
"selected": false,
"text": "array.each\n array.each_index\n for i in array\n array.length.times do | i |\n"
},
{
"answer_id": 61429880,
"author": "tanius",
"author_id": 1270008,
"author_profile": "https://Stackoverflow.com/users/1270008",
"pm_score": 2,
"selected": false,
"text": "class Array\n\n # Iterate over index and value. The intention of this\n # method is to provide polymorphism with Hash.\n #\n def each_pair #:yield:\n each_with_index {|e, i| yield(i,e) }\n end\n\nend\n Hash#each_pair Hash#each Array#each_pair Array#each_with_index Hash#each my_array = ['Hello', 'World', '!']\nmy_array.each_pair { |key, value| pp \"#{key}, #{value}\" }\n\n# result: \n\"0, Hello\"\n\"1, World\"\n\"2, !\"\n\nmy_hash = { '0' => 'Hello', '1' => 'World', '2' => '!' }\nmy_hash.each_pair { |key, value| pp \"#{key}, #{value}\" }\n\n# result: \n\"0, Hello\"\n\"1, World\"\n\"2, !\"\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25068/"
] |
310,642 | <p>I'm creating a list of the Slices in my Merb app, like this:</p>
<blockquote>
<p>Merb::Slices.each_slice do |slice|</p>
</blockquote>
<p>I'd like to get the list of dependencies for each of this slice, any idea how to access it?</p>
<p>I'm still reading merb code, solution might come soon ;)</p>
| [
{
"answer_id": 310671,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 0,
"selected": false,
"text": "/config/dependencies.rb merb -i >> Merb.methods.sort\n=> [\"<\", \"<=\", \"<=>\", \"==\", \"===\", \"=~\", \">\", \">=\", \"JSON\", \"__caller_info__\", \"__caller_lines__\", \"__id__\", \"__profile__\", \"__send__\", \"abstract_method\", \"adapter\", \"adapter=\", \"add_generators\", \"add_mime_type\", \"add_rakefiles\", \"ancestors\", \"args_and_options\", \"assigns\", \"at_exit\", \"at_exit_procs\", \"autoload\", \"autoload?\", \"available_accepts\", \"available_mime_types\", \"b64encode\", \"blank?\", \"bundled?\", \"class\", \"class_eval\", \"class_variable_defined?\", \"class_variables\", \"clone\", \"config\", \"const_defined?\", \"const_get\", \"const_missing\", \"const_set\", \"constants\", \"context\", \"debugger\", \"decode64\", \"decode_b\", \"deep_clone\", \"deferred_actions\", \"dependencies\", \"dependency\", \"describe\", \"dir_for\", \"disable\", \"disabled?\", \"disabled_components\", \"disabled_components=\", \"display\", \"dup\", \"encode64\", \"encoded_hash\", \"enforce!\", \"enum_for\", \"env\", \"env?\", \"environment\", \"environment=\", \"environment_info\", \"environment_info=\", \"eql?\", \"equal?\", \"exception\", \"exiting\", \"exiting=\", \"extend\", \"extract_options_from_args!\", \"fatal!\", \"find_const\", \"forking_environment?\", \"framework_root\", \"freeze\", \"frozen?\", \"full_const_get\", \"full_const_set\", \"generators\", \"given\", \"glob_for\", \"hash\", \"id\", \"in?\", \"include?\", \"included_modules\", \"inline\", \"inspect\", \"instance_eval\", \"instance_method\", \"instance_methods\", \"instance_of?\", \"instance_variable_defined?\", \"instance_variable_get\", \"instance_variable_set\", \"instance_variables\", \"is_a?\", \"is_haml?\", \"j\", \"jj\", \"kind_of?\", \"klass_hashes\", \"klass_hashes=\", \"load_config\", \"load_dependencies\", \"load_dependency\", \"load_paths\", \"load_paths=\", \"log_path\", \"log_stream\", \"logger\", \"make_module\", \"merb\", \"merge_env\", \"meta_class\", \"method\", \"method_defined?\", \"methods\", \"mime_transform_method\", \"module_eval\", \"modules\", \"name\", \"nil?\", \"object_id\", \"on_jruby?\", \"on_windows?\", \"options\", \"orm\", \"orm=\", \"orm_generator_scope\", \"present?\", \"print_colorized_backtrace\", \"private_class_method\", \"private_instance_methods\", \"private_method_defined?\", \"private_methods\", \"protected_instance_methods\", \"protected_method_defined?\", \"protected_methods\", \"public_class_method\", \"public_instance_methods\", \"public_method_defined?\", \"public_methods\", \"push_path\", \"quacks_like?\", \"rakefiles\", \"reload\", \"remove_mime_type\", \"remove_paths\", \"rescue_require\", \"reset_logger!\", \"respond_to?\", \"restart_environment\", \"root\", \"root=\", \"root_path\", \"send\", \"share_as\", \"share_examples_for\", \"shared_examples_for\", \"should\", \"should_not\", \"singleton_methods\", \"start\", \"start_environment\", \"started\", \"started=\", \"started?\", \"taguri\", \"taguri=\", \"taint\", \"tainted?\", \"template_engine\", \"template_engine=\", \"test_framework\", \"test_framework=\", \"test_framework_generator_scope\", \"testing?\", \"to_a\", \"to_enum\", \"to_json\", \"to_s\", \"to_yaml\", \"to_yaml_properties\", \"to_yaml_style\", \"track_dependency\", \"trap\", \"try_dup\", \"type\", \"untaint\", \"use_orm\", \"use_template_engine\", \"use_test\", \"use_testing_framework\", \"yaml_as\", \"yaml_tag_class_name\", \"yaml_tag_read_class\"]\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16974/"
] |
310,650 | <p>I'm retrieving a gzipped web page via curl, but when I output the retrieved content to the browser I just get the raw gzipped data. How can I decode the data in PHP?</p>
<p>One method I found was to write the content to a tmp file and then ...</p>
<pre><code>$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);
</code></pre>
<p>.... but man, there's got to be a better way.</p>
<p>Edit: This isn't a file, but a gzipped html page returned by a web server.</p>
| [
{
"answer_id": 2849331,
"author": "Jonas Lejon",
"author_id": 117283,
"author_profile": "https://Stackoverflow.com/users/117283",
"pm_score": 8,
"selected": true,
"text": "curl_setopt($ch, CURLOPT_ENCODING , \"gzip\");\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39539/"
] |
310,652 | <p>I am using the functions strpos(string, string) in javascript. In Firefox, Opera and IE the page loads fine, but in Chrome I get the error: Uncaught ReferenceError: strpos is not defined. The page I am working on is <a href="http://seniorproject.korykirk.com/0xpi2.php" rel="nofollow noreferrer">http://seniorproject.korykirk.com/0xpi2.php</a></p>
| [
{
"answer_id": 310665,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 4,
"selected": false,
"text": "haystack.indexOf(needle)"
},
{
"answer_id": 3839607,
"author": "TRiG",
"author_id": 209139,
"author_profile": "https://Stackoverflow.com/users/209139",
"pm_score": 2,
"selected": false,
"text": "strpos()"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,664 | <p>I'm having some trouble with ASP.NET MVC Beta, and the idea of making routes, controller actions, parameters on those controller actions and Html.ActionLinks all work together. I have an application that I'm working on where I have a model object called a Plot, and a corresponding PlotController. When a user creates a new Plot object, a URL friendly name gets generated (<a href="https://stackoverflow.com/questions/37809/how-do-i-generate-a-friendly-url-in-c">i.e.</a>). I would then like to generate a "List" of the Plots that belong to the user, each of which would be a link that would navigate the user to a view of the details of that Plot. I want the URL for that link to look something like this: <a href="http://myapp.com/plot/my-plot-name" rel="nofollow noreferrer">http://myapp.com/plot/my-plot-name</a>. I've attempted to make that happen with the code below, but it doesn't seem to be working, and I can't seem to find any good samples that show how to make all of this work together.</p>
<p>My Route definition:</p>
<pre><code>routes.MapRoute( "PlotByName", "plot/{name}", new { controller = "Plot", action = "ViewDetails" } );
</code></pre>
<p>My ControllerAction:</p>
<pre><code>[Authorize]
public ActionResult ViewDetails( string plotName )
{
ViewData["SelectedPlot"] = from p in CurrentUser.Plots where p.UrlFriendlyName == plotName select p;
return View();
}
</code></pre>
<p>As for the ActionLink, I'm not really sure what that would look like to generate the appropriate URL.</p>
<p>Any assistance would be greatly appreciated.</p>
| [
{
"answer_id": 310709,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": true,
"text": "<%= Html.ActionLink(\"Click Here\", \"ViewDetails\", \"Plot\", new { name=\"my-plot-name\" }, null)%>\n"
},
{
"answer_id": 310818,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute( \n \"PlotByName\", \n \"plot/{name}\", \n new { controller = \"Plot\", action = \"ViewDetails\", name = null }\n);\n public ActionResult ViewDetails(string name ) { ... }\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18831/"
] |
310,669 | <p>Does anyone have any idea why the following code sample fails with an XmlException "Data at the root level is invalid. Line 1, position 1."</p>
<pre><code>var body = "<?xml version="1.0" encoding="utf-16"?><Report> ......"
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.LoadXml(body);
</code></pre>
| [
{
"answer_id": 310708,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "MemoryStream stream = new MemoryStream();\n byte[] data = body.PayloadEncoding.GetBytes(body.Payload);\n stream.Write(data, 0, data.Length);\n stream.Seek(0, SeekOrigin.Begin);\n\n XmlTextReader reader = new XmlTextReader(stream);\n\n // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads\n bodyDoc.Load(reader);\n"
},
{
"answer_id": 1033807,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 7,
"selected": false,
"text": "string xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" ?>\\n<event>This is a Test</event>\";\nXmlDocument xmlDoc = new XmlDocument();\nxmlDoc.LoadXml(xml);\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n string xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" ?>\\n<event>This is a Test</event>\";\n\n// Encode the XML string in a UTF-8 byte array\nbyte[] encodedString = Encoding.UTF8.GetBytes(xml);\n\n// Put the byte array into a stream and rewind it to the beginning\nMemoryStream ms = new MemoryStream(encodedString);\nms.Flush();\nms.Position = 0;\n\n// Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes\nXmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(ms);\n"
},
{
"answer_id": 1443494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "XmlDocument bodyDoc = new XmlDocument();\nbodyDoc.XMLResolver = null;\nbodyDoc.Load(body);\n"
},
{
"answer_id": 4327481,
"author": "keithl8041",
"author_id": 119761,
"author_profile": "https://Stackoverflow.com/users/119761",
"pm_score": 2,
"selected": false,
"text": "var xdoc = new XmlDocument { XmlResolver = null }; \nxdoc.LoadXml(xmlFragment);\n"
},
{
"answer_id": 7915058,
"author": "Gunner",
"author_id": 1016351,
"author_profile": "https://Stackoverflow.com/users/1016351",
"pm_score": 5,
"selected": false,
"text": "LoadXml() Load() XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(\"sample.xml\");\n"
},
{
"answer_id": 16605505,
"author": "Sander Kouwenhoven",
"author_id": 2060906,
"author_profile": "https://Stackoverflow.com/users/2060906",
"pm_score": 2,
"selected": false,
"text": "public static class XmlHelperExtentions\n{\n /// <summary>\n /// Loads a string through .Load() instead of .LoadXml()\n /// This prevents character encoding problems.\n /// </summary>\n /// <param name=\"xmlDocument\"></param>\n /// <param name=\"xmlString\"></param>\n public static void LoadString(this XmlDocument xmlDocument, string xmlString, Encoding encoding = null) {\n\n if (encoding == null) {\n encoding = Encoding.UTF8;\n }\n\n // Encode the XML string in a byte array\n byte[] encodedString = encoding.GetBytes(xmlString);\n\n // Put the byte array into a stream and rewind it to the beginning\n using (var ms = new MemoryStream(encodedString)) {\n ms.Flush();\n ms.Position = 0;\n\n // Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes\n xmlDocument.Load(ms);\n }\n }\n}\n"
},
{
"answer_id": 19795465,
"author": "Rubarb",
"author_id": 2957447,
"author_profile": "https://Stackoverflow.com/users/2957447",
"pm_score": 1,
"selected": false,
"text": " <Window.Resources>\n <XmlDataProvider \n x:Name=\"myDP\"\n x:Key=\"MyData\"\n Source=\"\"\n XPath=\"/RootElement/Element\"\n IsAsynchronous=\"False\"\n IsInitialLoadEnabled=\"True\" \n debug:PresentationTraceSources.TraceLevel=\"High\" /> </Window.Resources>\n m_DataProvider = this.FindResource(\"MyData\") as XmlDataProvider;\n FileInfo file = new FileInfo(\"MyXmlFile.xml\");\n\n m_DataProvider.Document = new XmlDocument();\n m_DataProvider.Source = new Uri(file.FullName);\n"
},
{
"answer_id": 44398077,
"author": "xadriel",
"author_id": 618083,
"author_profile": "https://Stackoverflow.com/users/618083",
"pm_score": 0,
"selected": false,
"text": "bodyDoc.LoadXml(new MemoryStream(Encoding.Unicode.GetBytes(body)));"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,685 | <p>Can someone explain the main benefits of different types of references in C#?</p>
<ul>
<li>Weak references</li>
<li>Soft references</li>
<li>Phantom references</li>
<li>Strong references.</li>
</ul>
<p>We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.</p>
| [
{
"answer_id": 21441743,
"author": "Artur A",
"author_id": 304371,
"author_profile": "https://Stackoverflow.com/users/304371",
"pm_score": 3,
"selected": false,
"text": "class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {\n private final WeakReference<ImageView> imageViewReference;\n\n public BitmapWorkerTask(ImageView imageView) {\n imageViewReference = new WeakReference<ImageView>(imageView);\n }\n // Method for getting bitmap is removed for code clearness\n\n // Once complete, see if ImageView is still around and set bitmap.\n @Override\n protected void onPostExecute(Bitmap bitmap) {\n if (imageViewReference != null && bitmap != null) {\n final ImageView imageView = imageViewReference.get();\n if (imageView != null) {\n imageView.setImageBitmap(bitmap);\n }\n }\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
310,691 | <p>can anyone provide/refer a proper OO type helper class for managing a singleton of the SessionFactory and then also for managing Sessions?</p>
| [
{
"answer_id": 310824,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 2,
"selected": false,
"text": "public class BaseDataAccess\n{\n\n protected ISession m_session;\n\n public BaseDataAccess()\n {\n m_session = NHibernateHttpModule.CurrentSession;\n }\n\n public static ISession OpenSession()\n {\n Configuration config;\n ISessionFactory factory;\n ISession session;\n config = new Configuration();\n\n if (config == null)\n {\n throw new ArgumentNullException(nameof(config));\n }\n if (factory == null)\n {\n throw new ArgumentNullException(nameof(factory);\n }\n if (session == null)\n {\n throw new ArgumentNullException(nameof(session));\n }\n\n config.AddAssembly(\"My.Assembly.Here\");\n factory = config.BuildSessionFactory();\n session = factory.OpenSession();\n \n return session;\n }\n} \n"
},
{
"answer_id": 310899,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Handles creation and management of sessions and transactions. It is a singleton because \n/// building the initial session factory is very expensive. Inspiration for this class came \n/// from Chapter 8 of Hibernate in Action by Bauer and King. Although it is a sealed singleton\n/// you can use TypeMock (http://www.typemock.com) for more flexible testing.\n/// </summary>\npublic sealed class NHibernateSessionManager\n{\n private const string DefaultConfigFile = \"DefaultAppWeb.Config\";\n private static readonly object _syncRoot = new object();\n #region Thread-safe, lazy Singleton\n\n/// <summary>\n/// This is a thread-safe, lazy singleton. See http://www.yoda.arachsys.com/csharp/singleton.html\n/// for more details about its implementation.\n/// </summary>\npublic static NHibernateSessionManager Instance\n{\n get\n {\n return Nested.NHibernateSessionManager;\n }\n}\n\n/// <summary>\n/// Private constructor to enforce singleton\n/// </summary>\nprivate NHibernateSessionManager() { }\n\n/// <summary>\n/// Assists with ensuring thread-safe, lazy singleton\n/// </summary>\nprivate class Nested\n{\n static Nested() { }\n internal static readonly NHibernateSessionManager NHibernateSessionManager =\n new NHibernateSessionManager();\n}\n\n#endregion\n\n/// <summary>\n/// This method attempts to find a session factory stored in <see cref=\"sessionFactories\" />\n/// via its name; if it can't be found it creates a new one and adds it the hashtable.\n/// </summary>\n/// <param name=\"sessionFactoryConfigPath\">Path location of the factory config</param>\nprivate ISessionFactory GetSessionFactoryFor(string sessionFactoryConfigPath)\n{\n Check.Require(!string.IsNullOrEmpty(sessionFactoryConfigPath),\n \"sessionFactoryConfigPath may not be null nor empty\");\n\n // Attempt to retrieve a stored SessionFactory from the hashtable.\n ISessionFactory sessionFactory;// = (ISessionFactory)sessionFactories[sessionFactoryConfigPath];\n\n // try and get a session factory if we don't find one create it\n lock (_syncRoot)\n {\n if (!sessionFactories.TryGetValue(sessionFactoryConfigPath, out sessionFactory))\n {\n Configuration cfg = new Configuration();\n if (sessionFactoryConfigPath != DefaultConfigFile)\n {\n Check.Require(File.Exists(sessionFactoryConfigPath),\n \"The config file at '\" + sessionFactoryConfigPath + \"' could not be found\");\n cfg.Configure(sessionFactoryConfigPath);\n\n\n }\n else\n {\n cfg.Configure();\n }\n\n\n // Now that we have our Configuration object, create a new SessionFactory\n sessionFactory = cfg.BuildSessionFactory();\n\n\n Check.Ensure(sessionFactory != null, \"sessionFactory is null and was not built\");\n sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);\n }\n }\n\n\n\n return sessionFactory;\n}\n\n/// <summary>\n/// Allows you to register an interceptor on a new session. This may not be called if there is already\n/// an open session attached to the HttpContext. If you have an interceptor to be used, modify\n/// the HttpModule to call this before calling BeginTransaction().\n/// </summary>\npublic void RegisterInterceptorOn(string sessionFactoryConfigPath, IInterceptor interceptor)\n{\n ISession session = (ISession)ContextSessions[sessionFactoryConfigPath];\n\n if (session != null && session.IsOpen)\n {\n throw new CacheException(\"You cannot register an interceptor once a session has already been opened\");\n }\n\n GetSessionFrom(sessionFactoryConfigPath, interceptor);\n}\n\npublic ISession GetSessionFrom(string sessionFactoryConfigPath)\n{\n return GetSessionFrom(sessionFactoryConfigPath, null);\n}\n/// <summary>\n/// Gets or creates an ISession using the web / app config file.\n/// </summary>\n/// <returns></returns>\npublic ISession GetSessionFrom()\n{\n return GetSessionFrom(DefaultConfigFile, null);\n}\n/// <summary>\n/// Gets a session with or without an interceptor. This method is not called directly; instead,\n/// it gets invoked from other public methods.\n/// </summary>\nprivate ISession GetSessionFrom(string sessionFactoryConfigPath, IInterceptor interceptor)\n{\n var allSessions = ContextSessions;\n ISession session = null;\n if (!allSessions.TryGetValue(sessionFactoryConfigPath, out session))\n {\n if (interceptor != null)\n {\n session = GetSessionFactoryFor(sessionFactoryConfigPath).OpenSession(interceptor);\n }\n else\n {\n session = GetSessionFactoryFor(sessionFactoryConfigPath).OpenSession();\n }\n\n allSessions[sessionFactoryConfigPath] = session;\n }\n\n //session.FlushMode = FlushMode.Always;\n\n Check.Ensure(session != null, \"session was null\");\n\n return session;\n}\n\n/// <summary>\n/// Flushes anything left in the session and closes the connection.\n/// </summary>\npublic void CloseSessionOn(string sessionFactoryConfigPath)\n{\n ISession session;\n if (ContextSessions.TryGetValue(sessionFactoryConfigPath, out session))\n {\n if (session.IsOpen)\n {\n session.Flush();\n session.Close();\n }\n ContextSessions.Remove(sessionFactoryConfigPath);\n\n }\n\n}\n\npublic ITransaction BeginTransactionOn(string sessionFactoryConfigPath)\n{\n ITransaction transaction;\n\n if (!ContextTransactions.TryGetValue(sessionFactoryConfigPath, out transaction))\n {\n transaction = GetSessionFrom(sessionFactoryConfigPath).BeginTransaction();\n ContextTransactions.Add(sessionFactoryConfigPath, transaction);\n }\n\n return transaction;\n}\n\npublic void CommitTransactionOn(string sessionFactoryConfigPath)\n{\n\n try\n {\n if (HasOpenTransactionOn(sessionFactoryConfigPath))\n {\n ITransaction transaction = (ITransaction)ContextTransactions[sessionFactoryConfigPath];\n\n transaction.Commit();\n ContextTransactions.Remove(sessionFactoryConfigPath);\n }\n }\n catch (HibernateException he)\n {\n try\n {\n RollbackTransactionOn(sessionFactoryConfigPath);\n }\n finally\n {\n throw he;\n }\n }\n}\n\npublic bool HasOpenTransactionOn(string sessionFactoryConfigPath)\n{\n ITransaction transaction;\n if (ContextTransactions.TryGetValue(sessionFactoryConfigPath, out transaction))\n {\n\n return !transaction.WasCommitted && !transaction.WasRolledBack;\n }\n return false;\n}\n\npublic void RollbackTransactionOn(string sessionFactoryConfigPath)\n{\n\n try\n {\n if (HasOpenTransactionOn(sessionFactoryConfigPath))\n {\n ITransaction transaction = (ITransaction)ContextTransactions[sessionFactoryConfigPath];\n\n transaction.Rollback();\n }\n\n ContextTransactions.Remove(sessionFactoryConfigPath);\n }\n finally\n {\n\n ForceCloseSessionOn(sessionFactoryConfigPath);\n }\n}\n\n/// <summary>\n/// Since multiple databases may be in use, there may be one transaction per database \n/// persisted at any one time. The easiest way to store them is via a hashtable\n/// with the key being tied to session factory. If within a web context, this uses\n/// <see cref=\"HttpContext\" /> instead of the WinForms specific <see cref=\"CallContext\" />. \n/// Discussion concerning this found at http://forum.springframework.net/showthread.php?t=572\n/// </summary>\nprivate Dictionary<string, ITransaction> ContextTransactions\n{\n get\n {\n if (IsInWebContext())\n {\n if (HttpContext.Current.Items[TRANSACTION_KEY] == null)\n HttpContext.Current.Items[TRANSACTION_KEY] = new Dictionary<string, ITransaction>();\n\n return (Dictionary<string, ITransaction>)HttpContext.Current.Items[TRANSACTION_KEY];\n }\n else\n {\n if (CallContext.GetData(TRANSACTION_KEY) == null)\n CallContext.SetData(TRANSACTION_KEY, new Dictionary<string, ITransaction>());\n\n return (Dictionary<string, ITransaction>)CallContext.GetData(TRANSACTION_KEY);\n }\n }\n}\n\n/// <summary>\n/// Since multiple databases may be in use, there may be one session per database \n/// persisted at any one time. The easiest way to store them is via a hashtable\n/// with the key being tied to session factory. If within a web context, this uses\n/// <see cref=\"HttpContext\" /> instead of the WinForms specific <see cref=\"CallContext\" />. \n/// Discussion concerning this found at http://forum.springframework.net/showthread.php?t=572\n/// </summary>\nprivate Dictionary<string, ISession> ContextSessions\n{\n get\n {\n if (IsInWebContext())\n {\n if (HttpContext.Current.Items[SESSION_KEY] == null)\n HttpContext.Current.Items[SESSION_KEY] = new Dictionary<string, ISession>();\n\n return (Dictionary<string, ISession>)HttpContext.Current.Items[SESSION_KEY];\n }\n else\n {\n if (CallContext.GetData(SESSION_KEY) == null)\n CallContext.SetData(SESSION_KEY, new Dictionary<string, ISession>());\n\n return (Dictionary<string, ISession>)CallContext.GetData(SESSION_KEY);\n }\n }\n}\n\nprivate bool IsInWebContext()\n{\n return HttpContext.Current != null;\n}\n\nprivate Dictionary<string, ISessionFactory> sessionFactories = new Dictionary<string, ISessionFactory>();\nprivate const string TRANSACTION_KEY = \"CONTEXT_TRANSACTIONS\";\nprivate const string SESSION_KEY = \"CONTEXT_SESSIONS\";\n\npublic bool HasOpenTransactionOn()\n{\n return HasOpenTransactionOn(DefaultConfigFile);\n}\n\npublic void CommitTransactionOn()\n{\n CommitTransactionOn(DefaultConfigFile);\n}\n\npublic void CloseSessionOn()\n{\n CloseSessionOn(DefaultConfigFile);\n}\n\npublic void ForceCloseSessionOn()\n{\n ForceCloseSessionOn(DefaultConfigFile);\n\n}\n\npublic void ForceCloseSessionOn(string sessionFactoryConfigPath)\n{\n ISession session;\n if (ContextSessions.TryGetValue(sessionFactoryConfigPath, out session))\n {\n if (session.IsOpen)\n {\n\n session.Close();\n }\n ContextSessions.Remove(sessionFactoryConfigPath);\n\n }\n}\n\npublic void BeginTransactionOn()\n{\n this.BeginTransactionOn(DefaultConfigFile);\n}\n\npublic void RollbackTransactionOn()\n{\n this.RollbackTransactionOn(DefaultConfigFile);\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38574/"
] |
310,699 | <p>I'm using Emma in my ant build to perform coverage reporting. For those that have used Emma, is there a way to get the build to fail if the line coverage (or any type of coverage stat) does not meet a particular threshold? e.g. if the line coverage is not 100%</p>
| [
{
"answer_id": 310710,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": true,
"text": "report.metrics <report></report> name, class, method, block line"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30563/"
] |
310,700 | <p>Does anyone know what this means. Getting this in C# winforms applications:</p>
<blockquote>
<p>Not a legal OleAut date</p>
</blockquote>
| [
{
"answer_id": 362910,
"author": "lc.",
"author_id": 44853,
"author_profile": "https://Stackoverflow.com/users/44853",
"pm_score": 0,
"selected": false,
"text": "try\n{\n if (folderItem.ModifyDate.Year != 1899)\n {\n this.FileModifiedDate = folderItem.ModifyDate.ToShortDateString() + \n \" \" +\n folderItem.ModifyDate.ToLongTimeString();\n }\n}\n//we need this because it throws an exception if it's an invalid date...\ncatch (ArgumentException) { } \n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
310,714 | <p>On the PHP website, the only real checking they suggest is using <code>is_uploaded_file()</code> or <code>move_uploaded_file()</code>, <a href="http://ca.php.net/manual/en/features.file-upload.php" rel="noreferrer">here</a>. Of course you usually don't want user's uploading any type of file, for a variety of reasons.</p>
<p>Because of this, I have often used some "strict" mime type checking. Of course this is very flawed because often mime types are wrong and users can't upload their file. It is also very easy to fake and/or change. And along with all of that, each browser and OS deals with them differently.</p>
<p>Another method is to check the extension, which of course is even easier to change than mime type.</p>
<p>If you only want images, using something like <code>getimagesize()</code> will work.</p>
<p>What about other types of files? PDFs, Word documents or Excel files? Or even text only files?</p>
<p><strong>Edit:</strong> If you don't have <a href="http://php.net/manual/en/function.mime-content-type.php" rel="noreferrer">mime_content_type</a> or <a href="http://php.net/manual/en/function.finfo-file.php" rel="noreferrer">Fileinfo</a> and system("file -bi $uploadedfile") gives you the wrong file type, what other options are there?</p>
| [
{
"answer_id": 310740,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 6,
"selected": true,
"text": "system(\"file -bi $uploadedfile\")"
},
{
"answer_id": 370679,
"author": "Sudden Def",
"author_id": 28121,
"author_profile": "https://Stackoverflow.com/users/28121",
"pm_score": 4,
"selected": false,
"text": "application/pdf %PDF- %PDF-1.4"
},
{
"answer_id": 9763372,
"author": "Francesco Galgani",
"author_id": 1277576,
"author_profile": "https://Stackoverflow.com/users/1277576",
"pm_score": 2,
"selected": false,
"text": "Fileinfo system() if (strcmp(substr(mime_content_type($f),0,4),\"text\")==0) { ... }\n"
},
{
"answer_id": 17349416,
"author": "iZend",
"author_id": 2529117,
"author_profile": "https://Stackoverflow.com/users/2529117",
"pm_score": 1,
"selected": false,
"text": "file_mime_type function file_mime_type($file, $encoding=true) {\n $mime=false;\n\n if (function_exists('finfo_file')) {\n $finfo = finfo_open(FILEINFO_MIME);\n $mime = finfo_file($finfo, $file);\n finfo_close($finfo);\n }\n else if (substr(PHP_OS, 0, 3) == 'WIN') {\n $mime = mime_content_type($file);\n }\n else {\n $file = escapeshellarg($file);\n $cmd = \"file -iL $file\";\n\n exec($cmd, $output, $r);\n\n if ($r == 0) {\n $mime = substr($output[0], strpos($output[0], ': ')+2);\n }\n }\n\n if (!$mime) {\n return false;\n }\n\n if ($encoding) {\n return $mime;\n }\n\n return substr($mime, 0, strpos($mime, '; '));\n}\n"
},
{
"answer_id": 24328074,
"author": "Krausz Lóránt Szilveszter",
"author_id": 2192825,
"author_profile": "https://Stackoverflow.com/users/2192825",
"pm_score": 2,
"selected": false,
"text": "if(isset($_FILES['uploaded'])) {\n $temp = explode(\".\", $_FILES[\"uploaded\"][\"name\"]);\n\n $allowedExts = array(\"txt\",\"htm\",\"html\",\"php\",\"css\",\"js\",\"json\",\"xml\",\"swf\",\"flv\",\"pdf\",\"psd\",\"ai\",\"eps\",\"eps\",\"ps\",\"doc\",\"rtf\",\"ppt\",\"odt\",\"ods\");\n\n $extension = end($temp);\n if( in_array($extension, $allowedExts)) {\n //code....\n\n } else {\n echo \"Error,not Documentum type...\";\n }\n}\n"
},
{
"answer_id": 57439791,
"author": "LF00",
"author_id": 6521116,
"author_profile": "https://Stackoverflow.com/users/6521116",
"pm_score": 0,
"selected": false,
"text": "finfo_file file var_dump(mime_type(\"wiki templete.txt\")); // print string(10) \"text/plain\"\n\nfunction mime_type($file_path)\n{\n if (function_exists('finfo_open')) {\n $finfo = new finfo(FILEINFO_MIME_TYPE, null);\n $mime_type = $finfo->file($file_path);\n }\n if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {\n ob_start();\n passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);\n if ($return > 0) {\n ob_end_clean();\n $mime_type = null;\n }\n $type = trim(ob_get_clean());\n if (!preg_match('#^([a-z0-9\\-]+/[a-z0-9\\-\\.]+)#i', $type, $match)) {\n $mime_type = null;\n }\n $mime_type = $match[1];\n }\n return $mime_type;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
310,720 | <p>I am using Maven (and the Maven Eclipse Integration) to manage the dependencies for my Java projects in Eclipse. The automatic download feature for JAR files from the Maven repositories is a real time saver. Unfortunately, it does not include API documentation and source code.</p>
<p>How can I set up Maven to automatically also get the source and javadoc attachments and register them properly with Eclipse?</p>
| [
{
"answer_id": 311229,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 7,
"selected": false,
"text": "mvn eclipse:eclipse -DdownloadSources=true\n mvn eclipse:eclipse -DdownloadJavadocs=true\n =true mvn eclipse:eclipse -DdownloadSources -DdownloadJavadocs\n"
},
{
"answer_id": 932681,
"author": "mrembisz",
"author_id": 100402,
"author_profile": "https://Stackoverflow.com/users/100402",
"pm_score": 9,
"selected": true,
"text": "Window > Preferences > Maven and checking the \"Download Artifact Sources\" and \"Download Artifact JavaDoc\""
},
{
"answer_id": 1578986,
"author": "surajz",
"author_id": 191300,
"author_profile": "https://Stackoverflow.com/users/191300",
"pm_score": 2,
"selected": false,
"text": "window --> maven --> Download Artifact Sources (select check)\n"
},
{
"answer_id": 2118031,
"author": "overthink",
"author_id": 69689,
"author_profile": "https://Stackoverflow.com/users/69689",
"pm_score": 6,
"selected": false,
"text": "<project>\n ...\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-eclipse-plugin</artifactId>\n <configuration>\n <downloadSources>true</downloadSources>\n <downloadJavadocs>true</downloadJavadocs>\n ... other stuff ...\n </configuration>\n </plugin>\n </plugins>\n </build>\n ...\n</project>\n"
},
{
"answer_id": 3155810,
"author": "Hardy",
"author_id": 115835,
"author_profile": "https://Stackoverflow.com/users/115835",
"pm_score": 3,
"selected": false,
"text": "mvn dependency:sources"
},
{
"answer_id": 4379364,
"author": "wingnut",
"author_id": 386962,
"author_profile": "https://Stackoverflow.com/users/386962",
"pm_score": 2,
"selected": false,
"text": "window --> maven --> Download Artifact Sources (select check)\n maven--> download sources"
},
{
"answer_id": 4740429,
"author": "jhohlfeld",
"author_id": 578522,
"author_profile": "https://Stackoverflow.com/users/578522",
"pm_score": 1,
"selected": false,
"text": "<project>\n...\n<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-eclipse-plugin</artifactId>\n <configuration>\n <downloadSources>true</downloadSources>\n <downloadJavadocs>true</downloadJavadocs>\n ... other stuff ...\n </configuration>\n </plugin>\n </plgins>\n</build>\n...\n"
},
{
"answer_id": 7602691,
"author": "Chris Romine",
"author_id": 947564,
"author_profile": "https://Stackoverflow.com/users/947564",
"pm_score": 1,
"selected": false,
"text": "Window -> Preferences -> Maven\n"
},
{
"answer_id": 9229829,
"author": "Dan R.",
"author_id": 556632,
"author_profile": "https://Stackoverflow.com/users/556632",
"pm_score": 0,
"selected": false,
"text": "Foo.java Foo.class"
},
{
"answer_id": 10544474,
"author": "om39a",
"author_id": 1359391,
"author_profile": "https://Stackoverflow.com/users/1359391",
"pm_score": 2,
"selected": false,
"text": "windows->pref..->Maven"
},
{
"answer_id": 12028661,
"author": "Duncan Jones",
"author_id": 474189,
"author_profile": "https://Stackoverflow.com/users/474189",
"pm_score": 4,
"selected": false,
"text": "pom.xml settings.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n\n <profiles>\n <profile>\n <id>sources-and-javadocs</id>\n <properties>\n <downloadSources>true</downloadSources>\n <downloadJavadocs>true</downloadJavadocs>\n </properties>\n </profile>\n </profiles>\n\n <activeProfiles>\n <activeProfile>sources-and-javadocs</activeProfile>\n </activeProfiles>\n</settings>\n"
},
{
"answer_id": 23512141,
"author": "Sumeet",
"author_id": 2347348,
"author_profile": "https://Stackoverflow.com/users/2347348",
"pm_score": 3,
"selected": false,
"text": "project -> maven -> download sources"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
310,729 | <p>For loading time considerations I am using a runtime css file in my Flex Application.</p>
<p>I am having a problem with a multi line text control :</p>
<pre><code><mx:Text id="txtDescription" selectable="false"
styleName="imageRolloverButtonTextDark" width="100%" textAlign="center"
text="{_rolloverText}"/>
</code></pre>
<p>When my CSS stylesheet has loaded the text style correctly changes, but the height is not recalculated. It appears to be just a single line field.</p>
<p>FYI: The control is not actually visible, and triggered by a rollover. So I dont really care if the stylesheet hasnt loaded and they get standard system text. I jsut want it to be the correct height when it has been loaded.</p>
| [
{
"answer_id": 1112649,
"author": "verveguy",
"author_id": 66753,
"author_profile": "https://Stackoverflow.com/users/66753",
"pm_score": 2,
"selected": false,
"text": "<mx:Canvas id=\"box\" width=\"100%\" backgroundColor=\"Red\">\n <mx:Text width=\"{box.width}\" text=\"{someReallyLongString}\" />\n</mx:Canvas>\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
310,732 | <p>Given a class:</p>
<pre><code>from django.db import models
class Person(models.Model):
name = models.CharField(max_length=20)
</code></pre>
<p>Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:</p>
<pre><code> # Instead of:
Person.objects.filter(name__startswith='B')
# ... and:
Person.objects.filter(name__endswith='B')
# ... is there some way, given:
filter_by = '{0}__{1}'.format('name', 'startswith')
filter_value = 'B'
# ... that you can run the equivalent of this?
Person.objects.filter(filter_by=filter_value)
# ... which will throw an exception, since `filter_by` is not
# an attribute of `Person`.
</code></pre>
| [
{
"answer_id": 310775,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "'name' 'startswith' filter_by = '%s__%s' % ('name', 'startswith')\n"
},
{
"answer_id": 310785,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 9,
"selected": true,
"text": "kwargs = {\n '{0}__{1}'.format('name', 'startswith'): 'A',\n '{0}__{1}'.format('name', 'endswith'): 'Z'\n}\n\nPerson.objects.filter(**kwargs)\n"
},
{
"answer_id": 659419,
"author": "shacker",
"author_id": 8438,
"author_profile": "https://Stackoverflow.com/users/8438",
"pm_score": 3,
"selected": false,
"text": "{'is_staff':True,'last_name__startswith':'A',}\n self.question.custom_query kwargs = eval(self.question.custom_query)\nuser_list = User.objects.filter(**kwargs).order_by(\"last_name\") \n"
},
{
"answer_id": 68994663,
"author": "Branko Radojevic",
"author_id": 6705092,
"author_profile": "https://Stackoverflow.com/users/6705092",
"pm_score": 3,
"selected": false,
"text": "publisher_id\ndate_from\ndate_until\n # prepare filters to apply to queryset\nfilters = {}\nif publisher_id:\n filters['publisher_id'] = publisher_id\nif date_from:\n filters['metric_date__gte'] = date_from\nif date_until:\n filters['metric_date__lte'] = date_until\n\nfilter_q = Q(**filters)\n\nqueryset = Something.objects.filter(filter_q)...\n if publisher_ids:\n filters['publisher_id__in'] = publisher_ids\n"
},
{
"answer_id": 74306826,
"author": "amarse",
"author_id": 15830205,
"author_profile": "https://Stackoverflow.com/users/15830205",
"pm_score": 0,
"selected": false,
"text": "kwargs = {\n 'name__startswith': 'A',\n 'name__endswith': 'Z',\n ***(Add more filters here)***\n\n}\nPerson.objects.filter(**kwargs)\n\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
] |
310,749 | <p>I'm having a problem with the WPF Tab View control that I was hoping someone here might be able to help me with.</p>
<p>I want my tab view control to use rounded corners for the tab headers, because I think rounded tabs look better.</p>
<p>To do this I modified the default control template for the tab by using the "Edit Copy" command in Expression Blend. I then just set the corner radius for the "border" of the tab header.</p>
<p>The problem with this approach, however, is that the "Edit Copy" command ends up generating literal color values for the gradient brushes used to display the "Active" and "Mouse Over" tab backgrounds.</p>
<p>This causes problems when "hi contrast" mode is enabled. Rather than switching to the hi contrast color scheme, like the other controls, the tab with the modified template will use the literal color values specified in the gradient brushes for the active and mouse-over tabs tabs. This ends up making those tabs unreadable, because the text on the tab header gets changed to "white" when the OS switches to hi contrast mode (white text on a gray background is unreadable).</p>
<p>I figured I might be able to switch back to square tabs when hi-contrast mode is enabled, That would fix this particular problem. However, I imagine there will be similar issues with users that have custom windows themes installed.</p>
<p>So, what I'm wondering is:</p>
<ol>
<li>Is there any way I can change the gradients to point to system resources rather than literal values so that the colors will be updated correctly when hi-contrast mode is enabled</li>
<li>Or, is there a way for me to set the corner radius on the border of the tab header without creating a new control template?</li>
</ol>
<p><strong>Edit:</strong></p>
<p>I think I should be a little more explicit about what I'm looking for.
I want a tab control that behaves exactly like the default tab control, except that the tab header corners are rounded. By default, a tab control will use gradients for the tab backgrounds and will "highlight" inactive tabs when the user mouses over them. It will also respond correctly and change it's colors and it's mouse over behavior when the OS switches to hi contrast mode. I still need this behavior.</p>
<p>Creating a copy of the default control template in Blend creates a control template that does not work correctly in hi contrast mode. I want to know what I need to do to the control template, or the code in my window, to get that generated control template to work correctly in hi-contrast mode.</p>
| [
{
"answer_id": 317965,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 2,
"selected": true,
"text": "Color=\"{DynamicResource {x:Static SystemColors.XXXX}\"\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737192/"
] |
310,753 | <p>Mac OS X stores some files with resource forks. I need to create a file with a resource fork. The trouble is, I need to create this file on the command line. Is anyone aware of how you can create a file with a resource fork on the command line in Mac OS X?</p>
| [
{
"answer_id": 310774,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": false,
"text": "man Rez\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,770 | <p>This one is a bit tedious in as far as explaining, so here goes. I'm essentially populating a tableView on the iPhone with multiple sections, and potentially multiple rows per section. To my understanding, it's best to have an array of arrays so that you can simply determine how many sections one has by sending a message to the top level array of count, then for rows per section, doing the same for the inner array(s). My data is in the form of a dictionary. One of the key/value pairs in the dictionary determines where it will be displayed on the tableView. An example is the following:</p>
<pre><code>{
name: "bob",
location: 3
}
{
name: "jane",
location: 50
}
{
name: "chris",
location: 3
}
</code></pre>
<p>In this case I'd have an array with two subarrays. The first subarray would have two dictionaries containing bob and chris since they're both part of location 3. The second subarray would contain jane, since she is in location 50. What's my best bet in Cocoa populate this data structure? A hash table in C would probably do the trick, but I'd rather use the classes available in Cocoa.</p>
<p>Thanks and please let me know if I need to further clarify.</p>
| [
{
"answer_id": 310969,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": true,
"text": "NSArray * arrayOfRecords = [NSArray arrayWithObjects:\n\n [NSDictionary dictionaryWithObjectsAndKeys:\n @\"bob\", @\"name\",\n [NSNumber numberWithInt:3], @\"location\", nil],\n\n [NSDictionary dictionaryWithObjectsAndKeys:\n @\"jane\", @\"name\",\n [NSNumber numberWithInt:50], @\"location\", nil],\n\n [NSDictionary dictionaryWithObjectsAndKeys:\n @\"chris\", @\"name\",\n [NSNumber numberWithInt:3], @\"location\", nil],\n\n nil];\n\nNSMutableDictionary * sections = [NSMutableDictionary dictionary];\n\nfor (NSDictionary * record in arrayOfRecords)\n{\n id key = [record valueForKey:@\"location\"];\n NSMutableArray * rows = [sections objectForKey:key];\n\n if (rows == nil)\n {\n [sections setObject:[NSMutableArray arrayWithObject:record] forKey:key];\n }\n else\n {\n [rows addObject:record];\n }\n}\n\nNSArray * sortedKeys = [[sections allKeys] sortedArrayUsingSelector:@selector(compare:)];\nNSArray * sortedSections = [sections objectsForKeys:sortedKeys notFoundMarker:@\"\"];\n\nNSLog(@\"%@\", sortedSections);"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,786 | <p>Does anyone know how to change the color of a row (or row background) in the UIPickerView control from the iPhone SDK? Similiar to the below title for row, however I would also like to change the color of the row:</p>
<pre><code>- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 310863,
"author": "Sean",
"author_id": 29941,
"author_profile": "https://Stackoverflow.com/users/29941",
"pm_score": 4,
"selected": false,
"text": "- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {\n\n CGRect imageFrame = CGRectMake(0.0, 0.0, 15, 15);\n UIImageView *label = [[[UIImageView alloc] initWithFrame:imageFrame] **autorelease**];\n\n if (row == 0)\n {\n label.backgroundColor = [UIColor redColor];\n }\n if (row == 1)\n {\n label.backgroundColor = [UIColor blueColor];\n }\n if (row == 2)\n {\n label.backgroundColor = [UIColor blackColor];\n } \n return label;\n}\n"
},
{
"answer_id": 693830,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "label.backgroundColor = [UIColor yourcolorColor];\n"
},
{
"answer_id": 12100874,
"author": "Scott Gardner",
"author_id": 616764,
"author_profile": "https://Stackoverflow.com/users/616764",
"pm_score": 2,
"selected": false,
"text": "- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view\n{\n CGRect rowFrame = CGRectMake(00.0f, 0.0f, [pickerView viewForRow:row forComponent:component].frame.size.width, [pickerView viewForRow:row forComponent:component].frame.size.height);\n UILabel *label = [[UILabel alloc] initWithFrame:rowFrame];\n label.font = [UIFont boldSystemFontOfSize:18.0f];\n\n // This is an array I pass to the picker in prepareForSegue:sender:\n label.text = [self.values objectAtIndex:row];\n label.textAlignment = UITextAlignmentCenter;\n\n // This is an array I pass to the picker in prepareForSegue:sender:\n if ([self.backgroundColors count]) {\n label.backgroundColor = [self.backgroundColors objectAtIndex:row];\n\n // self.lightColors is an array I instantiate in viewDidLoad: self.lightColors = @[ [UIColor yellowColor], [UIColor greenColor], [UIColor whiteColor] ];\n label.textColor = [self.lightColors containsObject:label.backgroundColor] ? [UIColor blackColor] : [UIColor whiteColor];\n } else {\n label.textColor = [UIColor blackColor];\n }\n\n return label;\n}\n"
},
{
"answer_id": 40373123,
"author": "Ringo",
"author_id": 7078356,
"author_profile": "https://Stackoverflow.com/users/7078356",
"pm_score": 0,
"selected": false,
"text": "-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{\n\n UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];\n [labelSelected setTextColor:[UIColor redColor]];\n\n}\n - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{\n\n UILabel *label = (id)view;\n\n if (!label){\n\n label=[[UILabel alloc]init];\n label.textAlignment = NSTextAlignmentCenter;\n pickerView.backgroundColor=[UIColor whiteColor];\n label.text=[self pickerView:pickerView titleForRow:row forComponent:component];\n label.textColor=[UIColor grayColor];\n\n }\n return label;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29941/"
] |
310,787 | <p>I have an array (<code>arr</code>) of elements, and a function (<code>f</code>) that takes 2 elements and returns a number.</p>
<p>I need a permutation of the array, such that <code>f(arr[i], arr[i+1])</code> is as little as possible for each <code>i</code> in <code>arr</code>. (and it should loop, ie. it should also minimize <code>f(arr[arr.length - 1], arr[0])</code>)</p>
<p>Also, <code>f</code> works sort of like a distance, so <code>f(a,b) == f(b,a)</code></p>
<p>I don't need the optimum solution if it's too inefficient, but one that works reasonable well and is fast since I need to calculate them pretty much in realtime (I don't know what to length of <code>arr</code> is, but I think it could be something around 30)</p>
| [
{
"answer_id": 310811,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 0,
"selected": false,
"text": "g_i(p) = f(a^p[i], a^p[i+1]), and wrap around when i+1 > n\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815/"
] |
310,801 | <p>When using a subdomain and trying to view anything related to current_user. user is sent to a new session page, the page shows the session is created and gives the option to logout. I can use no subdomain and it works fine.</p>
| [
{
"answer_id": 310830,
"author": "Kevin H",
"author_id": 20116,
"author_profile": "https://Stackoverflow.com/users/20116",
"pm_score": 1,
"selected": false,
"text": "ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update( :session_domain => '.domain.com')\n"
},
{
"answer_id": 3986539,
"author": "jkrall",
"author_id": 100038,
"author_profile": "https://Stackoverflow.com/users/100038",
"pm_score": 1,
"selected": false,
"text": "ActionController::Base.session_options[:domain] = '.domain.com'\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,805 | <p>I've been knocking my head against this for some time now. I'm not really sure why it isn't working. I'm still pretty new to this whole WPF business. </p>
<p>Here's my XAML for the combobox</p>
<pre><code><ComboBox
SelectedValuePath="Type.FullName"
SelectedItem="{Binding Path=Type}"
Name="cmoBox" />
</code></pre>
<p>Here's what populates the ComboBox (myAssembly is a class I created with a list of possible types)</p>
<pre><code>cmoBox.ItemsSource = myAssembly.PossibleTypes;
</code></pre>
<p>I set the DataContext in a parent element of the ComboBox in the code behind like this:</p>
<pre><code>groupBox.DataContext = listBox.SelectedItem;
</code></pre>
<p>I want the binding to select the correct "possible type" from the combo box. It doesn't select anything. I have tried SelectedValue and SelectedItem. When I changed the DisplayMemberPath of the ComboBox to a different property it changed what was displayed so I know it's not completely broken. </p>
<p>Any ideas???</p>
| [
{
"answer_id": 310812,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 5,
"selected": true,
"text": "ItemsSource=\"{Binding}\" DataContext myAssembly.PossibleTypes"
},
{
"answer_id": 1866317,
"author": "TabbyCool",
"author_id": 226380,
"author_profile": "https://Stackoverflow.com/users/226380",
"pm_score": 4,
"selected": false,
"text": "<UserControl \n x:Class=\"MyNamespace.MyControl\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n DataContext=\"{Binding}\">\n\n <ComboBox \n Width=\"200\" \n ItemsSource=\"{Binding Path=myAssembly.PossibleTypes}\"\n SelectedValuePath=\"Type.FullName\" \n SelectedItem=\"{Binding Path=Type}\" \n Name=\"cmoBox\" />\n</UserControl>\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
310,820 | <p>I want to do this in Actionscript:</p>
<pre><code>typeof(control1) != typeof(control2)
</code></pre>
<p>to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns <code>'object'</code> for both <code>typeof()</code> expressions because thats the way Actionscript works.</p>
<p>I couldn't seem to find an alternative by looking in the debugger, or on pages that describe <code>typeof()</code> in Actionscript.</p>
<p>Is there a way to get the actual runtime type?</p>
| [
{
"answer_id": 310879,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 2,
"selected": false,
"text": " dynamic class A {}\n trace(A.prototype.constructor); // [class A]\n trace(A.prototype.constructor == A); // true\n var myA:A = new A();\n trace(myA.constructor == A); // true\n public function checkType():void {\n trace(prototype.constructor, prototype.constructor == Player);\n // shows [class Player] true\n}\n"
},
{
"answer_id": 315029,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "flash.utils.getQualifiedClassName() flash.utils.describeType()"
},
{
"answer_id": 457576,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 1,
"selected": false,
"text": "if (objectA is objectB.constructor || objectB is objectA.constructor)\n{\n // ObjectA inherits from ObjectB or vice versa\n}\n"
},
{
"answer_id": 739010,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "var mySprite:Sprite = new Sprite();\nvar myMovie:MovieClip = new MovieClip();\n\ntrace(mySprite is Sprite);\ntrace(myMovie is MovieClip);\ntrace(mySprite is MovieClip);\ntrace(myMovie is Sprite);\n true\ntrue\nfalse\nfalse\n"
},
{
"answer_id": 750592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Object obj = new Object();\nObject o = new Object();\n\nif(o.getClass().getName().endsWith(obj.getClass().getName())){\n return true; \n}else{\n return false;\n}\n"
},
{
"answer_id": 908536,
"author": "verveguy",
"author_id": 66753,
"author_profile": "https://Stackoverflow.com/users/66753",
"pm_score": 0,
"selected": false,
"text": "import flash.utils.getDefinitionByName;\nimport flash.utils.getQualifiedClassName;\n\n...\n\nif (objectA is getDefinitionByName(getQualifiedClassName(objectB)))\n{\n ...\n}\n"
},
{
"answer_id": 14884644,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 2,
"selected": false,
"text": "var actualRuntimeType:Class = Object(yourInstance).constructor;\n .constructor .constructor dynamic Object dynamic .constructor Object Object(instanceA).constructor === Object(instanceB).constructor;\n var actualRuntimeType:Class = yourInstance[\"constructor\"];\n .constructor [\"constructor\"]"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
310,826 | <p>I am building a small device with its own CPU (AVR Mega8) that is supposed to connect to a PC. Assuming that the physical connection and passing of bytes has been accomplished, what would be the best protocol to use on top of those bytes? The computer needs to be able to set certain voltages on the device, and read back certain other voltages.</p>
<p>At the moment, I am thinking a completely host-driven synchronous protocol: computer send requests, the embedded CPU answers. Any other ideas?</p>
| [
{
"answer_id": 310848,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": false,
"text": "Host --> [V02?] // Request voltage #2\nAVR --> [V02=2.34] // Reply with voltage #2\nHost --> [V06=3.12] // Set voltage #6\nAVR --> [V06=3.15] // Reply with voltage #6\n"
},
{
"answer_id": 318621,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 2,
"selected": false,
"text": "struct PacketHdr\n{\n char syncByte1;\n char syncByte2;\n char packetType;\n char bytesToFollow; //-or- totalPacketSize\n};\n\nstruct VoltageSet\n{ \n struct PacketHdr;\n int16 channelId;\n int16 voltageLevel; \n uint16 crc;\n};\n\nstruct VoltageResponse\n{\n struct PacketHdr;\n int16 data[N]; //Num channels are fixed\n uint16 crc;\n}\n"
},
{
"answer_id": 319533,
"author": "Borzio",
"author_id": 36215,
"author_profile": "https://Stackoverflow.com/users/36215",
"pm_score": 1,
"selected": false,
"text": " V0=3.20\n V1=3.21\n V2= ...\n D1=0\n D2=1\n D3=...\n and then start over -- \n 5=0 \n6=9\n2=5 \n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,833 | <p>In my views.py, i have a snippit of code like this:</p>
<pre><code>def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if request.POST:
if form.is_valid():
clean_post_data(form)
form.save()
action = "Added new product"
return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request))
else:
action = "There was an error. Please go back and try again"
return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request))
return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request))
</code></pre>
<p>But when i run that, i get the following error <code>'list' object has no attribute 'rstrip'</code>. What am i doing wrong.</p>
<p>I originally had the <code>for i in form.cleaned_data:</code> loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. <a href="http://dpaste.com/92836/" rel="nofollow noreferrer">http://dpaste.com/92836/</a></p>
| [
{
"answer_id": 311304,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": true,
"text": "clean_post_data clean"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
310,870 | <p>What's the difference between</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>and</p>
<pre><code>var A = function () { };
A.prototype.x = function () {
//do something
};
</code></pre>
| [
{
"answer_id": 310895,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 6,
"selected": false,
"text": "var A = function () {\n var private_var = ...;\n\n this.x = function () {\n return private_var;\n };\n\n this.setX = function (new_x) {\n private_var = new_x;\n };\n};\n"
},
{
"answer_id": 310905,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "new var A = function() {};\nA.prototype = {\n _instance_var: 0,\n\n initialize: function(v) { this._instance_var = v; },\n\n x: function() { alert(this._instance_var); }\n};\n"
},
{
"answer_id": 310914,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 9,
"selected": false,
"text": "[[Prototype]] myObj.method() var A = function () {\n this.x = function () {\n //do something\n };\n};\n A A() this.x window.x window.x var A = function () { };\nA.prototype.x = function () {\n //do something\n};\n A var A = new function () {\n this.x = function () {\n //do something\n };\n};\n new new [[Prototype]] x return this; console.log(A.x) // function () {\n // //do something\n // };\n var A = function () {\n this.x = function () {\n //do something\n };\n};\nvar a = new A();\n var A = (function () {\n this.x = function () {\n //do something\n };\n}());\n A this.x window.x A undefined var A = function () { \n this.objectsOwnProperties = \"are serialized\";\n};\nA.prototype.prototypeProperties = \"are NOT serialized\";\nvar instance = new A();\nconsole.log(instance.prototypeProperties); // \"are NOT serialized\"\nconsole.log(JSON.stringify(instance)); \n// {\"objectsOwnProperties\":\"are serialized\"} \n"
},
{
"answer_id": 310927,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 8,
"selected": false,
"text": "// x is a method assigned to the object using \"this\"\nvar A = function () {\n this.x = function () { alert('A'); };\n};\nA.prototype.updateX = function( value ) {\n this.x = function() { alert( value ); }\n};\n\nvar a1 = new A();\nvar a2 = new A();\na1.x(); // Displays 'A'\na2.x(); // Also displays 'A'\na1.updateX('Z');\na1.x(); // Displays 'Z'\na2.x(); // Still displays 'A'\n\n// Here x is a method assigned to the object using \"prototype\"\nvar B = function () { };\nB.prototype.x = function () { alert('B'); };\n\nB.prototype.updateX = function( value ) {\n B.prototype.x = function() { alert( value ); }\n}\n\nvar b1 = new B();\nvar b2 = new B();\nb1.x(); // Displays 'B'\nb2.x(); // Also displays 'B'\nb1.updateX('Y');\nb1.x(); // Displays 'Y'\nb2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances\n"
},
{
"answer_id": 12529413,
"author": "tarkabak",
"author_id": 1688637,
"author_profile": "https://Stackoverflow.com/users/1688637",
"pm_score": 4,
"selected": false,
"text": "this prototype BaseClass = function() {\n var text = null;\n\n this.setText = function(value) {\n text = value + \" BaseClass!\";\n };\n\n this.getText = function() {\n return text;\n };\n\n this.setText(\"Hello\"); // This always calls BaseClass.setText()\n};\n\nSubClass = function() {\n // setText is not overridden yet,\n // so the constructor calls the superclass' method\n BaseClass.call(this);\n\n // Keeping a reference to the superclass' method\n var super_setText = this.setText;\n // Overriding\n this.setText = function(value) {\n super_setText.call(this, \"SubClass says: \" + value);\n };\n};\nSubClass.prototype = new BaseClass();\n\nvar subClass = new SubClass();\nconsole.log(subClass.getText()); // Hello BaseClass!\n\nsubClass.setText(\"Hello\"); // setText is already overridden\nconsole.log(subClass.getText()); // SubClass says: Hello BaseClass!\n BaseClass = function() {\n this.setText(\"Hello\"); // This calls the overridden method\n};\n\nBaseClass.prototype.setText = function(value) {\n this.text = value + \" BaseClass!\";\n};\n\nBaseClass.prototype.getText = function() {\n return this.text;\n};\n\nSubClass = function() {\n // setText is already overridden, so this works as expected\n BaseClass.call(this);\n};\nSubClass.prototype = new BaseClass();\n\nSubClass.prototype.setText = function(value) {\n BaseClass.prototype.setText.call(this, \"SubClass says: \" + value);\n};\n\nvar subClass = new SubClass();\nconsole.log(subClass.getText()); // SubClass says: Hello BaseClass!\n var A = function (param1) {\n var privateVar = null; // Private variable\n\n // Calling this.setPrivateVar(param1) here would be an error\n\n this.setPrivateVar = function (value) {\n privateVar = value;\n console.log(\"setPrivateVar value set to: \" + value);\n\n // param1 is still here, possible memory leak\n console.log(\"setPrivateVar has param1: \" + param1);\n };\n\n // The constructor logic starts here possibly after\n // many lines of code that define methods\n\n this.setPrivateVar(param1); // This is valid\n};\n\nvar a = new A(0);\n// setPrivateVar value set to: 0\n// setPrivateVar has param1: 0\n\na.setPrivateVar(1);\n//setPrivateVar value set to: 1\n//setPrivateVar has param1: 0\n var A = function (param1) {\n this.setPublicVar(param1); // This is valid\n};\nA.prototype.setPublicVar = function (value) {\n this.publicVar = value; // No private variable\n};\n\nvar a = new A(0);\na.setPublicVar(1);\nconsole.log(a.publicVar); // 1\n"
},
{
"answer_id": 20944109,
"author": "oozzal",
"author_id": 2355112,
"author_profile": "https://Stackoverflow.com/users/2355112",
"pm_score": 4,
"selected": false,
"text": "this var AdultPerson = function() {\n\n var age;\n\n this.setAge = function(val) {\n // some housekeeping\n age = val >= 18 && val;\n };\n\n this.getAge = function() {\n return age;\n };\n\n this.isValid = function() {\n return !!age;\n };\n};\n prototype AdultPerson.prototype.getRights = function() {\n // Should be valid\n return this.isValid() && ['Booze', 'Drive'];\n};\n var p1 = new AdultPerson;\np1.setAge(12); // ( age = false )\nconsole.log(p1.getRights()); // false ( Kid alert! )\np1.setAge(19); // ( age = 19 )\nconsole.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )\n\nvar p2 = new AdultPerson;\np2.setAge(45); \nconsole.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***\n"
},
{
"answer_id": 30148923,
"author": "Ely",
"author_id": 1566187,
"author_profile": "https://Stackoverflow.com/users/1566187",
"pm_score": 4,
"selected": false,
"text": "var carlike = function(obj, loc) {\n obj.loc = loc;\n obj.move = function() {\n obj.loc++;\n };\n return obj;\n};\n\nvar amy = carlike({}, 1);\namy.move();\nvar ben = carlike({}, 9);\nben.move();\n Car methods move Car extend Car methods var Car = function(loc) {\n var obj = {loc: loc};\n extend(obj, Car.methods);\n return obj;\n};\n\nCar.methods = {\n move : function() {\n this.loc++;\n }\n};\n\nvar amy = Car(1);\namy.move();\nvar ben = Car(9);\nben.move();\n move prototype constructor Car prototype constructor Car Car.prototype.constructor Car amy.constructor Car.prototype amy.constructor Car amy instanceof Car instanceof Car amy var Car = function(loc) {\n var obj = Object.create(Car.prototype);\n obj.loc = loc;\n return obj;\n};\n\nCar.prototype.move = function() {\n this.loc++;\n};\n\nvar amy = Car(1);\namy.move();\nvar ben = Car(9);\nben.move();\n\nconsole.log(Car.prototype.constructor);\nconsole.log(amy.constructor);\nconsole.log(amy instanceof Car);\n var Dog = function() {\n return {legs: 4, bark: alert};\n};\n\nvar fido = Dog();\nconsole.log(fido instanceof Dog);\n instanceof false Dog fido fido Object.prototype new var Car = function(loc) {\n this.loc = loc;\n};\n\nCar.prototype.move = function() {\n this.loc++;\n};\n\nvar amy = new Car(1);\namy.move();\nvar ben = new Car(9);\nben.move();\n loc"
},
{
"answer_id": 34948211,
"author": "daremkd",
"author_id": 1085998,
"author_profile": "https://Stackoverflow.com/users/1085998",
"pm_score": 7,
"selected": false,
"text": "var A = function() { this.hey = function() { alert('from A') } };\n var A = function() {}\nA.prototype.hey = function() { alert('from prototype') };\n __proto__ anyObject.__proto__ __proto__ __proto__ var newObj = Object.create(null) __proto__ null prototype var A = [];\nA.prototype // undefined\nA = function() {}\nA.prototype // {} // got created when function() {} was defined\n A.prototype __proto__ __proto__ prototype __proto__ __proto__ __proto__ __proto__ __proto__ null undefined prototype A var a1 = new A();\n a1 new A() new a1 prototype __proto__ a1 __proto__ a1 new __proto__ prototype a1.__proto__ = A.prototype;\n A.prototype a1 a1.__proto__ A.prototype A = function() {} // JS: cool. let's also create A.prototype pointing to empty {}\n var a1 = new A() A() var A = function() { this.hey = function() { alert('from A') } };\n function() { } this.hey.. this a1 a1.hey = function() { alert('from A') }\n this a1 var a1 = new A() a1 a1 = {} a1.__proto__ A.prototype A() this this a1 var a2 = new A();\n a2 __proto__ A.prototype A() a2 hey a1 a2 hey new A __proto__ yoMan a1 __proto__ yoMan __proto__ a1 __proto__ A.prototype var A = function() {}\nA.prototype.hey = function() { alert('from prototype') };\n a1 function A() a1.hey\n a1 hey __proto__ a1 a2 hey __proto__ Function.prototype __proto__ Functional.prototype"
},
{
"answer_id": 35343454,
"author": "pishpish",
"author_id": 2227168,
"author_profile": "https://Stackoverflow.com/users/2227168",
"pm_score": 4,
"selected": false,
"text": "prototype new x A var A = function () {\n this.x = function () {\n //do something\n };\n};\n\nvar a = new A(); // constructor function gets executed\n // newly created object gets an 'x' property\n // which is a function\na.x(); // and can be called like this\n A var A = function () { };\nA.prototype.x = function () {\n //do something\n};\n\nvar a = new A(); // constructor function gets executed\n // which does nothing in this example\n\na.x(); // you are trying to access the 'x' property of an instance of 'A'\n // which does not exist\n // so JavaScript looks for that property in the prototype object\n // that was defined using the 'prototype' property of the constructor\n"
},
{
"answer_id": 45382292,
"author": "Arnav Aggarwal",
"author_id": 5075623,
"author_profile": "https://Stackoverflow.com/users/5075623",
"pm_score": 4,
"selected": false,
"text": "function ExampleFn() {\n this.print = function() {\n console.log(\"Calling print! \");\n }\n}\n\nvar objects = [];\nconsole.time('x');\nfor (let i = 0; i < 2000000; i++) {\n objects.push(new ExampleFn());\n}\nconsole.timeEnd('x');\n\n//x: 1151.960693359375ms function ExampleFn() {\n}\nExampleFn.prototype.print = function() {\n console.log(\"Calling print!\");\n}\n\nvar objects = [];\nconsole.time('y');\nfor (let i = 0; i < 2000000; i++) {\n objects.push(new ExampleFn());\n}\nconsole.timeEnd('y');\n\n//x: 617.866943359375ms print print"
},
{
"answer_id": 47878698,
"author": "牛さん",
"author_id": 1553656,
"author_profile": "https://Stackoverflow.com/users/1553656",
"pm_score": 3,
"selected": false,
"text": "prototype this"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39864/"
] |
310,888 | <p>Today I ran XtUnit at a part of my unit testing framework to to rollback database changes created while running a test case. This is a skeleton of how I have used it. The Test case ran successfully but the database state changed as a result. </p>
<pre><code>using NUnit.Framework;
using TeamAgile.ApplicationBlocks.Interception;
using TeamAgile.ApplicationBlocks.Interception.UnitTestExtensions;
namespace NameSpace.UnitTest
{
[TestFixture]
public class Test : InterceptableObject
{
[Test]
[DataRollBack]
public void CreateTest()
{
</code></pre>
<p>I use Nhibernate with Mysql. Am I missing something?</p>
| [
{
"answer_id": 354237,
"author": "Tom Lianza",
"author_id": 26624,
"author_profile": "https://Stackoverflow.com/users/26624",
"pm_score": 3,
"selected": true,
"text": "ExtensibleFixture InterceptableObject ExtensibleFixture InterceptableObject"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] |
310,889 | <p>I am taking my first foray into PHP programming and need to configure the environment for the first time. Can I use PHP with the built in VS web server or do I need to (and I hope not) use IIS locally?</p>
<p>In addition, any pointers on pitfalls to be avoided would be great.</p>
<p>Many thanks.</p>
<p><b>Update:</b> I should have made the question more explicit. I am developing a ASP.Net MVC application.</p>
<p><b>Update 2:</b> It's become clear that I haven't asked the question as cleanly as I would have liked. Here is what I am doing. I have an existing ASP.net MVC application that I am adding an e-mail form to. While researching, I came across this page: <a href="http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/" rel="nofollow noreferrer">Ajax Forms with jQuery</a> and I liked the interface he presented and thought I would try and adapt it. Calls are made to PHP functions and hence my question.</p>
<p>It is also clear that the confusion also could come from the fact that there is a better approach entirely. So, what is the way out of the maze, Alice?</p>
| [
{
"answer_id": 311491,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": true,
"text": "string mailTo = Request.Form[\"emailTo\"];\nstring mailFrom = Request.Form[\"emailFrom\"];\nstring subject = Request.Form[\"subject\"];\nstring message = Request.Form[\"message\"];\n\n// Send mail here using variables above\n// You'll need an SMTP server and some mail \n// sending code which I'm drawing a blank as\n// to what the name of the classes are at the moment\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13139/"
] |
310,911 | <p>Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?</p>
<p>Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.</p>
| [
{
"answer_id": 310918,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "if (newContent == false) var myNum = 0;\n$('p').html('' + myNum);\n"
},
{
"answer_id": 310920,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": true,
"text": "val html() html() $(\"p\").html((0).toString())\n"
},
{
"answer_id": 311164,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": -1,
"selected": false,
"text": "$('p')\n $(\"P\").eq(0).html( 'something' );\n $(\"P\").eq(0).html();\n"
},
{
"answer_id": 312693,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 0,
"selected": false,
"text": "text() html()"
},
{
"answer_id": 313999,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 0,
"selected": false,
"text": "html (function($) {\n var oldHtml = $.fn.html;\n $.fn.html = function (content) {\n oldHtml.apply(this, [content.toString()]);\n }\n})(jQuery);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
310,919 | <p>I've never liked wrapping the </p>
<pre><code>mysql_real_escape_string
</code></pre>
<p>function around input I expect to be integer for inclusion in a MySQL query.
Recently I came across the </p>
<pre><code>filter_var
</code></pre>
<p>function. Nice!</p>
<p>I'm currently using the code:</p>
<pre><code>if (isset($idUserIN)
&& filter_var($idUserIN, FILTER_VALIDATE_INT)
&& 0 < filter_var($idUserIN, FILTER_SANITIZE_NUMBER_INT)
) {
$idUser = filter_var($idUserIN, FILTER_SANITIZE_NUMBER_INT);
$sql = 'SELECT * FROM TABLE_NAME WHERE idUser = '.$idUser;
} else {
// handle invalid data
}
</code></pre>
<p>Does this leave any holes open?</p>
<p>('> 0' chosen rather than '>= 0' as its a table auto_increment field, so 0 would not be a normal value)</p>
| [
{
"answer_id": 310930,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "$sql = 'SELECT * FROM TABLE_NAME WHERE idUser = ' . intval($idUser);\n $idUserIN_filtered = filter_var($idUserIN, FILTER_VALIDATE_INT);\n\nif (isset($idUserIN) \n && $idUserIN_filtered \n && 0 < $idUserIN_filtered\n ) {\n $sql = 'SELECT * FROM TABLE_NAME WHERE idUser = '.$idUser_filtered;\n} else {\n // handle invalid data\n}\n"
},
{
"answer_id": 310959,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "public static function escape_int($i) {\n $sanitised = intval($i); \n if( '_' . $sanitised . '_' === '_' . $i . '_' && $sanitised > 0 ) {\n return $sanitised;\n }\n throw new IntegerEscapeException( $i, $sanitised );\n return \"ENOINT\"; # Wont Run This, but I prepare for the impossible. \n}\n\ntry { \n $sql = 'SELECT * FROM TABLE_NAME WHERE idUser = ' . DB::escape_int( $userid ); \n DB::query($sql); \n ...etc...\n} catch( IntegerEscapeException $e ) { \n die ( \"You shot the sherif!\" ); # bad example.\n}\n"
},
{
"answer_id": 311415,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 0,
"selected": false,
"text": "if ($idUser = filter_var($idUserIN, FILTER_VALIDATE_INT)) {\n $sql = 'SELECT * FROM TABLE_NAME WHERE idUser = '.$idUser;\n} else {\n // handle invalid data\n}\n if ($idUser = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT)) {\n if (!$idUser = filter_var($idUserIN, FILTER_VALIDATE_INT)) {\n throw new InputParameterException('UserId');\n}\n//else its valid\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10648/"
] |
310,946 | <p>I want to send an email from my iPhone application. I have heard that the iOS SDK doesn't have an email API. I don't want to use the following code because it will exit my application:</p>
<pre><code>NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
</code></pre>
<p>So how can I send an email from my app?</p>
| [
{
"answer_id": 1513433,
"author": "PeyloW",
"author_id": 165059,
"author_profile": "https://Stackoverflow.com/users/165059",
"pm_score": 9,
"selected": false,
"text": "MFMailComposeViewController MFMailComposeViewControllerDelegate #import <MessageUI/MFMailComposeViewController.h>\n MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];\ncontroller.mailComposeDelegate = self;\n[controller setSubject:@\"My Subject\"];\n[controller setMessageBody:@\"Hello there.\" isHTML:NO]; \nif (controller) [self presentModalViewController:controller animated:YES];\n[controller release];\n - (void)mailComposeController:(MFMailComposeViewController*)controller \n didFinishWithResult:(MFMailComposeResult)result \n error:(NSError*)error;\n{\n if (result == MFMailComposeResultSent) {\n NSLog(@\"It's away!\");\n }\n [self dismissModalViewControllerAnimated:YES];\n}\n if ([MFMailComposeViewController canSendMail]) {\n // Show the composer\n} else {\n // Handle the error\n}\n"
},
{
"answer_id": 12525746,
"author": "Kannan Prasad",
"author_id": 591843,
"author_profile": "https://Stackoverflow.com/users/591843",
"pm_score": 4,
"selected": false,
"text": "#import <MessageUI/MFMailComposeViewController.h>\n NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);\n\nNSString *documentsDirectory = [paths objectAtIndex:0];\n\nNSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@\"myGreenCard.png\"];\n\n\n\nMFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];\ncontroller.mailComposeDelegate = self;\n[controller setSubject:@\"Green card application\"];\n[controller setMessageBody:@\"Hi , <br/> This is my new latest designed green card.\" isHTML:YES]; \n[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@\"png\" fileName:@\"My Green Card\"];\nif (controller)\n [self presentModalViewController:controller animated:YES];\n[controller release];\n -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;\n{\n if (result == MFMailComposeResultSent) {\n NSLog(@\"It's away!\");\n }\n [self dismissModalViewControllerAnimated:YES];\n}\n"
},
{
"answer_id": 18697112,
"author": "mandeep",
"author_id": 2454925,
"author_profile": "https://Stackoverflow.com/users/2454925",
"pm_score": 4,
"selected": false,
"text": "-(void)EmailButtonACtion{\n\n if ([MFMailComposeViewController canSendMail])\n {\n MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];\n controller.mailComposeDelegate = self;\n [controller.navigationBar setBackgroundImage:[UIImage imageNamed:@\"navigation_bg_iPhone.png\"] forBarMetrics:UIBarMetricsDefault];\n controller.navigationBar.tintColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];\n [controller setSubject:@\"\"];\n [controller setMessageBody:@\" \" isHTML:YES];\n [controller setToRecipients:[NSArray arrayWithObjects:@\"\",nil]];\n UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];\n UIImage *ui = resultimg.image;\n pasteboard.image = ui;\n NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(ui)];\n [controller addAttachmentData:imageData mimeType:@\"image/png\" fileName:@\" \"];\n [self presentViewController:controller animated:YES completion:NULL];\n }\n else{\n UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@\"alrt\" message:nil delegate:self cancelButtonTitle:@\"ok\" otherButtonTitles: nil] ;\n [alert show];\n }\n\n }\n -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error\n {\n\n [MailAlert show];\n switch (result)\n {\n case MFMailComposeResultCancelled:\n MailAlert.message = @\"Email Cancelled\";\n break;\n case MFMailComposeResultSaved:\n MailAlert.message = @\"Email Saved\";\n break;\n case MFMailComposeResultSent:\n MailAlert.message = @\"Email Sent\";\n break;\n case MFMailComposeResultFailed:\n MailAlert.message = @\"Email Failed\";\n break;\n default:\n MailAlert.message = @\"Email Not Sent\";\n break;\n }\n [self dismissViewControllerAnimated:YES completion:NULL];\n [MailAlert show];\n }\n"
},
{
"answer_id": 32678731,
"author": "Esqarrouth",
"author_id": 2589276,
"author_profile": "https://Stackoverflow.com/users/2589276",
"pm_score": 1,
"selected": false,
"text": "import MessageUI\n\nclass YourVC: UIViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n if MFMailComposeViewController.canSendMail() {\n var emailTitle = \"Vea Software Feedback\"\n var messageBody = \"Vea Software! :) \"\n var toRecipents = [\"pj@veasoftware.com\"]\n var mc:MFMailComposeViewController = MFMailComposeViewController()\n mc.mailComposeDelegate = self\n mc.setSubject(emailTitle)\n mc.setMessageBody(messageBody, isHTML: false)\n mc.setToRecipients(toRecipents)\n self.presentViewController(mc, animated: true, completion: nil)\n } else {\n println(\"No email account found\")\n }\n }\n}\n\nextension YourVC: MFMailComposeViewControllerDelegate {\n func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {\n switch result.value {\n case MFMailComposeResultCancelled.value:\n println(\"Mail Cancelled\")\n case MFMailComposeResultSaved.value:\n println(\"Mail Saved\")\n case MFMailComposeResultSent.value:\n println(\"Mail Sent\")\n case MFMailComposeResultFailed.value:\n println(\"Mail Failed\")\n default:\n break\n }\n self.dismissViewControllerAnimated(false, completion: nil)\n }\n}\n"
},
{
"answer_id": 32719258,
"author": "brian.clear",
"author_id": 181947,
"author_profile": "https://Stackoverflow.com/users/181947",
"pm_score": 2,
"selected": false,
"text": "func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){\n if let error = error{\n print(\"Error: \\(error)\")\n }else{\n //NO Error\n //------------------------------------------------\n var feedbackMsg = \"\"\n\n switch result.rawValue {\n case MFMailComposeResultCancelled.rawValue:\n feedbackMsg = \"Mail Cancelled\"\n case MFMailComposeResultSaved.rawValue:\n feedbackMsg = \"Mail Saved\"\n case MFMailComposeResultSent.rawValue:\n feedbackMsg = \"Mail Sent\"\n case MFMailComposeResultFailed.rawValue:\n feedbackMsg = \"Mail Failed\"\n default:\n feedbackMsg = \"\"\n }\n\n print(\"Mail: \\(feedbackMsg)\")\n\n //------------------------------------------------\n }\n}\n"
},
{
"answer_id": 36671199,
"author": "Evdzhan Mustafa",
"author_id": 2868955,
"author_profile": "https://Stackoverflow.com/users/2868955",
"pm_score": 2,
"selected": false,
"text": "import Foundation\nimport MessageUI\n\nclass MailSender: NSObject, MFMailComposeViewControllerDelegate {\n\n let parentVC: UIViewController\n\n init(parentVC: UIViewController) {\n self.parentVC = parentVC\n super.init()\n }\n\n func send(title: String, messageBody: String, toRecipients: [String]) {\n if MFMailComposeViewController.canSendMail() {\n let mc: MFMailComposeViewController = MFMailComposeViewController()\n mc.mailComposeDelegate = self\n mc.setSubject(title)\n mc.setMessageBody(messageBody, isHTML: false)\n mc.setToRecipients(toRecipients)\n parentVC.presentViewController(mc, animated: true, completion: nil)\n } else {\n print(\"No email account found.\")\n }\n }\n\n func mailComposeController(controller: MFMailComposeViewController,\n didFinishWithResult result: MFMailComposeResult, error: NSError?) {\n\n switch result.rawValue {\n case MFMailComposeResultCancelled.rawValue: print(\"Mail Cancelled\")\n case MFMailComposeResultSaved.rawValue: print(\"Mail Saved\")\n case MFMailComposeResultSent.rawValue: print(\"Mail Sent\")\n case MFMailComposeResultFailed.rawValue: print(\"Mail Failed\")\n default: break\n }\n\n parentVC.dismissViewControllerAnimated(false, completion: nil)\n }\n}\n var ms: MailSender?\n\n@IBAction func onSendPressed(sender: AnyObject) {\n ms = MailSender(parentVC: self)\n let title = \"Title\"\n let messageBody = \"https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application this question.\"\n let toRecipents = [\"foo@bar.com\"]\n ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)\n}\n"
},
{
"answer_id": 38790744,
"author": "Patrick R",
"author_id": 6583644,
"author_profile": "https://Stackoverflow.com/users/6583644",
"pm_score": 2,
"selected": false,
"text": "#import <MessageUI/MessageUI.h> @interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>\n - (void) sendEmail {\n // Check if your app support the email.\n if ([MFMailComposeViewController canSendMail]) {\n // Create an object of mail composer.\n MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];\n // Add delegate to your self.\n mailComposer.mailComposeDelegate = self;\n // Add recipients to mail if you do not want to add default recipient then remove below line.\n [mailComposer setToRecipients:@[<add here your recipient objects>]];\n // Write email subject.\n [mailComposer setSubject:@“<Your Subject Here>”];\n // Set your email body and if body contains HTML then Pass “YES” in isHTML.\n [mailComposer setMessageBody:@“<Your Message Body>” isHTML:NO];\n // Show your mail composer.\n [self presentViewController:mailComposer animated:YES completion:NULL];\n }\n else {\n // Here you can show toast to user about not support to sending email.\n}\n}\n - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error {\n[controller dismissViewControllerAnimated:TRUE completion:nil];\n\n\nswitch (result) {\n case MFMailComposeResultSaved: {\n // Add code on save mail to draft.\n break;\n}\ncase MFMailComposeResultSent: {\n // Add code on sent a mail.\n break;\n}\ncase MFMailComposeResultCancelled: {\n // Add code on cancel a mail.\n break;\n}\ncase MFMailComposeResultFailed: {\n // Add code on failed to send a mail.\n break;\n}\ndefault:\n break;\n}\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39599/"
] |
310,947 | <p>Accepting the possibility of extreme ridicule, I must admit that I really miss sun Teamware's filemerge tool. I have switched from solaris to red hat linux, and find myself regularly missing filemerge (not to be confused with the Apple tool of the same name), as well as the solaris version of pstack (which worked on core files just as well as pids). </p>
<p>Do any experts out there have any advice of consolation? Better merging tools that incorporate ancestry? A single-line way to view the call stack of a core file?</p>
<p>Please help!</p>
| [
{
"answer_id": 6963805,
"author": "alvinabad",
"author_id": 293593,
"author_profile": "https://Stackoverflow.com/users/293593",
"pm_score": 1,
"selected": false,
"text": "kdiff3 x.A.cpp x.C.cpp x.P.cpp -o x.M.cpp\n x.A.cpp - ancestor version of x.cpp\nx.C.cpp - child verion of x.cpp\nx.P.cpp - parent version of x.cpp\nx.M.cpp - merged file\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39870/"
] |
310,964 | <p>I'm learning functional programming, and have tried to solve a couple problems in a functional style. One thing I experienced, while dividing up my problem into functions, was it seemed I had two options: use several disparate functions with similar parameter lists, or using nested functions which, as closures, can simply refer to bindings in the parent function. </p>
<p>Though I ended up going with the second approach, because it made function calls smaller and it seemed to "feel" better, from my reading it seems like I may be missing one of the main points of functional programming, in that this seems "side-effecty"? Now granted, these nested functions cannot modify the outer bindings, as the language I was using prevents that, but if you look at each individual inner function, you can't say "given the same parameters, this function will return the same results" because they do use the variables from the parent scope... am I right? </p>
<p>What is the desirable way to proceed? </p>
<p>Thanks!</p>
| [
{
"answer_id": 310971,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "(define (foo a)\n (define (bar b)\n (+ a b)) ; getting a from outer scope, not purely functional\n (bar 3))\n\n(define (foo a)\n (define (bar a b)\n (+ a b)) ; getting a from function parameters, purely functional\n (bar a 3))\n\n\n(define (bar a b) ; since this is purely functional, we can remove it from its\n (+ a b)) ; environment and it still works\n\n(define (foo a)\n (bar a 3))\n"
},
{
"answer_id": 311006,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 3,
"selected": true,
"text": "let factorial n =\n let rec facHelper p n =\n if n = 1 then p else facHelper (p*n) (n-1)\n in\n facHelper 1 n\n facHelper p"
},
{
"answer_id": 311271,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 1,
"selected": false,
"text": "putLines :: [String] -> IO ()\nputLines lines = putStr string\n where string = concat lines\n string lines"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38803/"
] |
310,974 | <p>Very simply, what is tail-call optimization?</p>
<p>More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?</p>
| [
{
"answer_id": 310980,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 11,
"selected": true,
"text": "(define (fact x)\n (if (= x 0) 1\n (* x (fact (- x 1)))))\n\n(define (fact x)\n (define (fact-tail x accum)\n (if (= x 0) accum\n (fact-tail (- x 1) (* x accum))))\n (fact-tail x 1))\n (fact 3)\n(* 3 (fact 2))\n(* 3 (* 2 (fact 1)))\n(* 3 (* 2 (* 1 (fact 0))))\n(* 3 (* 2 (* 1 1)))\n(* 3 (* 2 1))\n(* 3 2)\n6\n (fact 3)\n(fact-tail 3 1)\n(fact-tail 2 3)\n(fact-tail 1 6)\n(fact-tail 0 6)\n6\n"
},
{
"answer_id": 310987,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 8,
"selected": false,
"text": "from dis import dis\n\ndef fact(n):\n if n == 0:\n return 1\n return n * fact(n-1)\n\n\ndis(fact)\n 2 0 LOAD_FAST 0 (n)\n 2 LOAD_CONST 1 (0)\n 4 COMPARE_OP 2 (==)\n 6 POP_JUMP_IF_FALSE 12\n\n 3 8 LOAD_CONST 2 (1)\n 10 RETURN_VALUE\n\n 4 >> 12 LOAD_FAST 0 (n)\n 14 LOAD_GLOBAL 0 (fact)\n 16 LOAD_FAST 0 (n)\n 18 LOAD_CONST 2 (1)\n 20 BINARY_SUBTRACT\n 22 CALL_FUNCTION 1\n 24 BINARY_MULTIPLY\n 26 RETURN_VALUE\n def fact_h(n, acc):\n if n == 0:\n return acc\n return fact_h(n-1, acc*n)\n\ndef fact(n):\n return fact_h(n, 1)\n\n\ndis(fact)\n 2 0 LOAD_GLOBAL 0 (fact_h)\n 2 LOAD_FAST 0 (n)\n 4 LOAD_CONST 1 (1)\n 6 CALL_FUNCTION 2\n 8 RETURN_VALUE\n"
},
{
"answer_id": 9814654,
"author": "Christoph",
"author_id": 48015,
"author_profile": "https://Stackoverflow.com/users/48015",
"pm_score": 9,
"selected": false,
"text": "unsigned fac(unsigned n)\n{\n if (n < 2) return 1;\n return n * fac(n - 1);\n}\n fac() unsigned fac(unsigned n)\n{\n if (n < 2) return 1;\n unsigned acc = fac(n - 1);\n return n * acc;\n}\n fac() unsigned fac(unsigned n)\n{\n return fac_tailrec(1, n);\n}\n\nunsigned fac_tailrec(unsigned acc, unsigned n)\n{\n if (n < 2) return acc;\n return fac_tailrec(n * acc, n - 1);\n}\n unsigned fac_tailrec(unsigned acc, unsigned n)\n{\nTOP:\n if (n < 2) return acc;\n acc = n * acc;\n n = n - 1;\n goto TOP;\n}\n fac() unsigned fac(unsigned n)\n{\n unsigned acc = 1;\n\nTOP:\n if (n < 2) return acc;\n acc = n * acc;\n n = n - 1;\n goto TOP;\n}\n unsigned fac(unsigned n)\n{\n unsigned acc = 1;\n\n for (; n > 1; --n)\n acc *= n;\n\n return acc;\n}\n"
},
{
"answer_id": 12035807,
"author": "grillSandwich",
"author_id": 1589088,
"author_profile": "https://Stackoverflow.com/users/1589088",
"pm_score": 2,
"selected": false,
"text": "void eternity()\n{\n eternity();\n}\n"
},
{
"answer_id": 12126993,
"author": "btiernay",
"author_id": 527333,
"author_profile": "https://Stackoverflow.com/users/527333",
"pm_score": 6,
"selected": false,
"text": "sub foo (int a) {\n a += 15;\n return bar(a);\n}\n return somefunc(); pop stack frame; goto somefunc(); bar foo bar goto bar Foo bar foo bar bar foo foo sub foo (int a, int b) {\n if (b == 1) {\n return a;\n } else {\n return foo(a*a + a, b - 1);\n }\n sub foo (int a, int b) {\n label:\n if (b == 1) {\n return a;\n } else {\n a = a*a + a;\n b = b - 1;\n goto label;\n }\n"
},
{
"answer_id": 55230417,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 5,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nunsigned factorial(unsigned n) {\n if (n == 1) {\n return 1;\n }\n return n * factorial(n - 1);\n}\n\nint main(int argc, char **argv) {\n int input;\n if (argc > 1) {\n input = strtoul(argv[1], NULL, 0);\n } else {\n input = 5;\n }\n printf(\"%u\\n\", factorial(input));\n return EXIT_SUCCESS;\n}\n gcc -O1 -foptimize-sibling-calls -ggdb3 -std=c99 -Wall -Wextra -Wpedantic \\\n -o tail_call.out tail_call.c\nobjdump -d tail_call.out\n -foptimize-sibling-calls man gcc -foptimize-sibling-calls\n Optimize sibling and tail recursive calls.\n\n Enabled at levels -O2, -O3, -Os.\n -O1 -O0 -O3 -fno-optimize-sibling-calls 0000000000001145 <factorial>:\n 1145: 89 f8 mov %edi,%eax\n 1147: 83 ff 01 cmp $0x1,%edi\n 114a: 74 10 je 115c <factorial+0x17>\n 114c: 53 push %rbx\n 114d: 89 fb mov %edi,%ebx\n 114f: 8d 7f ff lea -0x1(%rdi),%edi\n 1152: e8 ee ff ff ff callq 1145 <factorial>\n 1157: 0f af c3 imul %ebx,%eax\n 115a: 5b pop %rbx\n 115b: c3 retq\n 115c: c3 retq\n -foptimize-sibling-calls 0000000000001145 <factorial>:\n 1145: b8 01 00 00 00 mov $0x1,%eax\n 114a: 83 ff 01 cmp $0x1,%edi\n 114d: 74 0e je 115d <factorial+0x18>\n 114f: 8d 57 ff lea -0x1(%rdi),%edx\n 1152: 0f af c7 imul %edi,%eax\n 1155: 89 d7 mov %edx,%edi\n 1157: 83 fa 01 cmp $0x1,%edx\n 115a: 75 f3 jne 114f <factorial+0xa>\n 115c: c3 retq\n 115d: 89 f8 mov %edi,%eax\n 115f: c3 retq\n -fno-optimize-sibling-calls callq push %rbx %rbx edi n ebx factorial factorial edi == n-1 ebx factorial n -foptimize-sibling-calls goto factorial je jne"
},
{
"answer_id": 60784854,
"author": "Peter Driscoll",
"author_id": 4139508,
"author_profile": "https://Stackoverflow.com/users/4139508",
"pm_score": 0,
"selected": false,
"text": "f x = g x\n f x = if c x then g x else h x.\n if true then g x else h x ---> g x\n\nf x ---> h x\n class simple_expresion\n{\n ...\npublic:\n virtual ximple_value *DoEvaluate() const = 0;\n};\n\nclass simple_value\n{\n ...\n};\n\nclass simple_function : public simple_expresion\n{\n ...\nprivate:\n simple_expresion *m_Function;\n simple_expresion *m_Parameter;\n\npublic:\n virtual simple_value *DoEvaluate() const\n {\n vector<simple_expresion *> parameterList;\n parameterList->push_back(m_Parameter);\n return m_Function->Call(parameterList);\n }\n};\n\nclass simple_if : public simple_function\n{\nprivate:\n simple_expresion *m_Condition;\n simple_expresion *m_Positive;\n simple_expresion *m_Negative;\n\npublic:\n simple_value *DoEvaluate() const\n {\n if (m_Condition.DoEvaluate()->IsTrue())\n {\n return m_Positive.DoEvaluate();\n }\n else\n {\n return m_Negative.DoEvaluate();\n }\n }\n}\n class tco_expresion\n{\n ...\npublic:\n virtual tco_expresion *DoEvaluate() const = 0;\n virtual bool IsValue()\n {\n return false;\n }\n};\n\nclass tco_value\n{\n ...\npublic:\n virtual bool IsValue()\n {\n return true;\n }\n};\n\nclass tco_function : public tco_expresion\n{\n ...\nprivate:\n tco_expresion *m_Function;\n tco_expresion *m_Parameter;\n\npublic:\n virtual tco_expression *DoEvaluate() const\n {\n vector< tco_expression *> parameterList;\n tco_expression *function = const_cast<SNI_Function *>(this);\n while (!function->IsValue())\n {\n function = function->DoCall(parameterList);\n }\n return function;\n }\n\n tco_expresion *DoCall(vector<tco_expresion *> &p_ParameterList)\n {\n p_ParameterList.push_back(m_Parameter);\n return m_Function;\n }\n};\n\nclass tco_if : public tco_function\n{\nprivate:\n tco_expresion *m_Condition;\n tco_expresion *m_Positive;\n tco_expresion *m_Negative;\n\n tco_expresion *DoEvaluate() const\n {\n if (m_Condition.DoEvaluate()->IsTrue())\n {\n return m_Positive;\n }\n else\n {\n return m_Negative;\n }\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38812/"
] |
310,981 | <p>I am working on lock free structure with g++ compiler. It seems that with -o1 switch, g++ will change the execution order of my code. How can I forbid g++'s optimization on certain part of my code while maintain the optimization to other part? I know I can split it to two files and link them, but it looks ugly.</p>
| [
{
"answer_id": 310980,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 11,
"selected": true,
"text": "(define (fact x)\n (if (= x 0) 1\n (* x (fact (- x 1)))))\n\n(define (fact x)\n (define (fact-tail x accum)\n (if (= x 0) accum\n (fact-tail (- x 1) (* x accum))))\n (fact-tail x 1))\n (fact 3)\n(* 3 (fact 2))\n(* 3 (* 2 (fact 1)))\n(* 3 (* 2 (* 1 (fact 0))))\n(* 3 (* 2 (* 1 1)))\n(* 3 (* 2 1))\n(* 3 2)\n6\n (fact 3)\n(fact-tail 3 1)\n(fact-tail 2 3)\n(fact-tail 1 6)\n(fact-tail 0 6)\n6\n"
},
{
"answer_id": 310987,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 8,
"selected": false,
"text": "from dis import dis\n\ndef fact(n):\n if n == 0:\n return 1\n return n * fact(n-1)\n\n\ndis(fact)\n 2 0 LOAD_FAST 0 (n)\n 2 LOAD_CONST 1 (0)\n 4 COMPARE_OP 2 (==)\n 6 POP_JUMP_IF_FALSE 12\n\n 3 8 LOAD_CONST 2 (1)\n 10 RETURN_VALUE\n\n 4 >> 12 LOAD_FAST 0 (n)\n 14 LOAD_GLOBAL 0 (fact)\n 16 LOAD_FAST 0 (n)\n 18 LOAD_CONST 2 (1)\n 20 BINARY_SUBTRACT\n 22 CALL_FUNCTION 1\n 24 BINARY_MULTIPLY\n 26 RETURN_VALUE\n def fact_h(n, acc):\n if n == 0:\n return acc\n return fact_h(n-1, acc*n)\n\ndef fact(n):\n return fact_h(n, 1)\n\n\ndis(fact)\n 2 0 LOAD_GLOBAL 0 (fact_h)\n 2 LOAD_FAST 0 (n)\n 4 LOAD_CONST 1 (1)\n 6 CALL_FUNCTION 2\n 8 RETURN_VALUE\n"
},
{
"answer_id": 9814654,
"author": "Christoph",
"author_id": 48015,
"author_profile": "https://Stackoverflow.com/users/48015",
"pm_score": 9,
"selected": false,
"text": "unsigned fac(unsigned n)\n{\n if (n < 2) return 1;\n return n * fac(n - 1);\n}\n fac() unsigned fac(unsigned n)\n{\n if (n < 2) return 1;\n unsigned acc = fac(n - 1);\n return n * acc;\n}\n fac() unsigned fac(unsigned n)\n{\n return fac_tailrec(1, n);\n}\n\nunsigned fac_tailrec(unsigned acc, unsigned n)\n{\n if (n < 2) return acc;\n return fac_tailrec(n * acc, n - 1);\n}\n unsigned fac_tailrec(unsigned acc, unsigned n)\n{\nTOP:\n if (n < 2) return acc;\n acc = n * acc;\n n = n - 1;\n goto TOP;\n}\n fac() unsigned fac(unsigned n)\n{\n unsigned acc = 1;\n\nTOP:\n if (n < 2) return acc;\n acc = n * acc;\n n = n - 1;\n goto TOP;\n}\n unsigned fac(unsigned n)\n{\n unsigned acc = 1;\n\n for (; n > 1; --n)\n acc *= n;\n\n return acc;\n}\n"
},
{
"answer_id": 12035807,
"author": "grillSandwich",
"author_id": 1589088,
"author_profile": "https://Stackoverflow.com/users/1589088",
"pm_score": 2,
"selected": false,
"text": "void eternity()\n{\n eternity();\n}\n"
},
{
"answer_id": 12126993,
"author": "btiernay",
"author_id": 527333,
"author_profile": "https://Stackoverflow.com/users/527333",
"pm_score": 6,
"selected": false,
"text": "sub foo (int a) {\n a += 15;\n return bar(a);\n}\n return somefunc(); pop stack frame; goto somefunc(); bar foo bar goto bar Foo bar foo bar bar foo foo sub foo (int a, int b) {\n if (b == 1) {\n return a;\n } else {\n return foo(a*a + a, b - 1);\n }\n sub foo (int a, int b) {\n label:\n if (b == 1) {\n return a;\n } else {\n a = a*a + a;\n b = b - 1;\n goto label;\n }\n"
},
{
"answer_id": 55230417,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 5,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nunsigned factorial(unsigned n) {\n if (n == 1) {\n return 1;\n }\n return n * factorial(n - 1);\n}\n\nint main(int argc, char **argv) {\n int input;\n if (argc > 1) {\n input = strtoul(argv[1], NULL, 0);\n } else {\n input = 5;\n }\n printf(\"%u\\n\", factorial(input));\n return EXIT_SUCCESS;\n}\n gcc -O1 -foptimize-sibling-calls -ggdb3 -std=c99 -Wall -Wextra -Wpedantic \\\n -o tail_call.out tail_call.c\nobjdump -d tail_call.out\n -foptimize-sibling-calls man gcc -foptimize-sibling-calls\n Optimize sibling and tail recursive calls.\n\n Enabled at levels -O2, -O3, -Os.\n -O1 -O0 -O3 -fno-optimize-sibling-calls 0000000000001145 <factorial>:\n 1145: 89 f8 mov %edi,%eax\n 1147: 83 ff 01 cmp $0x1,%edi\n 114a: 74 10 je 115c <factorial+0x17>\n 114c: 53 push %rbx\n 114d: 89 fb mov %edi,%ebx\n 114f: 8d 7f ff lea -0x1(%rdi),%edi\n 1152: e8 ee ff ff ff callq 1145 <factorial>\n 1157: 0f af c3 imul %ebx,%eax\n 115a: 5b pop %rbx\n 115b: c3 retq\n 115c: c3 retq\n -foptimize-sibling-calls 0000000000001145 <factorial>:\n 1145: b8 01 00 00 00 mov $0x1,%eax\n 114a: 83 ff 01 cmp $0x1,%edi\n 114d: 74 0e je 115d <factorial+0x18>\n 114f: 8d 57 ff lea -0x1(%rdi),%edx\n 1152: 0f af c7 imul %edi,%eax\n 1155: 89 d7 mov %edx,%edi\n 1157: 83 fa 01 cmp $0x1,%edx\n 115a: 75 f3 jne 114f <factorial+0xa>\n 115c: c3 retq\n 115d: 89 f8 mov %edi,%eax\n 115f: c3 retq\n -fno-optimize-sibling-calls callq push %rbx %rbx edi n ebx factorial factorial edi == n-1 ebx factorial n -foptimize-sibling-calls goto factorial je jne"
},
{
"answer_id": 60784854,
"author": "Peter Driscoll",
"author_id": 4139508,
"author_profile": "https://Stackoverflow.com/users/4139508",
"pm_score": 0,
"selected": false,
"text": "f x = g x\n f x = if c x then g x else h x.\n if true then g x else h x ---> g x\n\nf x ---> h x\n class simple_expresion\n{\n ...\npublic:\n virtual ximple_value *DoEvaluate() const = 0;\n};\n\nclass simple_value\n{\n ...\n};\n\nclass simple_function : public simple_expresion\n{\n ...\nprivate:\n simple_expresion *m_Function;\n simple_expresion *m_Parameter;\n\npublic:\n virtual simple_value *DoEvaluate() const\n {\n vector<simple_expresion *> parameterList;\n parameterList->push_back(m_Parameter);\n return m_Function->Call(parameterList);\n }\n};\n\nclass simple_if : public simple_function\n{\nprivate:\n simple_expresion *m_Condition;\n simple_expresion *m_Positive;\n simple_expresion *m_Negative;\n\npublic:\n simple_value *DoEvaluate() const\n {\n if (m_Condition.DoEvaluate()->IsTrue())\n {\n return m_Positive.DoEvaluate();\n }\n else\n {\n return m_Negative.DoEvaluate();\n }\n }\n}\n class tco_expresion\n{\n ...\npublic:\n virtual tco_expresion *DoEvaluate() const = 0;\n virtual bool IsValue()\n {\n return false;\n }\n};\n\nclass tco_value\n{\n ...\npublic:\n virtual bool IsValue()\n {\n return true;\n }\n};\n\nclass tco_function : public tco_expresion\n{\n ...\nprivate:\n tco_expresion *m_Function;\n tco_expresion *m_Parameter;\n\npublic:\n virtual tco_expression *DoEvaluate() const\n {\n vector< tco_expression *> parameterList;\n tco_expression *function = const_cast<SNI_Function *>(this);\n while (!function->IsValue())\n {\n function = function->DoCall(parameterList);\n }\n return function;\n }\n\n tco_expresion *DoCall(vector<tco_expresion *> &p_ParameterList)\n {\n p_ParameterList.push_back(m_Parameter);\n return m_Function;\n }\n};\n\nclass tco_if : public tco_function\n{\nprivate:\n tco_expresion *m_Condition;\n tco_expresion *m_Positive;\n tco_expresion *m_Negative;\n\n tco_expresion *DoEvaluate() const\n {\n if (m_Condition.DoEvaluate()->IsTrue())\n {\n return m_Positive;\n }\n else\n {\n return m_Negative;\n }\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
310,996 | <p>I am calling a batch file from Javascript in this fashion:</p>
<pre><code>function runBatch(){
var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath("C:\\test.bat");
var run = Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
var parameters = ["hi"];
run.run(false, parameters,parameters.length);
}
</code></pre>
<p>my test batch file is:</p>
<pre><code>echo on
echo %1
pause
exit
</code></pre>
<p>Each time I call a batch file, however, the command prompt is not displayed, as it would be if I simply ran the batch file from the desktop. How can I remedy this and display a command prompt for the batch file?</p>
<p><strong>Edit</strong>
To be clear, the cmd.exe process is launched - I can see it in the task bar. But no window gets displayed. This snippet behaves similarly:</p>
<pre><code>function runCmd(){
var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath("C:\\WINDOWS\\system32\\cmd.exe");
var run = Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
run.run(false, null,0);
}
</code></pre>
| [
{
"answer_id": 311940,
"author": "ng.mangine",
"author_id": 37784,
"author_profile": "https://Stackoverflow.com/users/37784",
"pm_score": 1,
"selected": false,
"text": "function runBatch(){\n var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);\n exe.initWithPath(\"C:\\\\test.bat\");\n exe.launch();\n}\n"
},
{
"answer_id": 312018,
"author": "pc1oad1etter",
"author_id": 525,
"author_profile": "https://Stackoverflow.com/users/525",
"pm_score": 2,
"selected": false,
"text": "f = fopen(\"temp.bat\"); \nfprintf(f, \"other.bat 1 2 3 4 5\"); \nfclose(f); \nexec(\"temp.bat\");\n"
},
{
"answer_id": 656397,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "var lPath = getWorkingDir.path + \"\\\\..\\\\..\\\\WINDOWS\\\\system32\\\\win.com\";\nlFile.initWithPath(lPath);\nvar process = Components.classes[\"@mozilla.org/process/util;1\"].createInstance(Components.interfaces.nsIProcess);\nprocess.init(lFile);\n var args = [\"cmd.exe\"];\nprocess.run(false, args, args.length);\n"
},
{
"answer_id": 1282346,
"author": "izogfif",
"author_id": 156973,
"author_profile": "https://Stackoverflow.com/users/156973",
"pm_score": 0,
"selected": false,
"text": "const FileFactory = new Components.Constructor(\"@mozilla.org/file/local;1\",\"nsILocalFile\",\"initWithPath\");\nvar str_LocalProgram = \"D:\\\\Windows\\\\system32\\\\cmd.exe\";\nvar obj_Program = new FileFactory(str_LocalProgram); \nvar process = Components.classes[\"@mozilla.org/process/util;1\"].createInstance(Components.interfaces.nsIProcess);\nprocess.init(obj_Program);\nvar args = [\"/C\", \"regedit.exe\"];\nprocess.run(true, args, args.length);\n"
},
{
"answer_id": 4959767,
"author": "ledm78",
"author_id": 611694,
"author_profile": "https://Stackoverflow.com/users/611694",
"pm_score": 0,
"selected": false,
"text": "function runBatch(){\n var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);\n exe.initWithPath(\"***C:\\ \\test.bat***\");\n var run = Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);\n run.init(exe);\n var parameters = [\"hi\"];\n run.run(false, parameters,parameters.length);\n}\n function runBatch(){\n var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);\n exe.initWithPath(\"***C:\\test.bat***\");\n var run = Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);\n run.init(exe);\n var parameters = [\"hi\"];\n run.run(false, parameters,parameters.length);\n}\n"
},
{
"answer_id": 6732800,
"author": "Albert",
"author_id": 850005,
"author_profile": "https://Stackoverflow.com/users/850005",
"pm_score": -1,
"selected": false,
"text": "<script>\n\n function callLight2()\n {\n\n netscape.security.PrivilegeManager.enablePrivilege(\n 'UniversalXPConnect'\n );\n var exe = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);\n // exe.initWithPath(C:\\\\Windows\\\\system32\\\\cmd.exe\"\");\n exe.initWithPath(\"/usr/bin/gnome-terminal\");\n\n var run = Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);\n run.init(exe); \n\n var parameters = [\"-e\", \"/usr/bin/ip_connect_up.sh 2 2 3 4 5 6\"];\n // var parameters = [\"/C\", \"regedit.exe\"];\n // var parameters = [\"hi\"];\n run.run(true, parameters,parameters.length);\n\n }\n\n\n</script>\n\n\n<a href=\"#\" onClick =\"callLight2()\">start</a>\n"
},
{
"answer_id": 15621035,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " let file = uri.QueryInterface(Components.interfaces.nsIFileURL).file;\n\n let run = Components.classes['@mozilla.org/process/util;1']\n .createInstance(Components.interfaces.nsIProcess);\n\n let path = file.path;\n\n if(file.exists())\n {\n // quick security check\n if(file.isExecutable())\n {\n // show error message\n return;\n }\n\n let localfile = file.QueryInterface(Components.interfaces.nsILocalFile);\n\n if(localfile != null)\n {\n if (app == \"app1\")\n {\n localfile.initWithPath(\"C:\\\\app1.bat\"); \n }\n else\n {\n localfile.initWithPath(\"C:\\\\app2.bat\");\n }\n run.init(localfile);\n var parameters = [path];\n run.run(false, parameters, parameters.length);\n }\n else\n {\n // show error message\n }\n }\n else\n {\n // show error message\n }\n @ECHO OFF\nSTART \"application.exe\" %1\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/310996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525/"
] |
311,043 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/311054/how-do-i-select-last-5-rows-in-a-table-without-sorting">How do I select last 5 rows in a table without sorting?</a> </p>
</blockquote>
<p>I want to select the top 10 records from a table in SQL Server without arranging the table in ascending or descending order.</p>
| [
{
"answer_id": 311056,
"author": "smoothdeveloper",
"author_id": 17049,
"author_profile": "https://Stackoverflow.com/users/17049",
"pm_score": 4,
"selected": false,
"text": "select top 10 * from [tablename] order by newid()\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,050 | <p>I have a scrolling div with Three linkbuttons and three differents divs. I need to apply CSS to active linkbutton as soon as button is clicked.The codes used by me are:</p>
<pre><code>protected void btnNetwork_Click(object sender, EventArgs e)
{
this.btnForecast.CssClass = "li_1";
this.btnBlog.CssClass = "li_2";
this.btnNetwork.CssClass = "li_3_active";
this.btnNetwork.ForeColor = System.Drawing.Color.White;
lblMsg.Visible = false;
BindGW("-----------------------------------");
Forecast.Visible = false;
Blog.Visible = false;
Network.Visible = true;
}
</code></pre>
<p>Thanks & Regards,</p>
<p>Khushi</p>
| [
{
"answer_id": 311233,
"author": "Pradeep Kumar Mishra",
"author_id": 22710,
"author_profile": "https://Stackoverflow.com/users/22710",
"pm_score": 2,
"selected": false,
"text": "$get('btnId').setAttribute(\"class\", \"some_class_name\");\n"
},
{
"answer_id": 3167645,
"author": "Jags",
"author_id": 382244,
"author_profile": "https://Stackoverflow.com/users/382244",
"pm_score": 0,
"selected": false,
"text": "body \n{ \n}\n\n.style1\n{\n color: #000080;\n}\n protected void Button1_Click(object sender, EventArgs e)\n{\n this.Label1.CssClass = \"style1\";\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39599/"
] |
311,051 | <p>I'm converting some Actionscript code from AS2 tp AS3, and I've eventually managed to get most of it to work again (it's allmost a totally different language, sharing just a little syntax similarity). One of the last things that still doesn't work, is the code for loading an external image.</p>
<p>Perhaps this has changed in AS3 but I really thought it was strange that to load an image you use <code>loadVideo</code>, why not loadImage? (on the other hand a flash application is constantly called a flash <em>video</em> even when it's not used for animation at all). This doesn't work anymore, and what I've found is a pretty complex code that is said to replace this oneliner <code>imageholder.loadVideo(url);</code> is this:</p>
<pre><code>var urlreq:URLRequest = new URLRequest(url);
var theloader:Loader = new URLLoader();
theloader.load(urlreq);
theloader.addEventListener(Event.COMPLETE, function(event:Event):void {
imageholder.addChild(theloader);
}
);
</code></pre>
<p>But this doesn't work.. What I am doing wrong, and is there a more suited function to load images in AS3?</p>
| [
{
"answer_id": 311157,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "for (i = 0; i<imgHolders.length; i++) {\n var loader:Loader = imgHolders[i].getChildByName(\"imgloader\"+i);\n if (loader) {\n loader.unload();\n } else {\n loader = new Loader();\n loader.name = \"imgloader\" + i;\n // Does't seem to work, commented out.\n //loader.addEventListener(Event.COMPLETE, centerimage);\n imgHolders[i].addChild(loader);\n }\n}\n var loader:Loader = imgHolders[index].getChildByName(\"imgloader\"+index);\nloader.load(new URLRequest(newurl);\n trace(\"centerImage\");"
},
{
"answer_id": 312894,
"author": "matt lohkamp",
"author_id": 14026,
"author_profile": "https://Stackoverflow.com/users/14026",
"pm_score": 2,
"selected": true,
"text": "import flash.display.Loader;\nimport flash.event.Event;\nimport flash.net.URLRequest;\n\nvar imageLoader:Loader = new Loader();\nimageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event){\n // e.target.content is the newly-loaded image, feel free to addChild it where ever it needs to go...\n});\nimageLoader.load(new URLRequest('yourImage.jpg'));\n"
},
{
"answer_id": 319810,
"author": "Matt Rix",
"author_id": 40922,
"author_profile": "https://Stackoverflow.com/users/40922",
"pm_score": 2,
"selected": false,
"text": "//this is WRONG\nloader.addEventListener(Event.COMPLETE, onLoad);\n\n//this is RIGHT\nloader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26115/"
] |
311,052 | <p>I'm looking for a way to change the CSS rules for pseudo-class selectors (such as :link, :hover, etc.) from JavaScript.</p>
<p>So an analogue of the CSS code: <code>a:hover { color: red }</code> in JS.</p>
<p>I couldn't find the answer anywhere else; if anyone knows that this is something browsers do not support, that would be a helpful result as well.</p>
| [
{
"answer_id": 311437,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 8,
"selected": false,
"text": "#elid:hover { background: red; }\n document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);\ndocument.styleSheets[0].cssRules[0].style.backgroundColor= 'red';\n document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);\ndocument.styleSheets[0].rules[0].style.backgroundColor= 'red';\n"
},
{
"answer_id": 322240,
"author": "Nathaniel Reinhart",
"author_id": 41122,
"author_profile": "https://Stackoverflow.com/users/41122",
"pm_score": 2,
"selected": false,
"text": "a:hover { background: red; }\n.theme1 a:hover { background: blue; }\n // Look up some good add/remove className code if you want to do this\n// This is really simplified\n\ndocument.body.className += \" theme1\"; \n"
},
{
"answer_id": 1016701,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "addCssRule = function(/* string */ selector, /* string */ rule) {\n if (document.styleSheets) {\n if (!document.styleSheets.length) {\n var head = document.getElementsByTagName('head')[0];\n head.appendChild(bc.createEl('style'));\n }\n\n var i = document.styleSheets.length-1;\n var ss = document.styleSheets[i];\n\n var l=0;\n if (ss.cssRules) {\n l = ss.cssRules.length;\n } else if (ss.rules) {\n // IE\n l = ss.rules.length;\n }\n\n if (ss.insertRule) {\n ss.insertRule(selector + ' {' + rule + '}', l);\n } else if (ss.addRule) {\n // IE\n ss.addRule(selector, rule, l);\n }\n }\n};\n"
},
{
"answer_id": 2432433,
"author": "TRiG",
"author_id": 209139,
"author_profile": "https://Stackoverflow.com/users/209139",
"pm_score": 3,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"always_on.css\">\n<link rel=\"stylesheet\" title=\"usual\" href=\"preferred.css\"> <!-- on by default -->\n<link rel=\"alternate stylesheet\" title=\"strange\" href=\"alternate.css\"> <!-- off by default -->\n function setActiveStyleSheet(title) {\n var i, a, main;\n for(i=0; (a = document.getElementsByTagName(\"link\")<i>); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1\n && a.getAttribute(\"title\")) {\n a.disabled = true;\n if(a.getAttribute(\"title\") == title) a.disabled = false;\n }\n }\n}\n"
},
{
"answer_id": 14106897,
"author": "Sergio Abreu",
"author_id": 1276883,
"author_profile": "https://Stackoverflow.com/users/1276883",
"pm_score": 3,
"selected": false,
"text": ".class{ /*normal css... */}\n.class[special]:after{ content: 'what you want'}\n function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }\n <element id='x' onclick=\"setSpecial(this.id)\"> ... \n"
},
{
"answer_id": 36768664,
"author": "vasanth",
"author_id": 6234323,
"author_profile": "https://Stackoverflow.com/users/6234323",
"pm_score": -1,
"selected": false,
"text": "$(\"p\").hover(function(){\n$(this).css(\"background-color\", \"yellow\");\n}, function(){\n$(this).css(\"background-color\", \"pink\");\n});\n"
},
{
"answer_id": 42941303,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 0,
"selected": false,
"text": "// If newState is provided add/remove theClass accordingly, otherwise toggle theClass\nfunction toggleClass(elem, theClass, newState) {\n var matchRegExp = new RegExp('(?:^|\\\\s)' + theClass + '(?!\\\\S)', 'g');\n var add = (arguments.length > 2 ? newState : (elem.className.match(matchRegExp) === null));\n\n elem.className = elem.className.replace(matchRegExp, ''); // clear all\n if (add) elem.className += ' ' + theClass;\n}\n\nfunction addCSSclass(rules) {\n var style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(\"\")); // WebKit hack :(\n document.head.appendChild(style);\n var sheet = style.sheet;\n\n rules.forEach((rule, index) => {\n try {\n if (\"insertRule\" in sheet) {\n sheet.insertRule(rule.selector + \"{\" + rule.rule + \"}\", index);\n } else if (\"addRule\" in sheet) {\n sheet.addRule(rule.selector, rule.rule, index);\n }\n } catch (e) {\n // firefox can break here \n }\n \n })\n}\n\nlet div = document.getElementById('mydiv');\naddCSSclass([{\n selector: '.narrowScrollbar::-webkit-scrollbar',\n rule: 'width: 5px'\n },\n {\n selector: '.narrowScrollbar::-webkit-scrollbar-thumb',\n rule: 'background-color:#808080;border-radius:100px'\n }\n]);\ntoggleClass(div, 'narrowScrollbar', true); <div id=\"mydiv\" style=\"height:300px;width:300px;border:solid;overflow-y:scroll\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus\n a diam volutpat, ullamcorper justo eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit\n nec sodales sodales. Etiam eget dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui. Lorem ipsum dolor sit amet, consectetur\n adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus a diam volutpat, ullamcorper justo\n eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit nec sodales sodales. Etiam eget\n dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui.\n</div>"
},
{
"answer_id": 50571368,
"author": "tangle sites",
"author_id": 9860279,
"author_profile": "https://Stackoverflow.com/users/9860279",
"pm_score": 4,
"selected": false,
"text": "const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;\n const styleTag = document.createElement(\"style\");\nstyleTag.innerHTML = cssTemplateString;\ndocument.head.insertAdjacentElement('beforeend', styleTag);\n"
},
{
"answer_id": 64707814,
"author": "Nick Parsons",
"author_id": 5648954,
"author_profile": "https://Stackoverflow.com/users/5648954",
"pm_score": 3,
"selected": false,
"text": "function changeColor(newColor) {\n document.documentElement.style.setProperty(\"--anchor-hover-color\", newColor);\n // ^^^^^^^^^^^-- select the root \n} :root {\n --anchor-hover-color: red;\n}\n\na:hover { \n color: var(--anchor-hover-color); \n} <a href=\"#\">Hover over me</a>\n\n<button onclick=\"changeColor('lime')\">Change to lime</button>\n<button onclick=\"changeColor('red')\">Change to red</button>"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39882/"
] |
311,054 | <p>I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.</p>
| [
{
"answer_id": 311059,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 5 * FROM [TableName]"
},
{
"answer_id": 311067,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": false,
"text": "select * \nfrom issues\nwhere issueid not in (\n select top (\n (select count(*) from issues) - 5\n ) issueid\n from issues\n)\n"
},
{
"answer_id": 311075,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 5 * FROM MyTable\nORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC\n"
},
{
"answer_id": 312182,
"author": "D'Arcy Rittich",
"author_id": 39430,
"author_profile": "https://Stackoverflow.com/users/39430",
"pm_score": 4,
"selected": false,
"text": "select Name \nfrom (\n select top 5 Name \n from MyTable \n order by Name desc\n) a \norder by Name asc\n"
},
{
"answer_id": 312224,
"author": "idstam",
"author_id": 21761,
"author_profile": "https://Stackoverflow.com/users/21761",
"pm_score": 2,
"selected": false,
"text": "USE AdventureWorks;\nGO\nWITH OrderedOrders AS\n(\n SELECT SalesOrderID, OrderDate,\n ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'\n FROM Sales.SalesOrderHeader \n) \nSELECT * \nFROM OrderedOrders \nWHERE RowNumber BETWEEN 50 AND 60;\n"
},
{
"answer_id": 661430,
"author": "msuvajac",
"author_id": 71899,
"author_profile": "https://Stackoverflow.com/users/71899",
"pm_score": 5,
"selected": false,
"text": "SELECT * FROM [MyTable] WHERE [id] > (SELECT MAX([id]) - 5 FROM [MyTable])\n"
},
{
"answer_id": 2490531,
"author": "Shrabani Joarder",
"author_id": 298818,
"author_profile": "https://Stackoverflow.com/users/298818",
"pm_score": 1,
"selected": false,
"text": "select * \nfrom table \norder by empno(primary key) desc \nfetch first 5 rows only\n"
},
{
"answer_id": 3934761,
"author": "M.M.F",
"author_id": 475957,
"author_profile": "https://Stackoverflow.com/users/475957",
"pm_score": 3,
"selected": false,
"text": "select * from users\nwhere user_id > \n( (select COUNT(*) from users) - 5)\n select TOP 5 from users order by user_id DESC\n"
},
{
"answer_id": 10170167,
"author": "Balaji",
"author_id": 1335750,
"author_profile": "https://Stackoverflow.com/users/1335750",
"pm_score": -1,
"selected": false,
"text": "select count(*) from TABLE\nselect top count * from TABLE where 'primary key row' NOT IN (select top (count-5) 'primary key row' from TABLE)\n"
},
{
"answer_id": 17861470,
"author": "Rob",
"author_id": 315938,
"author_profile": "https://Stackoverflow.com/users/315938",
"pm_score": 3,
"selected": false,
"text": "select * from table limit 5 offset (select count(*) from table) - 5;\n"
},
{
"answer_id": 18567579,
"author": "M Palani Mca",
"author_id": 1599079,
"author_profile": "https://Stackoverflow.com/users/1599079",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC\n select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc\n"
},
{
"answer_id": 18820227,
"author": "Ardalan Shahgholi",
"author_id": 2063547,
"author_profile": "https://Stackoverflow.com/users/2063547",
"pm_score": 2,
"selected": false,
"text": "Declare @Count1 int ;\n\nSelect @Count1 = Count(*)\nFROM [Log] AS L\n\nSELECT \n *\nFROM [Log] AS L\nORDER BY L.id\nOFFSET @Count - 5 ROWS\nFETCH NEXT 5 ROWS ONLY;\n"
},
{
"answer_id": 22266603,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "select * from tweets where placeID = '$placeID' and id > (\n (select count(*) from tweets where placeID = '$placeID')-2)\n"
},
{
"answer_id": 28755973,
"author": "Nadia Deqmin",
"author_id": 1878287,
"author_profile": "https://Stackoverflow.com/users/1878287",
"pm_score": 2,
"selected": false,
"text": "SELECT *\nFROM Table Name\nWHERE ID <= IDENT_CURRENT('Table Name')\nAND ID >= IDENT_CURRENT('Table Name') - 5\n"
},
{
"answer_id": 33213441,
"author": "Slava",
"author_id": 1089441,
"author_profile": "https://Stackoverflow.com/users/1089441",
"pm_score": 0,
"selected": false,
"text": "DECLARE @MYVAR NVARCHAR(100)\nDECLARE @step int\nSET @step = 0;\n\n\nDECLARE MYTESTCURSOR CURSOR\nDYNAMIC \nFOR\nSELECT col FROM [dbo].[table]\nOPEN MYTESTCURSOR\nFETCH LAST FROM MYTESTCURSOR INTO @MYVAR\nprint @MYVAR;\n\n\nWHILE @step < 10\nBEGIN \n FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR\n print @MYVAR;\n SET @step = @step + 1;\nEND \nCLOSE MYTESTCURSOR\nDEALLOCATE MYTESTCURSOR\n"
},
{
"answer_id": 36426724,
"author": "Apps Tawale",
"author_id": 5752950,
"author_profile": "https://Stackoverflow.com/users/5752950",
"pm_score": 2,
"selected": false,
"text": "select [Stu_Id],[Student_Name] ,[City] ,[Registered], \n RowNum = row_number() OVER (ORDER BY (SELECT 0)) \nfrom student\nORDER BY RowNum desc \n"
},
{
"answer_id": 50853704,
"author": "Irf",
"author_id": 1042705,
"author_profile": "https://Stackoverflow.com/users/1042705",
"pm_score": 0,
"selected": false,
"text": "select top 5 *, \n RowNum = row_number() OVER (ORDER BY (SELECT 0)) \nfrom [dbo].[ViewEmployeeMaster]\nORDER BY RowNum desc\n select *, RowNum2 = row_number() OVER (ORDER BY (SELECT 0)) \nfrom ( \n select top 5 *, RowNum = row_number() OVER (ORDER BY (SELECT 0)) \n from [dbo].[ViewEmployeeMaster]\n ORDER BY RowNum desc\n ) as t1\norder by RowNum2 desc\n"
},
{
"answer_id": 55428722,
"author": "Rahul Mahadik",
"author_id": 8847277,
"author_profile": "https://Stackoverflow.com/users/8847277",
"pm_score": 1,
"selected": false,
"text": "SELECT *\nFROM\n(\n SELECT TOP 5 *\n FROM [MyTable]\n ORDER BY Id DESC /*Primary Key*/\n) AS T\nORDER BY T.Id ASC; /*Primary Key*/\n"
},
{
"answer_id": 61654568,
"author": "Hervera",
"author_id": 8444078,
"author_profile": "https://Stackoverflow.com/users/8444078",
"pm_score": -1,
"selected": false,
"text": "select * from table limit 5 offset (select count(*) from table) - 5;\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,062 | <p>Which is the best method to make the browser use cached versions of js files (from the serverside)?</p>
| [
{
"answer_id": 311073,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 3,
"selected": false,
"text": "function OutputJs($Content) \n{ \n ob_start();\n echo $Content;\n $expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere\n header(\"Content-type: x-javascript\");\n header('Content-Length: ' . ob_get_length());\n header('Cache-Control: max-age='.$expires.', must-revalidate');\n header('Pragma: public');\n header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');\n ob_end_flush();\n return; \n} \n"
},
{
"answer_id": 311082,
"author": "William Macdonald",
"author_id": 2725,
"author_profile": "https://Stackoverflow.com/users/2725",
"pm_score": 5,
"selected": false,
"text": "AddOutputFilter DEFLATE css js\nExpiresActive On\nExpiresByType application/x-javascript A2592000\n"
},
{
"answer_id": 311089,
"author": "Kalid",
"author_id": 109,
"author_profile": "https://Stackoverflow.com/users/109",
"pm_score": 3,
"selected": false,
"text": "#Create filter to match files you want to cache \n<Files *.js>\nHeader add \"Cache-Control\" \"max-age=604800\"\n</Files>\n"
},
{
"answer_id": 321432,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 0,
"selected": false,
"text": "location /images {\n ...\n expires 4h;\n}\n"
},
{
"answer_id": 28927630,
"author": "select",
"author_id": 1436151,
"author_profile": "https://Stackoverflow.com/users/1436151",
"pm_score": 3,
"selected": false,
"text": "function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn(\"error loading \"+e))};a.open(\"GET\",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement(\"script\");b.readyState?b.onreadystatechange=function(){if(\"loaded\"==b.readyState||\"complete\"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute(\"src\",c);document.getElementsByTagName(\"head\")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement(\"script\");b.type=\"text/javascript\";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName(\"head\")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};\n requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){\n requireScript('examplejs', '0.0.3', 'example.js');\n});\n"
},
{
"answer_id": 39551751,
"author": "joel Moses",
"author_id": 3749691,
"author_profile": "https://Stackoverflow.com/users/3749691",
"pm_score": 0,
"selected": false,
"text": " (function(url, storageName) {\n var fromStorage = localStorage.getItem(storageName);\n var fullUrl = url + \"?rand=\" + (Math.floor(Math.random() * 100000000));\n getUrl(function(fromUrl) {\n// first load\n if (!fromStorage) {\n localStorage.setItem(storageName, fromUrl);\n return;\n }\n// old file\n if (fromStorage === fromUrl) {\n return;\n }\n // files updated\n localStorage.setItem(storageName, fromUrl);\n location.reload(true);\n });\n function getUrl(fn) {\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", fullUrl, true);\n xmlhttp.send();\n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState === XMLHttpRequest.DONE) {\n if (xmlhttp.status === 200 || xmlhttp.status === 2) {\n fn(xmlhttp.responseText);\n }\n else if (xmlhttp.status === 400) {\n throw 'unable to load file for cache check ' + url;\n }\n else {\n throw 'unable to load file for cache check ' + url;\n }\n }\n };\n }\n ;\n })(\"version.txt\", \"version\");"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7883/"
] |
311,068 | <p>This is pretty trivial, but I noticed on SO that instead of an offset they are using page numbers. I know the difference is minor (multiply the page number by rows on a page or divide offset by rows on a page), but I'm wondering if one is recommended over the other.</p>
<p>Some sites, like Google, of course use a more complicated system because they need to track your actual search. But I'm thinking for a simple site where this doesn't matter.</p>
<p>What is the recommended technique?</p>
| [
{
"answer_id": 597684,
"author": "thomasrutter",
"author_id": 53212,
"author_profile": "https://Stackoverflow.com/users/53212",
"pm_score": 3,
"selected": false,
"text": "WHERE my_sortorder >= (some offset)\nLIMIT 10\n LIMIT 10 OFFSET 880\n"
},
{
"answer_id": 45788241,
"author": "kbuilds",
"author_id": 1928804,
"author_profile": "https://Stackoverflow.com/users/1928804",
"pm_score": 3,
"selected": false,
"text": "limit offset"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
311,070 | <p>How to filter my datagridview by the value of my label.text on click event? That value is from my linq query:</p>
<pre><code>dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
c.Field<int>("ageColumn") < 5).Count();
</code></pre>
<p>Let's just say the above query gives me 12 (label.text = 12), now when I click "12", I want my datagridview to ONLY show those 12 rows that meet my above query.</p>
| [
{
"answer_id": 311139,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>(\"ageColumn\") > 3 &&\n c.Field<int>(\"ageColumn\") < 5)\n"
},
{
"answer_id": 311150,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": true,
"text": "Predicate<DataColumn> clause = c => c.Field<int>(\"ageColumn\") > 3 \n && c.Field<int>(\"ageColumn\") < 5;\nlabel1.Tag = clause;\n var clause = (sender as Label).Tag as Predicate<DataColumn>; \nmyDataSource = dataSet.Tables[0].AsEnumerable().Where(clause);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385/"
] |
311,074 | <p>In my application I have a <code>Customer</code> class and an <code>Address</code> class. The <code>Customer</code> class has three instances of the <code>Address</code> class: <code>customerAddress</code>, <code>deliveryAddress</code>, <code>invoiceAddress</code>.</p>
<p><strong>Whats the best way to reflect this structure in a database?</strong></p>
<ul>
<li>The straightforward way would be a customer table and a separate address table. </li>
<li>A more denormalized way would be just a customer table with columns for every address (Example for "street": customer_street, delivery_street, invoice_street) </li>
</ul>
<p>What are your experiences with that? Are there any advantages and disadvantages of these approaches?</p>
| [
{
"answer_id": 311091,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 5,
"selected": true,
"text": "CREATE TABLE Customer\n(\n ID int not null IDENTITY(1,1) PRIMARY KEY,\n Name varchar(60) not null,\n customerAddress int not null\n CONSTRAINT FK_Address1_AddressID FOREIGN KEY References Address(ID),\n deliveryAddress int null\n CONSTRAINT FK_Address2_AddressID FOREIGN KEY References Address(ID),\n invoiceAddress int null\n CONSTRAINT FK_Address3_AddressID FOREIGN KEY References Address(ID),\n -- etc\n)\n\nCREATE TABLE Address\n(\n ID int not null IDENTITY(1,1) PRIMARY KEY,\n Street varchar(120) not null\n -- etc\n)\n CREATE TABLE Customer\n(\n ID int not null IDENTITY(1,1) PRIMARY KEY,\n Name varchar(60) not null\n -- etc\n)\n\nCREATE TABLE Address\n(\n ID int not null IDENTITY(1,1) PRIMARY KEY,\n CustomerID int not null\n CONSTRAINT FK_Customer_CustomerID FOREIGN KEY References Customer(ID),\n Street varchar(120) not null,\n AddressType int not null \n -- etc\n)\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
311,092 | <p>I am working on an app with an NSTextView. When I paste random bytes into it (say, from a compiled C program) it displays gibberish, as it should. However, when I -setShowsControlCharacters:YES, the same causes a crash and gives the following error multiple times:</p>
<p><code>2008-11-22 00:27:22.671 MyAppName[6119:10b] *** -[NSBigMutableString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:]: Range or index out of bounds</code></p>
<p>I created a new project with just an NSTextView with the same property and it does not have this problem.</p>
<p>My question is, how can I debug my app to find the cause of the error? I have no idea where the bug originates. I am not familiar with the debugger built in to Xcode. If anyone could point me in the right direction in terms of how to track down such a bug I would be very grateful. Thanks.</p>
| [
{
"answer_id": 312204,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 4,
"selected": true,
"text": "objc_exception_throw -[NSException raise] objc_exception_throw"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18091/"
] |
311,094 | <p>Some background: In Germany (at least) invoice numbers have to follow certain rules:</p>
<ol>
<li>The have to be ordered</li>
<li>They have to be continuous (may not have gaps)</li>
</ol>
<p>Since a few months they are allowed to contain characters. Some customers want to use that possibility and customers don't know that or are afraid and they insist on digit-only invoice numbers.</p>
<p>Additionally the customers don't want to start them at zero.</p>
<p>Is I can think of many ways to generate such a number I wonder: What's the best way to do this?</p>
| [
{
"answer_id": 311107,
"author": "Frode Lillerud",
"author_id": 33431,
"author_profile": "https://Stackoverflow.com/users/33431",
"pm_score": 4,
"selected": true,
"text": "static object _invoiceNumberLock = new object();\npublic static string GetInvoiceNumber()\n{\n lock(_invoiceNumberLock)\n {\n //Connect to database and get MAX(invoicenumber)+1\n //Increase the invoicenumber in SQL database by one\n //Perhaps also add characters\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
311,102 | <p>For a system I need to convert a pointer to a long then the long back to the pointer type. As you can guess this is very unsafe. What I wanted to do is use dynamic_cast to do the conversion so if I mixed them I'll get a null pointer. This page says <a href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm</a></p>
<blockquote>
<p>The dynamic_cast operator performs
type conversions at run time. The
dynamic_cast operator guarantees the
conversion of a pointer to a base
class to a pointer to a derived class,
or the conversion of an lvalue
referring to a base class to a
reference to a derived class. A
program can thereby use a class
hierarchy safely. This operator and
the typeid operator provide run-time
type information (RTTI) support in
C++.</p>
</blockquote>
<p>and I'd like to get an error if it's null so I wrote my own dynamic cast</p>
<pre><code>template<class T, class T2> T mydynamic_cast(T2 p)
{
assert(dynamic_cast<T>(p));
return reinterpret_cast<T>(p);
}
</code></pre>
<p>With MSVC I get the error "error C2681: 'long' : invalid expression type for dynamic_cast". It turns out this will only work with classes which have virtual functions... WTF! I know the point of a dynamic cast was for the up/down casting inheritance problem but I also thought it was to solve the type cast problem dynamically. I know I could use reinterpret_cast but that doesn't guarantee the same type of safety.</p>
<p>What should I use to check if my typecast are the same type? I could compare the two typeid but I would have a problem when I want to typecast a derived to its base. So how can I solve this?</p>
| [
{
"answer_id": 311106,
"author": "amit kumar",
"author_id": 19501,
"author_profile": "https://Stackoverflow.com/users/19501",
"pm_score": 2,
"selected": false,
"text": "dynamic_cast reinterpret_cast assert(ptr != 0) reinterpret_cast union U { \nint* i_ptr_;\nlong l;\n}\n"
},
{
"answer_id": 311108,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 0,
"selected": false,
"text": "dynamic_cast<> pointer long safe_reinterpret_cast<> struct a_kind {}; \nstruct b_kind {}; \n\nvoid function(long ptr) \n{} \n\nint \nmain(int argc, char *argv[]) \n{ \n a_kind * ptr1 = new a_kind; \n b_kind * ptr2 = new b_kind;\n\n function( (long)ptr1 );\n function( (long)ptr2 );\n\n return 0;\n}\n function()"
},
{
"answer_id": 311189,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 0,
"selected": false,
"text": "reinterpret_cast ::intptr_t BOOST_STATIC_ASSERT(sizeof(T1) >= sizeof(T2));\n T* intptr_t U* T* intptr_t T*"
},
{
"answer_id": 311334,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "long uintptr_t dynamic_cast reinterpret_cast"
},
{
"answer_id": 311558,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": -1,
"selected": false,
"text": "class Base\n{\n};\n\nclass Foo : public Base\n{\n};\n\nclass Bar : public Base\n{\n};\n Base* obj = new Bar;\n\nBar* bar = dynamic_cast<Bar*>(obj); // this returns a pointer to the derived type because obj actually is a 'Bar' object\nassert( bar != 0 );\n\nFoo* foo = dynamic_cast<Foo*>(obj); // this returns NULL because obj isn't a Foo\nassert( foo == 0 );\n"
},
{
"answer_id": 311762,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 0,
"selected": false,
"text": "struct PtrWrapper {\n void* m_theRealPointer;\n std::string m_type;\n};\n\nvoid YourDangerousMethod( long argument ) {\n\n if ( !argument ) \n return;\n\n PtrWrapper& pw = *(PtrWrapper*)argument;\n\n assert( !pw.m_type.empty() );\n\n if ( pw.m_type == \"ClassA\" ) {\n ClassA* a = (ClassA*)pw.m_theRealPointer;\n a->DoSomething();\n } else if (...) { ... }\n\n}\n"
},
{
"answer_id": 324739,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": true,
"text": "#include <stdexcept>\n#include <typeinfo>\n#include <string>\n#include <iostream>\nusing namespace std;\n\n\n// Any class that needs to be passed out as a handle must inherit from this class.\n// Use virtual inheritance if needed in multiple inheritance situations.\nclass Base\n{\n\npublic:\n virtual ~Base() {} // Ensure a v-table exists for RTTI/dynamic_cast to work\n};\n\n\nclass ClassA : public Base\n{\n\n};\n\nclass ClassB : public Base\n{\n\n};\n\nclass ClassC\n{\npublic:\n virtual ~ClassC() {}\n};\n\n// Convert a pointer to a long handle. Always use this function\n// to pass handles to outside code. It ensures that T does derive\n// from Base, and that things work properly in a multiple inheritance\n// situation.\ntemplate <typename T>\nlong pointer_to_handle_cast(T ptr)\n{\n return reinterpret_cast<long>(static_cast<Base*>(ptr));\n}\n\n// Convert a long handle back to a pointer. This makes sure at\n// compile time that T does derive from Base. Throws an exception\n// if handle is NULL, or a pointer to a non-rtti object, or a pointer\n// to a class not convertable to T.\ntemplate <typename T>\nT safe_handle_cast(long handle)\n{\n if (handle == NULL)\n throw invalid_argument(string(\"Error casting null pointer to \") + (typeid(T).name()));\n\n Base *base = static_cast<T>(NULL); // Check at compile time that T converts to a Base *\n base = reinterpret_cast<Base *>(handle);\n T result = NULL;\n\n try\n {\n result = dynamic_cast<T>(base);\n }\n catch(__non_rtti_object &)\n {\n throw invalid_argument(string(\"Error casting non-rtti object to \") + (typeid(T).name()));\n }\n\n if (!result)\n throw invalid_argument(string(\"Error casting pointer to \") + typeid(*base).name() + \" to \" + (typeid(T).name()));\n\n return result;\n}\n\nint main()\n{\n ClassA *a = new ClassA();\n ClassB *b = new ClassB();\n ClassC *c = new ClassC();\n long d = 0; \n\n\n long ahandle = pointer_to_handle_cast(a);\n long bhandle = pointer_to_handle_cast(b);\n // long chandle = pointer_to_handle_cast(c); //Won't compile\n long chandle = reinterpret_cast<long>(c);\n // long dhandle = pointer_to_handle_cast(&d); Won't compile\n long dhandle = reinterpret_cast<long>(&d);\n\n // send handle to library\n //...\n // get handle back\n try\n {\n a = safe_handle_cast<ClassA *>(ahandle);\n //a = safe_handle_cast<ClassA *>(bhandle); // fails at runtime\n //a = safe_handle_cast<ClassA *>(chandle); // fails at runtime\n //a = safe_handle_cast<ClassA *>(dhandle); // fails at runtime\n //a = safe_handle_cast<ClassA *>(NULL); // fails at runtime\n //c = safe_handle_cast<ClassC *>(chandle); // Won't compile\n }\n catch (invalid_argument &ex)\n {\n cout << ex.what() << endl;\n }\n\n return 0;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,103 | <p>I need a map that has two keys, e.g.</p>
<pre><code>Map2<String /*ssn*/, String /*empId*/, Employee> _employees;
</code></pre>
<p>So that I can</p>
<pre><code>_employees.put(e.ssn(), e.empId(), e)
</code></pre>
<p>And later</p>
<pre><code>_employees.get1(someSsn);
_employees.get2(someImpId);
</code></pre>
<p>Or even</p>
<pre><code>_employees.remove1(someImpId);
</code></pre>
<p>I am not sure why I want to stop at two, why not more, probably because that's the case I am I need right now :-) But the type needs to handle fixed number of keys to be type-safe -- type parameters cannot be vararg :-)</p>
<p>Appreciate any pointers, or advice on why this is a bad idea.</p>
| [
{
"answer_id": 311110,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 2,
"selected": false,
"text": "Map< String, Map< String,Employee> > _employees;\n"
},
{
"answer_id": 311248,
"author": "Zach Scrivena",
"author_id": 20029,
"author_profile": "https://Stackoverflow.com/users/20029",
"pm_score": 2,
"selected": false,
"text": "empId Map empId Employee ssn Map empId ssn empId Map empId Employee Map"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18573/"
] |
311,117 | <p>I need a type which can contain a position of an object in a 3D environment - my house.</p>
<p>I need to know the floor it is on, and the x and Y coordinates on that floor.</p>
<p>The System.Windows.Point(int, int) only represent a two-dimensional space, but does .NET have a type for three-dimensional space?</p>
<p>I realize that I could do something like</p>
<pre><code>List<int, Point<int, int>>
</code></pre>
<p>but I would like to have just a simple type instead. Something like:</p>
<pre><code>3DPoint<int, int, int>
</code></pre>
<p>Does the .NET Framework have this?</p>
| [
{
"answer_id": 311129,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": true,
"text": "public struct Vector3\n{\n public float x;\n public float y;\n public float z;\n} \n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33431/"
] |
311,131 | <p>I've written a WPF UserControl, and want to add one or more of it to my Window at runtime when I click a button. How can I do that?</p>
<p>Edit: Further specification
I want to add the usercontrols to a Canvas, and put in a absolute position. The canvas is a drawing of the floors in my house, and each usercontrol has properties to indicate where in the house it is positioned. So I want all the controls to be positioned in the correct position on the canvas.</p>
<p>I'm thinking something like this</p>
<pre><code>var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place
</code></pre>
| [
{
"answer_id": 311136,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 2,
"selected": false,
"text": " _stackPanel.Children.Add(new YourControl()); \n"
},
{
"answer_id": 311815,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 6,
"selected": true,
"text": "var light = new LightUserControl(2);\nHouseCanvas.Children.Add(light);\nCanvas.SetLeft(light, 20);\nCanvas.SetTop(light, 20);\n"
},
{
"answer_id": 330360,
"author": "Ramiro Berrelleza",
"author_id": 548,
"author_profile": "https://Stackoverflow.com/users/548",
"pm_score": 4,
"selected": false,
"text": "Label newLabel = new Label();\nnewLabel.Content = \"The New Element\";\nMain.Children.Add(newLabel);\nGrid.SetColumn(newLabel, 0);\nGrid.SetRow(newLabel, 0);\n"
},
{
"answer_id": 9654392,
"author": "Dhruv Singhal",
"author_id": 1143633,
"author_profile": "https://Stackoverflow.com/users/1143633",
"pm_score": 2,
"selected": false,
"text": "for (i = 1; i <= buttoncount; i++)\n{\n Button mybutton = new Button();\n Grid1.Children.Add(mybutton);\n mybutton.Height = 100;\n mybutton.Width = 100;\n mybutton.Name = \"button\" + i;\n mybutton.Content = mybutton.Name;\n}\n"
},
{
"answer_id": 25705047,
"author": "dexiang",
"author_id": 3327485,
"author_profile": "https://Stackoverflow.com/users/3327485",
"pm_score": 0,
"selected": false,
"text": " public static void AddChild(this Visual parent, UIElement child)\n {\n if (InternalAddChild(parent, child))\n {\n return;\n }\n throw new NotSupportedException();\n }\n private static bool InternalAddChild(Visual parent, UIElement child)\n {\n Panel panel = parent as Panel;\n if (panel != null)\n {\n panel.Children.Add(child);\n return true;\n }\n for (int i = VisualTreeHelper.GetChildrenCount(parent) - 1; i != -1; i--)\n {\n Visual target = VisualTreeHelper.GetChild(parent, i) as Visual;\n if (target != null && InternalAddChild(target, child))\n {\n return true;\n }\n }\n return false;\n }\n"
},
{
"answer_id": 29855829,
"author": "Cassius",
"author_id": 1751784,
"author_profile": "https://Stackoverflow.com/users/1751784",
"pm_score": 0,
"selected": false,
"text": "for (i = 1; i <= buttoncount; i++)\n{\n Button mybutton = new Button();\n Grid1.Children.Add(mybutton);\n mybutton.Height = 100;\n mybutton.Width = 100;\n mybutton.Name = \"button\" + i;\n mybutton.Content = mybutton.Name;\n mybutton.Click += button_Click;\n}\n\nprivate void button_Click(object sender, RoutedEventArgs e)\n{\n // do something\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33431/"
] |
311,154 | <p>I have a .fla file with some text that I want to get at. Is there a free app than you can use to open .fla files, or just a tool to dump strings and pics?</p>
| [
{
"answer_id": 311170,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "strings -n 10 \"D:\\Archives\\scrolling flash gallery with preloader.fla\" > str\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2942/"
] |
311,165 | <p>How can you convert a byte array to a hexadecimal string and vice versa?</p>
| [
{
"answer_id": 311179,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 12,
"selected": true,
"text": "Convert.ToHexString Convert.FromHexString public static string ByteArrayToString(byte[] ba)\n{\n StringBuilder hex = new StringBuilder(ba.Length * 2);\n foreach (byte b in ba)\n hex.AppendFormat(\"{0:x2}\", b);\n return hex.ToString();\n}\n public static string ByteArrayToString(byte[] ba)\n{\n return BitConverter.ToString(ba).Replace(\"-\",\"\");\n}\n public static byte[] StringToByteArray(String hex)\n{\n int NumberChars = hex.Length;\n byte[] bytes = new byte[NumberChars / 2];\n for (int i = 0; i < NumberChars; i += 2)\n bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);\n return bytes;\n}\n Substring Convert.ToByte Convert.ToByte SubString"
},
{
"answer_id": 311338,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "public static class ByteExtensions\n{\n public static string ToHexString(this byte[] ba)\n {\n StringBuilder hex = new StringBuilder(ba.Length * 2);\n\n foreach (byte b in ba)\n {\n hex.AppendFormat(\"{0:x2}\", b);\n }\n return hex.ToString();\n }\n}\n"
},
{
"answer_id": 311379,
"author": "Baget",
"author_id": 34369,
"author_profile": "https://Stackoverflow.com/users/34369",
"pm_score": 6,
"selected": false,
"text": "byte[] bytes = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256}\nConsole.WriteLine( BitConverter.ToString(bytes));\n"
},
{
"answer_id": 311382,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 7,
"selected": false,
"text": "BitConverter String.Join(String.Empty, Array.ConvertAll(bytes, x => x.ToString(\"X2\")));\n String.Concat(Array.ConvertAll(bytes, x => x.ToString(\"X2\")));\n"
},
{
"answer_id": 624379,
"author": "patridge",
"author_id": 48700,
"author_profile": "https://Stackoverflow.com/users/48700",
"pm_score": 9,
"selected": false,
"text": "Stopwatch StringBuilder unsafe BitConverter {SoapHexBinary}.ToString {byte}.ToString(\"X2\") foreach {byte}.ToString(\"X2\") {IEnumerable}.Aggregate Array.ConvertAll string.Join Array.ConvertAll string.Concat {StringBuilder}.AppendFormat foreach {StringBuilder}.AppendFormat {IEnumerable}.Aggregate Func<byte[], string> TestCandidates GenerateTestInput static string ByteArrayToHexStringViaStringJoinArrayConvertAll(byte[] bytes) {\n return string.Join(string.Empty, Array.ConvertAll(bytes, b => b.ToString(\"X2\")));\n}\nstatic string ByteArrayToHexStringViaStringConcatArrayConvertAll(byte[] bytes) {\n return string.Concat(Array.ConvertAll(bytes, b => b.ToString(\"X2\")));\n}\nstatic string ByteArrayToHexStringViaBitConverter(byte[] bytes) {\n string hex = BitConverter.ToString(bytes);\n return hex.Replace(\"-\", \"\");\n}\nstatic string ByteArrayToHexStringViaStringBuilderAggregateByteToString(byte[] bytes) {\n return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.Append(b.ToString(\"X2\"))).ToString();\n}\nstatic string ByteArrayToHexStringViaStringBuilderForEachByteToString(byte[] bytes) {\n StringBuilder hex = new StringBuilder(bytes.Length * 2);\n foreach (byte b in bytes)\n hex.Append(b.ToString(\"X2\"));\n return hex.ToString();\n}\nstatic string ByteArrayToHexStringViaStringBuilderAggregateAppendFormat(byte[] bytes) {\n return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.AppendFormat(\"{0:X2}\", b)).ToString();\n}\nstatic string ByteArrayToHexStringViaStringBuilderForEachAppendFormat(byte[] bytes) {\n StringBuilder hex = new StringBuilder(bytes.Length * 2);\n foreach (byte b in bytes)\n hex.AppendFormat(\"{0:X2}\", b);\n return hex.ToString();\n}\nstatic string ByteArrayToHexViaByteManipulation(byte[] bytes) {\n char[] c = new char[bytes.Length * 2];\n byte b;\n for (int i = 0; i < bytes.Length; i++) {\n b = ((byte)(bytes[i] >> 4));\n c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);\n b = ((byte)(bytes[i] & 0xF));\n c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);\n }\n return new string(c);\n}\nstatic string ByteArrayToHexViaByteManipulation2(byte[] bytes) {\n char[] c = new char[bytes.Length * 2];\n int b;\n for (int i = 0; i < bytes.Length; i++) {\n b = bytes[i] >> 4;\n c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7));\n b = bytes[i] & 0xF;\n c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7));\n }\n return new string(c);\n}\nstatic string ByteArrayToHexViaSoapHexBinary(byte[] bytes) {\n SoapHexBinary soapHexBinary = new SoapHexBinary(bytes);\n return soapHexBinary.ToString();\n}\nstatic string ByteArrayToHexViaLookupAndShift(byte[] bytes) {\n StringBuilder result = new StringBuilder(bytes.Length * 2);\n string hexAlphabet = \"0123456789ABCDEF\";\n foreach (byte b in bytes) {\n result.Append(hexAlphabet[(int)(b >> 4)]);\n result.Append(hexAlphabet[(int)(b & 0xF)]);\n }\n return result.ToString();\n}\nstatic readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_Lookup32, GCHandleType.Pinned).AddrOfPinnedObject();\nstatic string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes) {\n var lookupP = _lookup32UnsafeP;\n var result = new string((char)0, bytes.Length * 2);\n fixed (byte* bytesP = bytes)\n fixed (char* resultP = result) {\n uint* resultP2 = (uint*)resultP;\n for (int i = 0; i < bytes.Length; i++) {\n resultP2[i] = lookupP[bytesP[i]];\n }\n }\n return result;\n}\nstatic uint[] _Lookup32 = Enumerable.Range(0, 255).Select(i => {\n string s = i.ToString(\"X2\");\n return ((uint)s[0]) + ((uint)s[1] << 16);\n}).ToArray();\nstatic string ByteArrayToHexViaLookupPerByte(byte[] bytes) {\n var result = new char[bytes.Length * 2];\n for (int i = 0; i < bytes.Length; i++)\n {\n var val = _Lookup32[bytes[i]];\n result[2*i] = (char)val;\n result[2*i + 1] = (char) (val >> 16);\n }\n return new string(result);\n}\nstatic string ByteArrayToHexViaLookup(byte[] bytes) {\n string[] hexStringTable = new string[] {\n \"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"0A\", \"0B\", \"0C\", \"0D\", \"0E\", \"0F\",\n \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"1A\", \"1B\", \"1C\", \"1D\", \"1E\", \"1F\",\n \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"2A\", \"2B\", \"2C\", \"2D\", \"2E\", \"2F\",\n \"30\", \"31\", \"32\", \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", \"3A\", \"3B\", \"3C\", \"3D\", \"3E\", \"3F\",\n \"40\", \"41\", \"42\", \"43\", \"44\", \"45\", \"46\", \"47\", \"48\", \"49\", \"4A\", \"4B\", \"4C\", \"4D\", \"4E\", \"4F\",\n \"50\", \"51\", \"52\", \"53\", \"54\", \"55\", \"56\", \"57\", \"58\", \"59\", \"5A\", \"5B\", \"5C\", \"5D\", \"5E\", \"5F\",\n \"60\", \"61\", \"62\", \"63\", \"64\", \"65\", \"66\", \"67\", \"68\", \"69\", \"6A\", \"6B\", \"6C\", \"6D\", \"6E\", \"6F\",\n \"70\", \"71\", \"72\", \"73\", \"74\", \"75\", \"76\", \"77\", \"78\", \"79\", \"7A\", \"7B\", \"7C\", \"7D\", \"7E\", \"7F\",\n \"80\", \"81\", \"82\", \"83\", \"84\", \"85\", \"86\", \"87\", \"88\", \"89\", \"8A\", \"8B\", \"8C\", \"8D\", \"8E\", \"8F\",\n \"90\", \"91\", \"92\", \"93\", \"94\", \"95\", \"96\", \"97\", \"98\", \"99\", \"9A\", \"9B\", \"9C\", \"9D\", \"9E\", \"9F\",\n \"A0\", \"A1\", \"A2\", \"A3\", \"A4\", \"A5\", \"A6\", \"A7\", \"A8\", \"A9\", \"AA\", \"AB\", \"AC\", \"AD\", \"AE\", \"AF\",\n \"B0\", \"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\", \"B8\", \"B9\", \"BA\", \"BB\", \"BC\", \"BD\", \"BE\", \"BF\",\n \"C0\", \"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"C9\", \"CA\", \"CB\", \"CC\", \"CD\", \"CE\", \"CF\",\n \"D0\", \"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\", \"D8\", \"D9\", \"DA\", \"DB\", \"DC\", \"DD\", \"DE\", \"DF\",\n \"E0\", \"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"E6\", \"E7\", \"E8\", \"E9\", \"EA\", \"EB\", \"EC\", \"ED\", \"EE\", \"EF\",\n \"F0\", \"F1\", \"F2\", \"F3\", \"F4\", \"F5\", \"F6\", \"F7\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FD\", \"FE\", \"FF\",\n };\n StringBuilder result = new StringBuilder(bytes.Length * 2);\n foreach (byte b in bytes) {\n result.Append(hexStringTable[b]);\n }\n return result.ToString();\n}\n string.Concat Array.ConvertAll string.Join StringBuilder.Append(b.ToString(\"X2\")) foreach {IEnumerable}.Aggregate BitConverter SoapHexBinary unsafe"
},
{
"answer_id": 632920,
"author": "Waleed Eissa",
"author_id": 676066,
"author_profile": "https://Stackoverflow.com/users/676066",
"pm_score": 6,
"selected": false,
"text": "private static string ByteArrayToHex(byte[] barray)\n{\n char[] c = new char[barray.Length * 2];\n byte b;\n for (int i = 0; i < barray.Length; ++i)\n {\n b = ((byte)(barray[i] >> 4));\n c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);\n b = ((byte)(barray[i] & 0xF));\n c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);\n }\n return new string(c);\n}\n"
},
{
"answer_id": 1423967,
"author": "Jack Straw",
"author_id": 147430,
"author_profile": "https://Stackoverflow.com/users/147430",
"pm_score": 2,
"selected": false,
"text": "public static String ByteArrayToSQLHexString(byte[] Source)\n{\n return = \"0x\" + BitConverter.ToString(Source).Replace(\"-\", \"\");\n}\n"
},
{
"answer_id": 1993103,
"author": "Olipro",
"author_id": 234946,
"author_profile": "https://Stackoverflow.com/users/234946",
"pm_score": 0,
"selected": false,
"text": "hex.Substring(i, 2) hex[i]+hex[i+1] i+=2 i++"
},
{
"answer_id": 2050653,
"author": "Chris F",
"author_id": 195931,
"author_profile": "https://Stackoverflow.com/users/195931",
"pm_score": 4,
"selected": false,
"text": "private byte[] HexStringToByteArray(string hexString)\n{\n int hexStringLength = hexString.Length;\n byte[] b = new byte[hexStringLength / 2];\n for (int i = 0; i < hexStringLength; i += 2)\n {\n int topChar = (hexString[i] > 0x40 ? hexString[i] - 0x37 : hexString[i] - 0x30) << 4;\n int bottomChar = hexString[i + 1] > 0x40 ? hexString[i + 1] - 0x37 : hexString[i + 1] - 0x30;\n b[i / 2] = Convert.ToByte(topChar + bottomChar);\n }\n return b;\n}\n"
},
{
"answer_id": 2556329,
"author": "Mykroft",
"author_id": 2191,
"author_profile": "https://Stackoverflow.com/users/2191",
"pm_score": 8,
"selected": false,
"text": "using System.Runtime.Remoting.Metadata.W3cXsd2001;\n\npublic static byte[] GetStringToBytes(string value)\n{\n SoapHexBinary shb = SoapHexBinary.Parse(value);\n return shb.Value;\n}\n\npublic static string GetBytesToString(byte[] value)\n{\n SoapHexBinary shb = new SoapHexBinary(value);\n return shb.ToString();\n}\n"
},
{
"answer_id": 2889978,
"author": "Fredrik Hu",
"author_id": 348018,
"author_profile": "https://Stackoverflow.com/users/348018",
"pm_score": 2,
"selected": false,
"text": "hex[i] + hex[i+1] int public static byte[] StringToByteArray2(string hex)\n{\n byte[] bytes = new byte[hex.Length/2];\n int bl = bytes.Length;\n for (int i = 0; i < bl; ++i)\n {\n bytes[i] = (byte)((hex[2 * i] > 'F' ? hex[2 * i] - 0x57 : hex[2 * i] > '9' ? hex[2 * i] - 0x37 : hex[2 * i] - 0x30) << 4);\n bytes[i] |= (byte)(hex[2 * i + 1] > 'F' ? hex[2 * i + 1] - 0x57 : hex[2 * i + 1] > '9' ? hex[2 * i + 1] - 0x37 : hex[2 * i + 1] - 0x30);\n }\n return bytes;\n}\n"
},
{
"answer_id": 2948187,
"author": "Alexey Borzenkov",
"author_id": 355189,
"author_profile": "https://Stackoverflow.com/users/355189",
"pm_score": 2,
"selected": false,
"text": " public static string ToHexString(byte[] data) {\n byte b;\n int i, j, k;\n int l = data.Length;\n char[] r = new char[l * 2];\n for (i = 0, j = 0; i < l; ++i) {\n b = data[i];\n k = b >> 4;\n r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);\n k = b & 15;\n r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);\n }\n return new string(r);\n }\n"
},
{
"answer_id": 3824807,
"author": "Mark",
"author_id": 64084,
"author_profile": "https://Stackoverflow.com/users/64084",
"pm_score": 3,
"selected": false,
"text": "public static string ByteArrayToString(byte[] ba) \n{\n // Concatenate the bytes into one long string\n return ba.Aggregate(new StringBuilder(32),\n (sb, b) => sb.Append(b.ToString(\"X2\"))\n ).ToString();\n}\n public static string ByteArrayToString(byte[] ba) \n{ \n StringBuilder hex = new StringBuilder(ba.Length * 2); \n\n for(int i=0; i < ba.Length; i++) // <-- Use for loop is faster than foreach \n hex.Append(ba[i].ToString(\"X2\")); // <-- ToString is faster than AppendFormat \n\n return hex.ToString(); \n} \n"
},
{
"answer_id": 3973996,
"author": "Craig Poulton",
"author_id": 481145,
"author_profile": "https://Stackoverflow.com/users/481145",
"pm_score": 4,
"selected": false,
"text": "string hex = BitConverter.ToString(YourByteArray).Replace(\"-\", \"\");\n Dim hex As String = BitConverter.ToString(YourByteArray).Replace(\"-\", \"\")\n"
},
{
"answer_id": 5609040,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 1,
"selected": false,
"text": " static readonly char[] _hexDigits = \"0123456789abcdef\".ToCharArray();\n public static string ToHexString(this byte[] bytes)\n {\n char[] digits = new char[bytes.Length * 2];\n for (int i = 0; i < bytes.Length; i++)\n {\n int d1, d2;\n d1 = Math.DivRem(bytes[i], 16, out d2);\n digits[2 * i] = _hexDigits[d1];\n digits[2 * i + 1] = _hexDigits[d2];\n }\n return new string(digits);\n }\n BitConverter.ToString BitConverter.ToString"
},
{
"answer_id": 6274772,
"author": "drphrozen",
"author_id": 326391,
"author_profile": "https://Stackoverflow.com/users/326391",
"pm_score": 4,
"selected": false,
"text": "private static readonly byte[] LookupTable = new byte[] {\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF\n};\n\nprivate static byte Lookup(char c)\n{\n var b = LookupTable[c];\n if (b == 255)\n throw new IOException(\"Expected a hex character, got \" + c);\n return b;\n}\n\npublic static byte ToByte(char[] chars, int offset)\n{\n return (byte)(Lookup(chars[offset]) << 4 | Lookup(chars[offset + 1]));\n}\n private static readonly char[][] LookupTableUpper;\nprivate static readonly char[][] LookupTableLower;\n\nstatic Hex()\n{\n LookupTableLower = new char[256][];\n LookupTableUpper = new char[256][];\n for (var i = 0; i < 256; i++)\n {\n LookupTableLower[i] = i.ToString(\"x2\").ToCharArray();\n LookupTableUpper[i] = i.ToString(\"X2\").ToCharArray();\n }\n}\n\npublic static char[] ToCharLower(byte[] b, int bOffset)\n{\n return LookupTableLower[b[bOffset]];\n}\n\npublic static char[] ToCharUpper(byte[] b, int bOffset)\n{\n return LookupTableUpper[b[bOffset]];\n}\n StringBuilderToStringFromBytes: 106148\nBitConverterToStringFromBytes: 15783\nArrayConvertAllToStringFromBytes: 54290\nByteManipulationToCharArray: 8444\nTableBasedToCharArray: 5651 *\n"
},
{
"answer_id": 6275329,
"author": "ClausAndersen",
"author_id": 788686,
"author_profile": "https://Stackoverflow.com/users/788686",
"pm_score": 2,
"selected": false,
"text": "if (b == 255)... offset++ offset offset offset + 1 private static readonly byte[] LookupTableLow = new byte[] {\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF\n};\n\nprivate static readonly byte[] LookupTableHigh = new byte[] {\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF\n};\n\nprivate static byte LookupLow(char c)\n{\n var b = LookupTableLow[c];\n if (b == 255)\n throw new IOException(\"Expected a hex character, got \" + c);\n return b;\n}\n\nprivate static byte LookupHigh(char c)\n{\n var b = LookupTableHigh[c];\n if (b == 255)\n throw new IOException(\"Expected a hex character, got \" + c);\n return b;\n}\n\npublic static byte ToByte(char[] chars, int offset)\n{\n return (byte)(LookupHigh(chars[offset++]) | LookupLow(chars[offset]));\n}\n"
},
{
"answer_id": 6378247,
"author": "Stas Makutin",
"author_id": 574743,
"author_profile": "https://Stackoverflow.com/users/574743",
"pm_score": 2,
"selected": false,
"text": "public static byte[] FromHexString(string src)\n{\n if (String.IsNullOrEmpty(src))\n return null;\n\n int index = src.Length;\n int sz = index / 2;\n if (sz <= 0)\n return null;\n\n byte[] rc = new byte[sz];\n\n while (--sz >= 0)\n {\n char lo = src[--index];\n char hi = src[--index];\n\n rc[sz] = (byte)(\n (\n (hi >= '0' && hi <= '9') ? hi - '0' :\n (hi >= 'a' && hi <= 'f') ? hi - 'a' + 10 :\n (hi >= 'A' && hi <= 'F') ? hi - 'A' + 10 :\n 0\n )\n << 4 | \n (\n (lo >= '0' && lo <= '9') ? lo - '0' :\n (lo >= 'a' && lo <= 'f') ? lo - 'a' + 10 :\n (lo >= 'A' && lo <= 'F') ? lo - 'A' + 10 :\n 0\n )\n );\n }\n\n return rc; \n}\n"
},
{
"answer_id": 7911281,
"author": "John Craig",
"author_id": 1015780,
"author_profile": "https://Stackoverflow.com/users/1015780",
"pm_score": -1,
"selected": false,
"text": "Public Function BufToHex(ByVal buf() As Byte) As String\n Dim sB As New System.Text.StringBuilder\n For i As Integer = 0 To buf.Length - 1\n sB.Append(buf(i).ToString(\"x2\"))\n Next i\n Return sB.ToString\nEnd Function\n"
},
{
"answer_id": 10706477,
"author": "Ben Mosher",
"author_id": 344143,
"author_profile": "https://Stackoverflow.com/users/344143",
"pm_score": 3,
"selected": false,
"text": "Give me that string:\n04c63f7842740c77e545bb0b2ade90b384f119f6ab57b680b7aa575a2f40939f\n\nTime to parse 100,000 times: 50.4192 ms\nResult as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=\nBitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5\n7-B6-80-B7-AA-57-5A-2F-40-93-9F\n\nAccepted answer: (StringToByteArray)\nTime to parse 100000 times: 233.1264ms\nResult as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=\nBitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5\n7-B6-80-B7-AA-57-5A-2F-40-93-9F\n\nWith Mono's implementation:\nTime to parse 100000 times: 777.2544ms\nResult as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=\nBitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5\n7-B6-80-B7-AA-57-5A-2F-40-93-9F\n\nWith SoapHexBinary:\nTime to parse 100000 times: 845.1456ms\nResult as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=\nBitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5\n7-B6-80-B7-AA-57-5A-2F-40-93-9F\n public static byte[] ToByteArrayFromHex(string hexString)\n{\n if (hexString.Length % 2 != 0) throw new ArgumentException(\"String must have an even length\");\n var array = new byte[hexString.Length / 2];\n for (int i = 0; i < hexString.Length; i += 2)\n {\n array[i/2] = ByteFromTwoChars(hexString[i], hexString[i + 1]);\n }\n return array;\n}\n\nprivate static byte ByteFromTwoChars(char p, char p_2)\n{\n byte ret;\n if (p <= '9' && p >= '0')\n {\n ret = (byte) ((p - '0') << 4);\n }\n else if (p <= 'f' && p >= 'a')\n {\n ret = (byte) ((p - 'a' + 10) << 4);\n }\n else if (p <= 'F' && p >= 'A')\n {\n ret = (byte) ((p - 'A' + 10) << 4);\n } else throw new ArgumentException(\"Char is not a hex digit: \" + p,\"p\");\n\n if (p_2 <= '9' && p_2 >= '0')\n {\n ret |= (byte) ((p_2 - '0'));\n }\n else if (p_2 <= 'f' && p_2 >= 'a')\n {\n ret |= (byte) ((p_2 - 'a' + 10));\n }\n else if (p_2 <= 'F' && p_2 >= 'A')\n {\n ret |= (byte) ((p_2 - 'A' + 10));\n } else throw new ArgumentException(\"Char is not a hex digit: \" + p_2, \"p_2\");\n\n return ret;\n}\n unsafe if"
},
{
"answer_id": 10758999,
"author": "Rick",
"author_id": 1417778,
"author_profile": "https://Stackoverflow.com/users/1417778",
"pm_score": 1,
"selected": false,
"text": "public static byte[] StrToByteArray(string str)\n {\n Dictionary<string, byte> hexindex = new Dictionary<string, byte>();\n for (byte i = 0; i < 255; i++)\n hexindex.Add(i.ToString(\"X2\"), i);\n\n List<byte> hexres = new List<byte>();\n for (int i = 0; i < str.Length; i += 2)\n hexres.Add(hexindex[str.Substring(i, 2)]);\n\n return hexres.ToArray();\n }\n"
},
{
"answer_id": 13905273,
"author": "Behrooz",
"author_id": 179795,
"author_profile": "https://Stackoverflow.com/users/179795",
"pm_score": 1,
"selected": false,
"text": " static char[] hexes = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n public static string ToHexadecimal (this byte[] Bytes)\n {\n char[] Result = new char[Bytes.Length << 1];\n int Offset = 0;\n for (int i = 0; i != Bytes.Length; i++) {\n Result[Offset++] = hexes[Bytes[i] >> 4];\n Result[Offset++] = hexes[Bytes[i] & 0x0F];\n }\n return new string(Result);\n }\n"
},
{
"answer_id": 14333437,
"author": "CodesInChaos",
"author_id": 445517,
"author_profile": "https://Stackoverflow.com/users/445517",
"pm_score": 7,
"selected": false,
"text": "static string ByteToHexBitFiddle(byte[] bytes)\n{\n char[] c = new char[bytes.Length * 2];\n int b;\n for (int i = 0; i < bytes.Length; i++) {\n b = bytes[i] >> 4;\n c[i * 2] = (char)(55 + b + (((b-10)>>31)&-7));\n b = bytes[i] & 0xF;\n c[i * 2 + 1] = (char)(55 + b + (((b-10)>>31)&-7));\n }\n return new string(c);\n}\n bytes[i] >> 4 bytes[i] & 0xF b - 10 < 0 b < 10 >= 0 b > 10 A F i >> 31 -1 i < 0 0 i >= 0 (b-10)>>31 0 -1 0 b A F 'A'-10 b 0 9 '0' - 55 & -7 (0 & -7) == 0 (-1 & -7) == -7 c i i < bytes.Length bytes[i] b"
},
{
"answer_id": 16565896,
"author": "JJJ",
"author_id": 5547,
"author_profile": "https://Stackoverflow.com/users/5547",
"pm_score": 2,
"selected": false,
"text": "public static string ByteArrayToString2(byte[] ba)\n{\n char[] c = new char[ba.Length * 2];\n for( int i = 0; i < ba.Length * 2; ++i)\n {\n byte b = (byte)((ba[i>>1] >> 4*((i&1)^1)) & 0xF);\n c[i] = (char)(55 + b + (((b-10)>>31)&-7));\n }\n return new string( c );\n}\n public static string ByteArrayToString(byte[] ba)\n{\n return string.Concat( ba.SelectMany( b => new int[] { b >> 4, b & 0xF }).Select( b => (char)(55 + b + (((b-10)>>31)&-7))) );\n}\n public static byte[] HexStringToByteArray( string s )\n{\n byte[] ab = new byte[s.Length>>1];\n for( int i = 0; i < s.Length; i++ )\n {\n int b = s[i];\n b = (b - '0') + ((('9' - b)>>31)&-7);\n ab[i>>1] |= (byte)(b << 4*((i&1)^1));\n }\n return ab;\n}\n"
},
{
"answer_id": 16907438,
"author": "JamieSee",
"author_id": 1015164,
"author_profile": "https://Stackoverflow.com/users/1015164",
"pm_score": 2,
"selected": false,
"text": "foreach for using System;\n\nnamespace ConversionExtensions\n{\n public static class ByteArrayExtensions\n {\n private readonly static char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n\n public static string ToHexString(this byte[] bytes)\n {\n char[] hex = new char[bytes.Length * 2];\n int index = 0;\n\n foreach (byte b in bytes)\n {\n hex[index++] = digits[b >> 4];\n hex[index++] = digits[b & 0x0F];\n }\n\n return new string(hex);\n }\n }\n}\n\n\nusing System;\nusing System.IO;\n\nnamespace ConversionExtensions\n{\n public static class StringExtensions\n {\n public static byte[] ToBytes(this string hexString)\n {\n if (!string.IsNullOrEmpty(hexString) && hexString.Length % 2 != 0)\n {\n throw new FormatException(\"Hexadecimal string must not be empty and must contain an even number of digits to be valid.\");\n }\n\n hexString = hexString.ToUpperInvariant();\n byte[] data = new byte[hexString.Length / 2];\n\n for (int index = 0; index < hexString.Length; index += 2)\n {\n int highDigitValue = hexString[index] <= '9' ? hexString[index] - '0' : hexString[index] - 'A' + 10;\n int lowDigitValue = hexString[index + 1] <= '9' ? hexString[index + 1] - '0' : hexString[index + 1] - 'A' + 10;\n\n if (highDigitValue < 0 || lowDigitValue < 0 || highDigitValue > 15 || lowDigitValue > 15)\n {\n throw new FormatException(\"An invalid digit was encountered. Valid hexadecimal digits are 0-9 and A-F.\");\n }\n else\n {\n byte value = (byte)((highDigitValue << 4) | (lowDigitValue & 0x0F));\n data[index / 2] = value;\n }\n }\n\n return data;\n }\n }\n}\n Cores: 4 <br/>\n Current Clock Speed: 1576 <br/>\n Max Clock Speed: 3092 <br/>\n"
},
{
"answer_id": 17923942,
"author": "CoperNick",
"author_id": 1457197,
"author_profile": "https://Stackoverflow.com/users/1457197",
"pm_score": 4,
"selected": false,
"text": "public static byte[] HexToByteUsingByteManipulation(string s)\n{\n byte[] bytes = new byte[s.Length / 2];\n for (int i = 0; i < bytes.Length; i++)\n {\n int hi = s[i*2] - 65;\n hi = hi + 10 + ((hi >> 31) & 7);\n\n int lo = s[i*2 + 1] - 65;\n lo = lo + 10 + ((lo >> 31) & 7) & 0x0f;\n\n bytes[i] = (byte) (lo | hi << 4);\n }\n return bytes;\n}\n & 0x0f hi = hi + 10 + ((hi >> 31) & 7); hi = ch-65 + 10 + (((ch-65) >> 31) & 7); hi = ch - 65 + 10 + 7; hi = ch - 48 0xffffffff & 7 hi = ch - 65 + 10; 0x00000000 & 7 0 & 0x0f 'A' '0' '9' 'A' ...456789:;<=>?@ABCD..."
},
{
"answer_id": 18396903,
"author": "JoseH",
"author_id": 1226086,
"author_profile": "https://Stackoverflow.com/users/1226086",
"pm_score": 2,
"selected": false,
"text": "static private readonly char[] hexAlphabet = new char[]\n {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\nstatic string ByteArrayToHexViaByteManipulation3(byte[] bytes)\n{\n char[] c = new char[bytes.Length * 2];\n byte b;\n for (int i = 0; i < bytes.Length; i++)\n {\n b = ((byte)(bytes[i] >> 4));\n c[i * 2] = hexAlphabet[b];\n b = ((byte)(bytes[i] & 0xF));\n c[i * 2 + 1] = hexAlphabet[b];\n }\n return new string(c);\n}\n static private readonly char[] hexAlphabet = new char[]\n {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n static string ByteArrayToHexViaByteManipulation4(byte[] bytes)\n {\n char[] c = new char[bytes.Length * 2];\n for (int i = 0, ptr = 0; i < bytes.Length; i++, ptr += 2)\n {\n byte b = bytes[i];\n c[ptr] = hexAlphabet[b >> 4];\n c[ptr + 1] = hexAlphabet[b & 0xF];\n }\n return new string(c);\n }\n"
},
{
"answer_id": 18543022,
"author": "MCattle",
"author_id": 1257753,
"author_profile": "https://Stackoverflow.com/users/1257753",
"pm_score": 2,
"selected": false,
"text": "<Extension()>\nPublic Function FromHexToByteArray(hex As String) As Byte()\n hex = If(hex, String.Empty)\n If hex.Length Mod 2 = 1 Then hex = \"0\" & hex\n Return Enumerable.Range(0, hex.Length \\ 2).Select(Function(i) Convert.ToByte(hex.Substring(i * 2, 2), 16)).ToArray\nEnd Function\n\n<Extension()>\nPublic Function ToHexString(bytes As IEnumerable(Of Byte)) As String\n Return String.Concat(bytes.Select(Function(b) b.ToString(\"X2\")))\nEnd Function\n"
},
{
"answer_id": 18939148,
"author": "spacepille",
"author_id": 1959167,
"author_profile": "https://Stackoverflow.com/users/1959167",
"pm_score": 2,
"selected": false,
"text": "private static readonly byte[] HexNibble = new byte[] {\n 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,\n 0x8, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF\n};\n\npublic static byte[] HexStringToByteArray( string str )\n{\n int byteCount = str.Length >> 1;\n byte[] result = new byte[byteCount + (str.Length & 1)];\n for( int i = 0; i < byteCount; i++ )\n result[i] = (byte) (HexNibble[str[i << 1] - 48] << 4 | HexNibble[str[(i << 1) + 1] - 48]);\n if( (str.Length & 1) != 0 )\n result[byteCount] = (byte) HexNibble[str[str.Length - 1] - 48];\n return result;\n}\n"
},
{
"answer_id": 19562623,
"author": "astrada",
"author_id": 2860133,
"author_profile": "https://Stackoverflow.com/users/2860133",
"pm_score": 1,
"selected": false,
"text": "XmlWriter.WriteBinHex public static string ToBinHex(byte[] bytes)\n {\n XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();\n xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;\n xmlWriterSettings.CheckCharacters = false;\n xmlWriterSettings.Encoding = ASCIIEncoding.ASCII;\n MemoryStream memoryStream = new MemoryStream();\n using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))\n {\n xmlWriter.WriteBinHex(bytes, 0, bytes.Length);\n }\n return Encoding.ASCII.GetString(memoryStream.ToArray());\n }\n"
},
{
"answer_id": 20695932,
"author": "Maratius",
"author_id": 3077541,
"author_profile": "https://Stackoverflow.com/users/3077541",
"pm_score": 3,
"selected": false,
"text": "public static class HexHelper\n{\n [System.Diagnostics.Contracts.Pure]\n public static string ToHex(this byte[] value)\n {\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n const string hexAlphabet = @\"0123456789ABCDEF\";\n\n var chars = new char[checked(value.Length * 2)];\n unchecked\n {\n for (int i = 0; i < value.Length; i++)\n {\n chars[i * 2] = hexAlphabet[value[i] >> 4];\n chars[i * 2 + 1] = hexAlphabet[value[i] & 0xF];\n }\n }\n return new string(chars);\n }\n\n [System.Diagnostics.Contracts.Pure]\n public static byte[] FromHex(this string value)\n {\n if (value == null)\n throw new ArgumentNullException(\"value\");\n if (value.Length % 2 != 0)\n throw new ArgumentException(\"Hexadecimal value length must be even.\", \"value\");\n\n unchecked\n {\n byte[] result = new byte[value.Length / 2];\n for (int i = 0; i < result.Length; i++)\n {\n // 0(48) - 9(57) -> 0 - 9\n // A(65) - F(70) -> 10 - 15\n int b = value[i * 2]; // High 4 bits.\n int val = ((b - '0') + ((('9' - b) >> 31) & -7)) << 4;\n b = value[i * 2 + 1]; // Low 4 bits.\n val += (b - '0') + ((('9' - b) >> 31) & -7);\n result[i] = checked((byte)val);\n }\n return result;\n }\n }\n}\n public static class HexUnsafeHelper\n{\n [System.Diagnostics.Contracts.Pure]\n public static unsafe string ToHex(this byte[] value)\n {\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n const string alphabet = @\"0123456789ABCDEF\";\n\n string result = new string(' ', checked(value.Length * 2));\n fixed (char* alphabetPtr = alphabet)\n fixed (char* resultPtr = result)\n {\n char* ptr = resultPtr;\n unchecked\n {\n for (int i = 0; i < value.Length; i++)\n {\n *ptr++ = *(alphabetPtr + (value[i] >> 4));\n *ptr++ = *(alphabetPtr + (value[i] & 0xF));\n }\n }\n }\n return result;\n }\n\n [System.Diagnostics.Contracts.Pure]\n public static unsafe byte[] FromHex(this string value)\n {\n if (value == null)\n throw new ArgumentNullException(\"value\");\n if (value.Length % 2 != 0)\n throw new ArgumentException(\"Hexadecimal value length must be even.\", \"value\");\n\n unchecked\n {\n byte[] result = new byte[value.Length / 2];\n fixed (char* valuePtr = value)\n {\n char* valPtr = valuePtr;\n for (int i = 0; i < result.Length; i++)\n {\n // 0(48) - 9(57) -> 0 - 9\n // A(65) - F(70) -> 10 - 15\n int b = *valPtr++; // High 4 bits.\n int val = ((b - '0') + ((('9' - b) >> 31) & -7)) << 4;\n b = *valPtr++; // Low 4 bits.\n val += (b - '0') + ((('9' - b) >> 31) & -7);\n result[i] = checked((byte)val);\n }\n }\n return result;\n }\n }\n}\n"
},
{
"answer_id": 21246369,
"author": "Maarten Bodewes",
"author_id": 589259,
"author_profile": "https://Stackoverflow.com/users/589259",
"pm_score": 2,
"selected": false,
"text": "StringBuilder public static String ToHex (byte[] data)\n{\n int dataLength = data.Length;\n // pre-create the stringbuilder using the length of the data * 2, precisely enough\n StringBuilder sb = new StringBuilder (dataLength * 2);\n for (int i = 0; i < dataLength; i++) {\n int b = data [i];\n\n // check using calculation over bits to see if first tuple is a letter\n // isLetter is zero if it is a digit, 1 if it is a letter\n int isLetter = (b >> 7) & ((b >> 6) | (b >> 5)) & 1;\n\n // calculate the code using a multiplication to make up the difference between\n // a digit character and an alphanumerical character\n int code = '0' + ((b >> 4) & 0xF) + isLetter * ('A' - '9' - 1);\n // now append the result, after casting the code point to a character\n sb.Append ((Char)code);\n\n // do the same with the lower (less significant) tuple\n isLetter = (b >> 3) & ((b >> 2) | (b >> 1)) & 1;\n code = '0' + (b & 0xF) + isLetter * ('A' - '9' - 1);\n sb.Append ((Char)code);\n }\n return sb.ToString ();\n}\n\npublic static byte[] FromHex (String hex)\n{\n\n // pre-create the array\n int resultLength = hex.Length / 2;\n byte[] result = new byte[resultLength];\n // set validity = 0 (0 = valid, anything else is not valid)\n int validity = 0;\n int c, isLetter, value, validDigitStruct, validDigit, validLetterStruct, validLetter;\n for (int i = 0, hexOffset = 0; i < resultLength; i++, hexOffset += 2) {\n c = hex [hexOffset];\n\n // check using calculation over bits to see if first char is a letter\n // isLetter is zero if it is a digit, 1 if it is a letter (upper & lowercase)\n isLetter = (c >> 6) & 1;\n\n // calculate the tuple value using a multiplication to make up the difference between\n // a digit character and an alphanumerical character\n // minus 1 for the fact that the letters are not zero based\n value = ((c & 0xF) + isLetter * (-1 + 10)) << 4;\n\n // check validity of all the other bits\n validity |= c >> 7; // changed to >>, maybe not OK, use UInt?\n\n validDigitStruct = (c & 0x30) ^ 0x30;\n validDigit = ((c & 0x8) >> 3) * (c & 0x6);\n validity |= (isLetter ^ 1) * (validDigitStruct | validDigit);\n\n validLetterStruct = c & 0x18;\n validLetter = (((c - 1) & 0x4) >> 2) * ((c - 1) & 0x2);\n validity |= isLetter * (validLetterStruct | validLetter);\n\n // do the same with the lower (less significant) tuple\n c = hex [hexOffset + 1];\n isLetter = (c >> 6) & 1;\n value ^= (c & 0xF) + isLetter * (-1 + 10);\n result [i] = (byte)value;\n\n // check validity of all the other bits\n validity |= c >> 7; // changed to >>, maybe not OK, use UInt?\n\n validDigitStruct = (c & 0x30) ^ 0x30;\n validDigit = ((c & 0x8) >> 3) * (c & 0x6);\n validity |= (isLetter ^ 1) * (validDigitStruct | validDigit);\n\n validLetterStruct = c & 0x18;\n validLetter = (((c - 1) & 0x4) >> 2) * ((c - 1) & 0x2);\n validity |= isLetter * (validLetterStruct | validLetter);\n }\n\n if (validity != 0) {\n throw new ArgumentException (\"Hexadecimal encoding incorrect for input \" + hex);\n }\n\n return result;\n}\n"
},
{
"answer_id": 24343727,
"author": "CodesInChaos",
"author_id": 445517,
"author_profile": "https://Stackoverflow.com/users/445517",
"pm_score": 6,
"selected": false,
"text": "private static readonly uint[] _lookup32 = CreateLookup32();\n\nprivate static uint[] CreateLookup32()\n{\n var result = new uint[256];\n for (int i = 0; i < 256; i++)\n {\n string s=i.ToString(\"X2\");\n result[i] = ((uint)s[0]) + ((uint)s[1] << 16);\n }\n return result;\n}\n\nprivate static string ByteArrayToHexViaLookup32(byte[] bytes)\n{\n var lookup32 = _lookup32;\n var result = new char[bytes.Length * 2];\n for (int i = 0; i < bytes.Length; i++)\n {\n var val = lookup32[bytes[i]];\n result[2*i] = (char)val;\n result[2*i + 1] = (char) (val >> 16);\n }\n return new string(result);\n}\n ushort struct{char X1, X2} struct{byte X1, X2} unsafe private static readonly uint[] _lookup32Unsafe = CreateLookup32Unsafe();\nprivate static readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_lookup32Unsafe,GCHandleType.Pinned).AddrOfPinnedObject();\n\nprivate static uint[] CreateLookup32Unsafe()\n{\n var result = new uint[256];\n for (int i = 0; i < 256; i++)\n {\n string s=i.ToString(\"X2\");\n if(BitConverter.IsLittleEndian)\n result[i] = ((uint)s[0]) + ((uint)s[1] << 16);\n else\n result[i] = ((uint)s[1]) + ((uint)s[0] << 16);\n }\n return result;\n}\n\npublic static string ByteArrayToHexViaLookup32Unsafe(byte[] bytes)\n{\n var lookupP = _lookup32UnsafeP;\n var result = new char[bytes.Length * 2];\n fixed(byte* bytesP = bytes)\n fixed (char* resultP = result)\n {\n uint* resultP2 = (uint*)resultP;\n for (int i = 0; i < bytes.Length; i++)\n {\n resultP2[i] = lookupP[bytesP[i]];\n }\n }\n return new string(result);\n}\n public static string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes)\n{\n var lookupP = _lookup32UnsafeP;\n var result = new string((char)0, bytes.Length * 2);\n fixed (byte* bytesP = bytes)\n fixed (char* resultP = result)\n {\n uint* resultP2 = (uint*)resultP;\n for (int i = 0; i < bytes.Length; i++)\n {\n resultP2[i] = lookupP[bytesP[i]];\n }\n }\n return result;\n}\n"
},
{
"answer_id": 26304129,
"author": "tne",
"author_id": 2266481,
"author_profile": "https://Stackoverflow.com/users/2266481",
"pm_score": 5,
"selected": false,
"text": "Convert.ToByte String.Substring Convert.ToByte Convert.ToByte String.Substring Convert.ToByte Convert.ToByte(char[], Int32) public static byte[] HexadecimalStringToByteArray_Original(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n for (var i = 0; i < outputLength; i++)\n output[i] = Convert.ToByte(input.Substring(i * 2, 2), 16);\n return output;\n }\n public static byte[] HexadecimalStringToByteArray_Rev4(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n using (var sr = new StringReader(input))\n {\n for (var i = 0; i < outputLength; i++)\n output[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);\n }\n return output;\n }\n String.Substring StringReader String.Substring Convert.ToByte public static byte[] HexadecimalStringToByteArray(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n var numeral = new char[2];\n using (var sr = new StringReader(input))\n {\n for (var i = 0; i < outputLength; i++)\n {\n numeral[0] = (char)sr.Read();\n numeral[1] = (char)sr.Read();\n output[i] = Convert.ToByte(new string(numeral), 16);\n }\n }\n return output;\n }\n numeral StringReader.Read public static byte[] HexadecimalStringToByteArray(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n var numeral = new char[2];\n using (var sr = new StringReader(input))\n {\n for (var i = 0; i < outputLength; i++)\n {\n var read = sr.Read(numeral, 0, 2);\n Debug.Assert(read == 2);\n output[i] = Convert.ToByte(new string(numeral), 16);\n }\n }\n return output;\n }\n _pos j _length _s Read String.CopyTo CopyTo public static byte[] HexadecimalStringToByteArray(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n var numeral = new char[2];\n for (int i = 0, j = 0; i < outputLength; i++, j += 2)\n {\n input.CopyTo(j, numeral, 0, 2);\n output[i] = Convert.ToByte(new string(numeral), 16);\n }\n return output;\n }\n j i i public static byte[] HexadecimalStringToByteArray_BestEffort(string input)\n {\n var outputLength = input.Length / 2;\n var output = new byte[outputLength];\n var numeral = new char[2];\n for (int i = 0; i < outputLength; i++)\n {\n input.CopyTo(i * 2, numeral, 0, 2);\n output[i] = Convert.ToByte(new string(numeral), 16);\n }\n return output;\n }\n String.Substring String.Substring String.Substring CopyTo String.Substring Convert.ToByte(String, Int32) String.Substring Convert.ToByte String.Substring Convert.ToByte(char[], Int32) String String.Substring Convert.ToByte(String, Int32) Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz\n Cores: 8\n Current Clock Speed: 2600\n Max Clock Speed: 2600\n--------------------\nParsing hexadecimal string into an array of bytes\n--------------------\nHexadecimalStringToByteArray_Original: 7,777.09 average ticks (over 10000 runs), 1.2X\nHexadecimalStringToByteArray_BestEffort: 8,550.82 average ticks (over 10000 runs), 1.1X\nHexadecimalStringToByteArray_Rev4: 9,218.03 average ticks (over 10000 runs), 1.0X\n 209113288F93A9AB8E474EA78D899AFDBB874355\n"
},
{
"answer_id": 33248172,
"author": "Nicholas Petersen",
"author_id": 264031,
"author_profile": "https://Stackoverflow.com/users/264031",
"pm_score": 1,
"selected": false,
"text": " /// <summary>\n /// Converts the byte array to a hex string very fast. Excellent job\n /// with code lightly adapted from 'community wiki' here: https://stackoverflow.com/a/14333437/264031\n /// (the function was originally named: ByteToHexBitFiddle). Now allows a native lowerCase option\n /// to be input and allows null or empty inputs (null returns null, empty returns empty).\n /// </summary>\n public static string ToHexString(this byte[] bytes, bool lowerCase = false)\n {\n if (bytes == null)\n return null;\n else if (bytes.Length == 0)\n return \"\";\n\n char[] c = new char[bytes.Length * 2];\n\n int b;\n int xAddToAlpha = lowerCase ? 87 : 55;\n int xAddToDigit = lowerCase ? -39 : -7;\n\n for (int i = 0; i < bytes.Length; i++) {\n\n b = bytes[i] >> 4;\n c[i * 2] = (char)(xAddToAlpha + b + (((b - 10) >> 31) & xAddToDigit));\n\n b = bytes[i] & 0xF;\n c[i * 2 + 1] = (char)(xAddToAlpha + b + (((b - 10) >> 31) & xAddToDigit));\n }\n\n string val = new string(c);\n return val;\n }\n\n public static string ToHexString(this IEnumerable<byte> bytes, bool lowerCase = false)\n {\n if (bytes == null)\n return null;\n byte[] arr = bytes.ToArray();\n return arr.ToHexString(lowerCase);\n }\n"
},
{
"answer_id": 34333212,
"author": "Geograph",
"author_id": 3302804,
"author_profile": "https://Stackoverflow.com/users/3302804",
"pm_score": 3,
"selected": false,
"text": " public static byte[] HexToBytes(this string hexString) \n {\n byte[] b = new byte[hexString.Length / 2]; \n char c;\n for (int i = 0; i < hexString.Length / 2; i++)\n {\n c = hexString[i * 2];\n b[i] = (byte)((c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)) << 4);\n c = hexString[i * 2 + 1];\n b[i] += (byte)(c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57));\n }\n\n return b;\n }\n public static string BytesToHex(this byte[] barray, bool toLowerCase = true)\n {\n byte addByte = 0x37;\n if (toLowerCase) addByte = 0x57;\n char[] c = new char[barray.Length * 2];\n byte b;\n for (int i = 0; i < barray.Length; ++i)\n {\n b = ((byte)(barray[i] >> 4));\n c[i * 2] = (char)(b > 9 ? b + addByte : b + 0x30);\n b = ((byte)(barray[i] & 0xF));\n c[i * 2 + 1] = (char)(b > 9 ? b + addByte : b + 0x30);\n }\n\n return new string(c);\n }\n"
},
{
"answer_id": 37351439,
"author": "Kel",
"author_id": 238441,
"author_profile": "https://Stackoverflow.com/users/238441",
"pm_score": 2,
"selected": false,
"text": "stackalloc static string ByteToHexBitFiddle(byte[] bytes)\n{\n var c = stackalloc char[bytes.Length * 2 + 1];\n int b; \n for (int i = 0; i < bytes.Length; ++i)\n {\n b = bytes[i] >> 4;\n c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7));\n b = bytes[i] & 0xF;\n c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7));\n }\n c[bytes.Length * 2 ] = '\\0';\n return new string(c);\n}\n"
},
{
"answer_id": 43736448,
"author": "Tommaso Ercole",
"author_id": 5903844,
"author_profile": "https://Stackoverflow.com/users/5903844",
"pm_score": 1,
"selected": false,
"text": "static string ByteArrayToHexViaLookupPerByte2(byte[] bytes)\n{ \n var result3 = new uint[bytes.Length];\n for (int i = 0; i < bytes.Length; i++)\n result3[i] = _Lookup32[bytes[i]];\n var handle = GCHandle.Alloc(result3, GCHandleType.Pinned);\n try\n {\n var result = Marshal.PtrToStringUni(handle.AddrOfPinnedObject(), bytes.Length * 2);\n return result;\n }\n finally\n {\n handle.Free();\n }\n}\n"
},
{
"answer_id": 50330863,
"author": "cahit beyaz",
"author_id": 1639347,
"author_profile": "https://Stackoverflow.com/users/1639347",
"pm_score": 0,
"selected": false,
"text": "public static class Utils\n{\n public static byte[] ToBin(this string hex)\n {\n int NumberChars = hex.Length;\n byte[] bytes = new byte[NumberChars / 2];\n for (int i = 0; i < NumberChars; i += 2)\n bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);\n return bytes;\n }\n public static string ToHex(this byte[] ba)\n {\n return BitConverter.ToString(ba).Replace(\"-\", \"\");\n }\n}\n byte[] arr1 = new byte[] { 1, 2, 3 };\n string hex1 = arr1.ToHex();\n byte[] arr2 = hex1.ToBin();\n"
},
{
"answer_id": 56378760,
"author": "SandRock",
"author_id": 282105,
"author_profile": "https://Stackoverflow.com/users/282105",
"pm_score": 1,
"selected": false,
"text": "00-aa-84-fb\n12 32 FF CD\n12 00\n12_32_FF_CD\n1200d5e68a\n /// <summary>Reads a hex string into bytes</summary>\npublic static IEnumerable<byte> HexadecimalStringToBytes(string hex) {\n if (hex == null)\n throw new ArgumentNullException(nameof(hex));\n\n char c, c1 = default(char);\n bool hasc1 = false;\n unchecked {\n for (int i = 0; i < hex.Length; i++) {\n c = hex[i];\n bool isValid = 'A' <= c && c <= 'f' || 'a' <= c && c <= 'f' || '0' <= c && c <= '9';\n if (!hasc1) {\n if (isValid) {\n hasc1 = true;\n }\n } else {\n hasc1 = false;\n if (isValid) {\n yield return (byte)((GetHexVal(c1) << 4) + GetHexVal(c));\n }\n }\n\n c1 = c;\n } \n }\n}\n\n/// <summary>Reads a hex string into a byte array</summary>\npublic static byte[] HexadecimalStringToByteArray(string hex)\n{\n if (hex == null)\n throw new ArgumentNullException(nameof(hex));\n\n var bytes = new List<byte>(hex.Length / 2);\n foreach (var item in HexadecimalStringToBytes(hex)) {\n bytes.Add(item);\n }\n\n return bytes.ToArray();\n}\n\nprivate static byte GetHexVal(char val)\n{\n return (byte)(val - (val < 0x3A ? 0x30 : val < 0x5B ? 0x37 : 0x57));\n // ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^^^^\n // digits 0-9 upper char A-Z a-z\n}\n"
},
{
"answer_id": 58666976,
"author": "tomasz_kajetan_stanczak",
"author_id": 1860672,
"author_profile": "https://Stackoverflow.com/users/1860672",
"pm_score": 1,
"selected": false,
"text": " // a safe version of the lookup solution: \n\n public static string ByteArrayToHexViaLookup32Safe(byte[] bytes, bool withZeroX)\n {\n if (bytes.Length == 0)\n {\n return withZeroX ? \"0x\" : \"\";\n }\n\n int length = bytes.Length * 2 + (withZeroX ? 2 : 0);\n StateSmall stateToPass = new StateSmall(bytes, withZeroX);\n return string.Create(length, stateToPass, (chars, state) =>\n {\n int offset0x = 0;\n if (state.WithZeroX)\n {\n chars[0] = '0';\n chars[1] = 'x';\n offset0x += 2;\n }\n\n Span<uint> charsAsInts = MemoryMarshal.Cast<char, uint>(chars.Slice(offset0x));\n int targetLength = state.Bytes.Length;\n for (int i = 0; i < targetLength; i += 1)\n {\n uint val = Lookup32[state.Bytes[i]];\n charsAsInts[i] = val;\n }\n });\n }\n\n private struct StateSmall\n {\n public StateSmall(byte[] bytes, bool withZeroX)\n {\n Bytes = bytes;\n WithZeroX = withZeroX;\n }\n\n public byte[] Bytes;\n public bool WithZeroX;\n }\n"
},
{
"answer_id": 58975761,
"author": "Erçin Dedeoğlu",
"author_id": 2426367,
"author_profile": "https://Stackoverflow.com/users/2426367",
"pm_score": 2,
"selected": false,
"text": " public static string BytesToString(byte[] ba) =>\n ba.Aggregate(new StringBuilder(32), (sb, b) => sb.Append(b.ToString(\"X2\"))).ToString();\n"
},
{
"answer_id": 60626134,
"author": "Gregory Morse",
"author_id": 2908254,
"author_profile": "https://Stackoverflow.com/users/2908254",
"pm_score": 2,
"selected": false,
"text": "BigInteger.Parse(str, System.Globalization.NumberStyles.HexNumber).ToByteArray().Reverse().ToArray();\n"
},
{
"answer_id": 61492572,
"author": "ravthiru",
"author_id": 737936,
"author_profile": "https://Stackoverflow.com/users/737936",
"pm_score": -1,
"selected": false,
"text": "Byte.toUnsignedInt public static String convertBytesToHex(byte[] bytes) {\n StringBuilder result = new StringBuilder();\n for (byte byt : bytes) {\n int decimal = Byte.toUnsignedInt(byt);\n String hex = Integer.toHexString(decimal);\n result.append(hex);\n }\n return result.toString();\n}\n"
},
{
"answer_id": 63864709,
"author": "Paul",
"author_id": 3591916,
"author_profile": "https://Stackoverflow.com/users/3591916",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Extension methods to quickly convert byte array to string and back.\n/// </summary>\npublic static class HexConverter\n{\n /// <summary>\n /// Map values to hex digits\n /// </summary>\n private static readonly char[] HexDigits =\n {\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'\n };\n\n /// <summary>\n /// Map 56 characters between ['0', 'F'] to their hex equivalents, and set invalid characters\n /// such that they will overflow byte to fail conversion.\n /// </summary>\n private static readonly ushort[] HexValues =\n {\n 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100,\n 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100,\n 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x0100, 0x000A, 0x000B,\n 0x000C, 0x000D, 0x000E, 0x000F\n };\n\n /// <summary>\n /// Empty byte array \n /// </summary>\n private static readonly byte[] Empty = new byte[0];\n\n /// <summary>\n /// Convert a byte array to a hexadecimal string.\n /// </summary>\n /// <param name=\"bytes\">\n /// The input byte array.\n /// </param>\n /// <returns>\n /// A string of hexadecimal digits.\n /// </returns>\n public static string ToHexString(this byte[] bytes)\n {\n var c = new char[bytes.Length * 2];\n for (int i = 0, j = 0; i < bytes.Length; i++)\n {\n c[j++] = HexDigits[bytes[i] >> 4];\n c[j++] = HexDigits[bytes[i] & 0x0F];\n }\n\n return new string(c);\n }\n\n /// <summary>\n /// Parse a string of hexadecimal digits into a byte array.\n /// </summary>\n /// <param name=\"hexadecimalString\">\n /// The hexadecimal string.\n /// </param>\n /// <returns>\n /// The parsed <see cref=\"byte[]\"/> array.\n /// </returns>\n /// <exception cref=\"ArgumentException\">\n /// The input string either contained invalid characters, or was of an odd length.\n /// </exception>\n public static byte[] ToByteArray(string hexadecimalString)\n {\n if (!TryParse(hexadecimalString, out var value))\n {\n throw new ArgumentException(\"Invalid hexadecimal string\", nameof(hexadecimalString));\n }\n\n return value;\n }\n\n /// <summary>\n /// Parse a hexadecimal string to bytes\n /// </summary>\n /// <param name=\"hexadecimalString\">\n /// The hexadecimal string, which must be an even number of characters.\n /// </param>\n /// <param name=\"value\">\n /// The parsed value if successful.\n /// </param>\n /// <returns>\n /// True if successful.\n /// </returns>\n public static bool TryParse(string hexadecimalString, out byte[] value)\n {\n if (hexadecimalString.Length == 0)\n {\n value = Empty;\n return true;\n }\n\n if (hexadecimalString.Length % 2 != 0)\n {\n value = Empty;\n return false;\n }\n\n try\n {\n\n value = new byte[hexadecimalString.Length / 2];\n for (int i = 0, j = 0; j < hexadecimalString.Length; i++)\n {\n value[i] = (byte)((HexValues[hexadecimalString[j++] - '0'] << 4)\n | HexValues[hexadecimalString[j++] - '0']);\n }\n\n return true;\n }\n catch (OverflowException)\n {\n value = Empty;\n return false;\n }\n }\n}\n"
},
{
"answer_id": 64490764,
"author": "balrob",
"author_id": 1676498,
"author_profile": "https://Stackoverflow.com/users/1676498",
"pm_score": 5,
"selected": false,
"text": "Convert.ToHexString(byte[] inArray) string Convert.FromHexString(string s) byte[]"
},
{
"answer_id": 64498722,
"author": "AlejandroAlis",
"author_id": 5583316,
"author_profile": "https://Stackoverflow.com/users/5583316",
"pm_score": 3,
"selected": false,
"text": " static public byte[] HexStrToByteArray(string str)\n {\n byte[] res = new byte[(str.Length % 2 != 0 ? 0 : str.Length / 2)]; //check and allocate memory\n for (int i = 0, j = 0; j < res.Length; i += 2, j++) //convert loop\n res[j] = (byte)((str[i] % 32 + 9) % 25 * 16 + (str[i + 1] % 32 + 9) % 25);\n return res;\n }\n"
},
{
"answer_id": 66437123,
"author": "Ali Zahid",
"author_id": 2631220,
"author_profile": "https://Stackoverflow.com/users/2631220",
"pm_score": 3,
"selected": false,
"text": "internal static class ByteArrayExtensions\n{\n \n public static string ToHexString(this byte[] bytes, Casing casing = Casing.Upper)\n {\n Span<char> result = stackalloc char[0];\n if (bytes.Length > 16)\n {\n var array = new char[bytes.Length * 2];\n result = array.AsSpan();\n }\n else\n {\n result = stackalloc char[bytes.Length * 2];\n }\n\n int pos = 0;\n foreach (byte b in bytes)\n {\n ToCharsBuffer(b, result, pos, casing);\n pos += 2;\n }\n\n return result.ToString();\n }\n\n private static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)\n {\n uint difference = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU) - 0x8989U;\n uint packedResult = ((((uint)(-(int)difference) & 0x7070U) >> 4) + difference + 0xB9B9U) | (uint)casing;\n\n buffer[startingIndex + 1] = (char)(packedResult & 0xFF);\n buffer[startingIndex] = (char)(packedResult >> 8);\n }\n}\n\npublic enum Casing : uint\n{\n // Output [ '0' .. '9' ] and [ 'A' .. 'F' ].\n Upper = 0,\n\n // Output [ '0' .. '9' ] and [ 'a' .. 'f' ].\n Lower = 0x2020U,\n}\n"
},
{
"answer_id": 68066131,
"author": "Rosei",
"author_id": 13817556,
"author_profile": "https://Stackoverflow.com/users/13817556",
"pm_score": 3,
"selected": false,
"text": "input length: 10,000,000 bytes\nruns: 100\naverage elapsed time per run:\nV1 = 136.4ms\nV2 = 104.5ms\nV3 = 22.0ms\nV4 = 9.9ms\nV5_1 = 10.2ms\nV5_2 = 9.0ms\nV5_3 = 9.3ms\nV6 = 18.3ms\nV7 = 9.8ms\nV8 = 8.8ms\nV9 = 10.2ms\nV10 = 19.0ms\nV11 = 12.2ms\nV12 = 27.4ms\nV13 = 21.8ms\nV14 = 12.0ms\nV15 = 14.9ms\nV16 = 15.3ms\nV17 = 9.5ms\nV18 got excluded from this test, because it was very slow when using very long string\nV19 = 222.8ms\nV20 = 66.0ms\nV21 = 15.4ms\n\nV1 average ticks per run: 1363529.4\nV2 is more fast than V1 by: 1.3 times (ticks ratio)\nV3 is more fast than V1 by: 6.2 times (ticks ratio)\nV4 is more fast than V1 by: 13.8 times (ticks ratio)\nV5_1 is more fast than V1 by: 13.3 times (ticks ratio)\nV5_2 is more fast than V1 by: 15.2 times (ticks ratio)\nV5_3 is more fast than V1 by: 14.8 times (ticks ratio)\nV6 is more fast than V1 by: 7.4 times (ticks ratio)\nV7 is more fast than V1 by: 13.9 times (ticks ratio)\nV8 is more fast than V1 by: 15.4 times (ticks ratio)\nV9 is more fast than V1 by: 13.4 times (ticks ratio)\nV10 is more fast than V1 by: 7.2 times (ticks ratio)\nV11 is more fast than V1 by: 11.1 times (ticks ratio)\nV12 is more fast than V1 by: 5.0 times (ticks ratio)\nV13 is more fast than V1 by: 6.3 times (ticks ratio)\nV14 is more fast than V1 by: 11.4 times (ticks ratio)\nV15 is more fast than V1 by: 9.2 times (ticks ratio)\nV16 is more fast than V1 by: 8.9 times (ticks ratio)\nV17 is more fast than V1 by: 14.4 times (ticks ratio)\nV19 is more SLOW than V1 by: 1.6 times (ticks ratio)\nV20 is more fast than V1 by: 2.1 times (ticks ratio)\nV21 is more fast than V1 by: 8.9 times (ticks ratio)\n V18 took long time at the previous test, \nso let's decrease length for it: \ninput length: 1,000,000 bytes\nruns: 100\naverage elapsed time per run: V1 = 14.1ms , V18 = 146.7ms\nV1 average ticks per run: 140630.3\nV18 is more SLOW than V1 by: 10.4 times (ticks ratio)\n input length: 100 byte\nruns: 1,000,000\nV1 average ticks per run: 14.6\nV2 is more fast than V1 by: 1.4 times (ticks ratio)\nV3 is more fast than V1 by: 5.9 times (ticks ratio)\nV4 is more fast than V1 by: 15.7 times (ticks ratio)\nV5_1 is more fast than V1 by: 15.1 times (ticks ratio)\nV5_2 is more fast than V1 by: 18.4 times (ticks ratio)\nV5_3 is more fast than V1 by: 16.3 times (ticks ratio)\nV6 is more fast than V1 by: 5.3 times (ticks ratio)\nV7 is more fast than V1 by: 15.7 times (ticks ratio)\nV8 is more fast than V1 by: 18.0 times (ticks ratio)\nV9 is more fast than V1 by: 15.5 times (ticks ratio)\nV10 is more fast than V1 by: 7.8 times (ticks ratio)\nV11 is more fast than V1 by: 12.4 times (ticks ratio)\nV12 is more fast than V1 by: 5.3 times (ticks ratio)\nV13 is more fast than V1 by: 5.2 times (ticks ratio)\nV14 is more fast than V1 by: 13.4 times (ticks ratio)\nV15 is more fast than V1 by: 9.9 times (ticks ratio)\nV16 is more fast than V1 by: 9.2 times (ticks ratio)\nV17 is more fast than V1 by: 16.2 times (ticks ratio)\nV18 is more fast than V1 by: 1.1 times (ticks ratio)\nV19 is more SLOW than V1 by: 1.6 times (ticks ratio)\nV20 is more fast than V1 by: 1.9 times (ticks ratio)\nV21 is more fast than V1 by: 11.4 times (ticks ratio)\n static byte[] HexStringToByteArrayV5_3(string hexString) {\n int hexStringLength = hexString.Length;\n byte[] b = new byte[hexStringLength / 2];\n for (int i = 0; i < hexStringLength; i += 2) {\n int topChar = hexString[i];\n topChar = (topChar > 0x40 ? (topChar & ~0x20) - 0x37 : topChar - 0x30) << 4;\n int bottomChar = hexString[i + 1];\n bottomChar = bottomChar > 0x40 ? (bottomChar & ~0x20) - 0x37 : bottomChar - 0x30;\n b[i / 2] = (byte)(topChar + bottomChar);\n }\n return b;\n}\n"
},
{
"answer_id": 68596484,
"author": "TrustworthySystems",
"author_id": 6531333,
"author_profile": "https://Stackoverflow.com/users/6531333",
"pm_score": 4,
"selected": false,
"text": "byte[] string System.Convert.ToHexString var myBytes = new byte[100];\nvar myString = System.Convert.ToHexString(myBytes);\n string byte[] System.Convert.FromHexString var myString = \"E10B116E8530A340BCC7B3EAC208487B\";\nvar myBytes = System.Convert.FromHexString(myString);\n"
},
{
"answer_id": 71781152,
"author": "Ben",
"author_id": 1188047,
"author_profile": "https://Stackoverflow.com/users/1188047",
"pm_score": 0,
"selected": false,
"text": "public static String encode(byte[] bytes, boolean uppercase) {\n char[] result = new char[2 * bytes.length];\n for (int i = 0; i < bytes.length; i++) {\n byte word = bytes[i];\n byte left = (byte) ((0XF0 & word) >>> 4);\n byte right = (byte) ((byte) 0X0F & word);\n\n int resultIndex = i * 2;\n result[resultIndex] = encode(left, uppercase);\n result[resultIndex + 1] = encode(right, uppercase);\n }\n return new String(result);\n}\n\npublic static char encode(byte value, boolean uppercase) {\n int characterCase = uppercase ? 0 : 32;\n if (value > 15 || value < 0) {\n return '0';\n }\n if (value > 9) {\n return (char) (value + 0x37 | characterCase);\n }\n return (char) (value + 0x30);\n}\n"
},
{
"answer_id": 71904920,
"author": "antoninkriz",
"author_id": 3161322,
"author_profile": "https://Stackoverflow.com/users/3161322",
"pm_score": 3,
"selected": false,
"text": "using System;\nstring result = Convert.ToHexString(bytesToConvert);\n Convert.ToHexString B33F69 b33f69 Convert.ToHexString ToLower() unsafe X2 x2 Mean N=100 ConvertToHexString using System;\n\nstring result = Convert.ToHexString(bytesToConvert);\n unsafe LookupPerByteSpan LookupPerByte unsafe LookupSpanPerByteSpan ReadOnlySpan<byte> private static readonly uint[] Lookup32 = Enumerable.Range(0, 256).Select(i =>\n{\n string s = i.ToString(\"X2\");\n return s[0] + ((uint)s[1] << 16);\n}).ToArray();\n\npublic string ToHexString(byte[] bytes)\n{\n var result = bytes.Length * 2 <= 1024\n ? stackalloc char[bytes.Length * 2]\n : new char[bytes.Length * 2];\n\n for (int i = 0; i < bytes.Length; i++)\n {\n var val = Lookup32[bytes[i]];\n result[2 * i] = (char)val;\n result[2 * i + 1] = (char)(val >> 16);\n }\n\n return new string(result);\n}\n LookupAndShiftAlphabetSpanMultiply ReadOnlySpan<byte> new byte {1, 2, 3, ...} private static ReadOnlySpan<byte> HexAlphabetSpan => new[]\n{\n (byte)'0', (byte)'1', (byte)'2', (byte)'3',\n (byte)'4', (byte)'5', (byte)'6', (byte)'7',\n (byte)'8', (byte)'9', (byte)'A', (byte)'B',\n (byte)'C', (byte)'D', (byte)'E', (byte)'F'\n};\n\npublic static string ToHexString(byte[] bytes)\n{\n var res = bytes.Length * 2 <= 1024 ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2];\n\n for (var i = 0; i < bytes.Length; ++i)\n {\n var j = i * 2;\n res[j] = (char)HexAlphabetSpan[bytes[i] >> 4];\n res[j + 1] = (char)HexAlphabetSpan[bytes[i] & 0xF];\n }\n\n return new string(res);\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582/"
] |
311,166 | <p>When using the <a href="http://en.wikipedia.org/wiki/Pimpl_idiom" rel="nofollow noreferrer">pImpl idiom</a> is it preferable to use a <code>boost:shared_ptr</code> instead of a <code>std::auto_ptr</code>? I'm sure I once read that the boost version is more exception friendly?</p>
<pre><code>class Foo
{
public:
Foo();
private:
struct impl;
std::auto_ptr<impl> impl_;
};
class Foo
{
public:
Foo();
private:
struct impl;
boost::shared_ptr<impl> impl_;
};
</code></pre>
<p>[EDIT] Is it always safe to use std::auto_ptr<> or are there situations when an alternative boost smart pointer is required?</p>
| [
{
"answer_id": 311182,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 4,
"selected": false,
"text": "auto_ptr boost::noncopyable auto_ptr impl delete impl_ auto_ptr"
},
{
"answer_id": 311185,
"author": "kshahar",
"author_id": 33982,
"author_profile": "https://Stackoverflow.com/users/33982",
"pm_score": 2,
"selected": false,
"text": "std::auto_ptr boost::scoped_ptr auto_ptr boost::scoped_ptr"
},
{
"answer_id": 311219,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 1,
"selected": false,
"text": "auto_ptr auto_ptr const auto_ptr"
},
{
"answer_id": 311252,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 6,
"selected": true,
"text": "// in MyClass.h\n\nclass Pimpl;\n\nclass MyClass \n{ \nprivate:\n std::auto_ptr<Pimpl> pimpl;\n\npublic: \n MyClass();\n};\n\n// Body of these functions in MyClass.cpp\n // in MyClass.h\n\nclass Pimpl;\n\nclass MyClass \n{ \nprivate:\n std::auto_ptr<Pimpl> pimpl;\n\npublic: \n MyClass();\n ~MyClass();\n};\n // in MyClass.cpp\n\n#include \"Pimpl.h\"\n\nMyClass::MyClass() : pimpl(new Pimpl(blah))\n{\n}\n\nMyClass::~MyClass() \n{\n // this needs to be here, even when empty\n}\n"
},
{
"answer_id": 7013002,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 1,
"selected": false,
"text": "scoped_ptr shared_ptr shared_ptr class CopyableFoo {\npublic:\n ...\n CopyableFoo (const CopyableFoo&);\n CopyableFoo& operator= (const CopyableFoo&);\nprivate:\n scoped_ptr<Impl> impl_;\n};\n\n...\nCopyableFoo (const CopyableFoo& rhs)\n : impl_(new Impl (*rhs.impl_))\n{}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
311,181 | <p>I'm looking for a open source .Net HTTP proxy library. Basically I want to develop something like Fiddler (so much lighter with less features).</p>
| [
{
"answer_id": 311200,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "RewriteRule ^(.*) http://www.testsiteXY.com$1 [P]\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,184 | <p>I'm using Oracle 10g and I'm trying to "stack" the conditions in a CASE statement, like I would do in C++ :</p>
<pre><code>case 1:
case 2:
// instructions
break;
</code></pre>
<p>i.e. having the same code block executed for two different successful conditions.</p>
<p>I've tried :</p>
<pre><code>WHEN 1, 2 THEN
WHEN 1 OR 2 THEN
</code></pre>
<p>... without luck.
Is it even possible ?</p>
<p><strong>EDIT</strong> - Full snippet</p>
<pre><code>CASE v_n
WHEN (1 OR 2) THEN
dbms_output.put_line('Case 1 or 2');
WHEN 3 THEN
dbms_output.put_line('Case 3');
END CASE;
</code></pre>
<p>Generates an <strong>expression is of wrong type</strong> error</p>
| [
{
"answer_id": 311208,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 6,
"selected": true,
"text": "CASE\n WHEN v_n = 1 OR v_n = 2 THEN\n dbms_output.put_line('Case 1 or 2');\n WHEN v_n = 3 THEN\n dbms_output.put_line('Case 3'); \nEND CASE;\n"
},
{
"answer_id": 37603025,
"author": "Dima Korobskiy",
"author_id": 534217,
"author_profile": "https://Stackoverflow.com/users/534217",
"pm_score": 2,
"selected": false,
"text": "BEGIN\n CASE \n WHEN EXTRACT(YEAR FROM SYSDATE) IN (2015, 2016, 2017) THEN\n dbms_output.put_line('Yes');\n ELSE\n dbms_output.put_line('No');\n END CASE;\nEND;\n/\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77004/"
] |
311,188 | <p>I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), <b>EDIT</b> it and save it back to the DB. Secondly how do I <b>DELETE</b> the data that's in the DB? i.e. search, select and then delete!</p>
<p>Please show me an example of the code I need to write on my <code>view.py</code> and <code>urls.py</code> for perform this task.</p>
| [
{
"answer_id": 311191,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 5,
"selected": false,
"text": "emp = Employee.objects.get(pk = emp_id)\nemp.name = 'Somename'\nemp.save()\n emp.delete()\n def update(request, id):\n emp = Employee.objects.get(pk = id)\n #you can do this for as many fields as you like\n #here I asume you had a form with input like <input type=\"text\" name=\"name\"/>\n #so it's basically like that for all form fields\n emp.name = request.POST.get('name')\n emp.save()\n return HttpResponse('updated')\n\ndef delete(request, id):\n emp = Employee.objects.get(pk = id)\n emp.delete()\n return HttpResponse('deleted')\n (r'^delete/(\\d+)/$','myproject.myapp.views.delete'),\n(r'^update/(\\d+)/$','myproject.myapp.views.update'),\n"
},
{
"answer_id": 57261909,
"author": "Real.Cryptc",
"author_id": 10495823,
"author_profile": "https://Stackoverflow.com/users/10495823",
"pm_score": 2,
"selected": false,
"text": "b = ModelName.objects.get(id = 1)\nb.delete()\n b = ModelName.objects.get(id = 1)\nb.name = 'Henry'\nb.save()\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20894/"
] |
311,193 | <p>I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?</p>
| [
{
"answer_id": 311195,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 6,
"selected": true,
"text": "public class MyClass\n{\n public List<MyItem> Items;\n}\n public class MyItemCollection : List<MyItem>\n{\n}\n\npublic class MyClass\n{\n public MyItemCollection Items;\n}\n public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }\n"
},
{
"answer_id": 311232,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 1,
"selected": false,
"text": "public static implicit operator MyClass(List m) \n{\n // code to convert from m to MyClass\n}\n\npublic static explicit operator List(MyClass m) \n{\n // code to convert from MyClass list\n}\n"
},
{
"answer_id": 312506,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "List<T> Collection<T> virtual List<T> virtual"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html" rel="noreferrer">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources" rel="noreferrer">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| [
{
"answer_id": 311360,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "class Bit( object ):\n def __init__( self, size ):\n self.bits= array.array('B',[0 for i in range((size+7)//8)] )\n def set( self, bit ):\n b= self.bits[bit//8]\n self.bits[bit//8] = b | 1 << (bit % 8)\n def get( self, bit ):\n b= self.bits[bit//8]\n return (b >> (bit % 8)) & 1\n //8 % 8 >>3 &0x07 'B' 8 'L' 32 'H'"
},
{
"answer_id": 311907,
"author": "Ryan Cox",
"author_id": 620,
"author_profile": "https://Stackoverflow.com/users/620",
"pm_score": 5,
"selected": false,
"text": "from BitVector import BitVector\nfrom random import Random\n# get hashes from http://www.partow.net/programming/hashfunctions/index.html\nfrom hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash\n\n\n#\n# ryan.a.cox@gmail.com / www.asciiarmor.com\n#\n# copyright (c) 2008, ryan cox\n# all rights reserved \n# BSD license: http://www.opensource.org/licenses/bsd-license.php\n#\n\nclass BloomFilter(object):\n def __init__(self, n=None, m=None, k=None, p=None, bits=None ):\n self.m = m\n if k > 4 or k < 1:\n raise Exception('Must specify value of k between 1 and 4')\n self.k = k\n if bits:\n self.bits = bits\n else:\n self.bits = BitVector( size=m )\n self.rand = Random()\n self.hashes = []\n self.hashes.append(RSHash)\n self.hashes.append(JSHash)\n self.hashes.append(PJWHash)\n self.hashes.append(DJBHash)\n\n # switch between hashing techniques\n self._indexes = self._rand_indexes\n #self._indexes = self._hash_indexes\n\n def __contains__(self, key):\n for i in self._indexes(key): \n if not self.bits[i]:\n return False \n return True \n\n def add(self, key):\n dupe = True \n bits = []\n for i in self._indexes(key): \n if dupe and not self.bits[i]:\n dupe = False\n self.bits[i] = 1\n bits.append(i)\n return dupe\n\n def __and__(self, filter):\n if (self.k != filter.k) or (self.m != filter.m): \n raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND')\n return BloomFilter(m=self.m,k=self.k,bits=(self.bits & filter.bits))\n\n def __or__(self, filter):\n if (self.k != filter.k) or (self.m != filter.m): \n raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR')\n return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits))\n\n def _hash_indexes(self,key):\n ret = []\n for i in range(self.k):\n ret.append(self.hashes[i](key) % self.m)\n return ret\n\n def _rand_indexes(self,key):\n self.rand.seed(hash(key))\n ret = []\n for i in range(self.k):\n ret.append(self.rand.randint(0,self.m-1))\n return ret\n\nif __name__ == '__main__':\n e = BloomFilter(m=100, k=4)\n e.add('one')\n e.add('two')\n e.add('three')\n e.add('four')\n e.add('five') \n\n f = BloomFilter(m=100, k=4)\n f.add('three')\n f.add('four')\n f.add('five')\n f.add('six')\n f.add('seven')\n f.add('eight')\n f.add('nine')\n f.add(\"ten\") \n\n # test check for dupe on add\n assert not f.add('eleven') \n assert f.add('eleven') \n\n # test membership operations\n assert 'ten' in f \n assert 'one' in e \n assert 'ten' not in e \n assert 'one' not in f \n\n # test set based operations\n union = f | e\n intersection = f & e\n\n assert 'ten' in union\n assert 'one' in union \n assert 'three' in intersection\n assert 'ten' not in intersection\n assert 'one' not in intersection\n def fast_count_bits( self, v ):\n bits = (\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 )\n\n return bits[v & 0xff] + bits[(v >> 8) & 0xff] + bits[(v >> 16) & 0xff] + bits[v >> 24]\n"
},
{
"answer_id": 12060876,
"author": "user1277476",
"author_id": 1277476,
"author_profile": "https://Stackoverflow.com/users/1277476",
"pm_score": 2,
"selected": false,
"text": "__init__"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
311,206 | <p>I have these 2 vectors:</p>
<pre><code>alpha =
1 1 1 1 1 1 1 1 1
f_uv =
193 193 194 192 193 193 190 189 191
</code></pre>
<p>And when I do this:</p>
<pre><code>alphaf_uv = alpha * f_uv'
</code></pre>
<p>I get the error message:</p>
<pre><code>"??? Error using ==> mtimes
Integers can only be combined with integers of the same class, or scalar doubles."
</code></pre>
<p>The interesting part is that this error doesn't appear if I define the same vectors in the console and try the multiplication there.</p>
<p><code>alpha</code> is defined by me and <code>f_uv</code> is obtained from some pixels in a PNG image.</p>
| [
{
"answer_id": 311209,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "f_uv' alphaf_uv = double(alpha) * double(f_uv')\n alphaf_uv"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38721/"
] |
311,221 | <p>If you had a 10 minute hands-on session to teach someone Emacs, what would you show them?</p>
<pre>
Start emacs: emacs
...
Quit emacs: C-x C-c
</pre>
<p>What else would you have them do between starting and quitting Emacs, while you stood behind them?</p>
| [
{
"answer_id": 311226,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "M-x"
},
{
"answer_id": 311239,
"author": "Miserable Variable",
"author_id": 18573,
"author_profile": "https://Stackoverflow.com/users/18573",
"pm_score": 1,
"selected": false,
"text": "XEmacs 21.4 (patch 21) \"Educational Television\" (cygwin, Mule) of Tue Dec 4 2007 on vzell-de \n\n`C-' means the control key,`M-' means the meta key \n\n\nInformation, on-line help: \n\nXEmacs comes with plenty of documentation... \n\n\nM-? F: read the XEmacs FAQ (a capital F!) \nM-? t: read the XEmacs tutorial (also available through the Help menu) \nf1: get help on using XEmacs (also available through the Help menu) \nM-? i: read the on-line documentation \n\nM-x describe-project: read about the GNU project \nM-x about-xemacs: see who's developing XEmacs \n"
},
{
"answer_id": 311663,
"author": "ShreevatsaR",
"author_id": 4958,
"author_profile": "https://Stackoverflow.com/users/4958",
"pm_score": 7,
"selected": true,
"text": "C-x C-c C-g ESC ESC ESC C-h t M-x function-name C-h k [keystroke] self-insert-command C-h a M-x apropos-command C-h a paragraph C-h w command-name M-x describe-function C-h f M-x apropos-documentation C-h d C-h C-h C-h C-c C-h"
},
{
"answer_id": 8364556,
"author": "yPhil",
"author_id": 1729094,
"author_profile": "https://Stackoverflow.com/users/1729094",
"pm_score": 1,
"selected": false,
"text": "C-h C-h C-y M-y C-u C-SPC"
},
{
"answer_id": 8555058,
"author": "stevejb",
"author_id": 318976,
"author_profile": "https://Stackoverflow.com/users/318976",
"pm_score": 0,
"selected": false,
"text": "M-x re-builder org-mode"
},
{
"answer_id": 8560189,
"author": "aerique",
"author_id": 206767,
"author_profile": "https://Stackoverflow.com/users/206767",
"pm_score": 0,
"selected": false,
"text": "M-x global-set-key M-x M-x apropos"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,242 | <p>I'm new to PHP and I'm trying to do something that may be bad practise and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do.</p>
<p>I have one webpage with a form that collects data. That is submited to a PHP script that does a bunch of processing - but doesn't actually display anything important. What I want is that once the processing is done, the script then tells the browser to open another page, where the results are displayed. </p>
<p>I know I can use <em>header('Location: page.php');</em> but I can't work out how to provide POST data with this. How can I do that? Alternatively, is there another way to tell the browser to open another page?</p>
<p>EDIT: What I'm taking from the responses is that it's <em>possible</em> to do this using various hacks but I'd be better off to just have the processing and the display code in one file. I'm happy with that; this was an experiment more than anything.</p>
| [
{
"answer_id": 311269,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 4,
"selected": false,
"text": "session_start();\n$_SESSION['formdata'] = $_POST; //or whatever\n session_start();\nprint_r($_SESSION['formdata']);\n header('Location: page.php?' . http_build_query($_POST)); \n"
},
{
"answer_id": 311348,
"author": "Tom",
"author_id": 26155,
"author_profile": "https://Stackoverflow.com/users/26155",
"pm_score": 2,
"selected": false,
"text": "<form id=\"redirect_form\" method=\"post\" action=\"http://someserver.com/somepage.php\">\n <input type=\"hidden\" name=\"field_1\" value=\"<?php echo htmlentities($value_1); ?>\">\n <input type=\"hidden\" name=\"field_2\" value=\"<?php echo htmlentities($value_2); ?>\">\n <input type=\"hidden\" name=\"field_3\" value=\"<?php echo htmlentities($value_3); ?>\">\n</form>\n<script type=\"text/javascript\">\n document.getElementById('redirect_form').submit();\n</script>\n"
},
{
"answer_id": 313627,
"author": "Josh Smeaton",
"author_id": 10583,
"author_profile": "https://Stackoverflow.com/users/10583",
"pm_score": 4,
"selected": true,
"text": "<form method=\"post\" action=\"display.php\">\n...\n</form>\n if ($_POST) {\n require_once(process.php);\n process($_POST);\n display_results;\n}\n"
},
{
"answer_id": 313636,
"author": "user10117",
"author_id": 10117,
"author_profile": "https://Stackoverflow.com/users/10117",
"pm_score": 0,
"selected": false,
"text": "<?php if($doingForm) { ?>\n\nhtml for form here\n\n<?php } else { ?>\n\nhtml for results\n\n<? } ?>\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39905/"
] |
311,243 | <p>I have a Java application and I would like to make it extensible. To create an extension, developers within our company will write a Java class that implements a certain interface. They may also wish to write associated helper classes. I would like to load these extensions into the application without an outage.</p>
<p>I would like to limit what this class can do to the following:</p>
<ol>
<li>Call methods in the application's API (this will be a parameter to the constructor)</li>
<li>Create instances of other objects within the same package (so the author of the extension class can use other classes to get the job done).</li>
</ol>
<p>When the class is invoked the API object that is passed in will already have a "customer" defined and stored as a member variable. It will use this to limit access via the API to that customer's data.</p>
<p>I do not want these classes doing things such as accessing the database, writing to disk, or otherwise doing things etc. This is mostly an effort at dependency management and encapsulation as the same team of developers will have access to write both extensions and the core system.</p>
<p>Is there a pattern for this? Am I on the right track?</p>
| [
{
"answer_id": 312001,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "grant codeBase \"file:/path/to/app/lib/*\" {\n permission java.io.FilePermission \"/path/to/app/-\", \"read\";\n permission java.io.FilePermission \"/path/to/app/data/-\", \"read,write,delete\";\n};\n\ngrant codeBase \"file:/path/to/app/ext/*\" {\n permission java.util.PropertyPermission \"java.io.tmpdir\", \"read\";\n permission java.io.FilePermission \"${java.io.tmpdir}/myapp/-\", \"read,write,delete\";\n};\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14663/"
] |
311,249 | <p>What are the hidden features of Maven2?</p>
| [
{
"answer_id": 311254,
"author": "Kuukage",
"author_id": 39907,
"author_profile": "https://Stackoverflow.com/users/39907",
"pm_score": 1,
"selected": false,
"text": "<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-dependency-plugin</artifactId>\n</plugin>\n"
},
{
"answer_id": 311279,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 4,
"selected": true,
"text": "<settings xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n <profile>\n <id>localcacheproxies</id>\n\n <activation>\n <activeByDefault>true</activeByDefault>\n </activation>\n\n <repositories>\n <repository>\n <id>localCacheProxy</id>\n <url>http://my-local-proxy.com/maven-proxy</url>\n </repository>\n </repositories>\n </profile>\n</profiles>\n"
},
{
"answer_id": 739361,
"author": "Brandon Yarbrough",
"author_id": 81491,
"author_profile": "https://Stackoverflow.com/users/81491",
"pm_score": 2,
"selected": false,
"text": " <build>\n <resources>\n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources>\n </build>\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39907/"
] |
311,250 | <p>Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
</code></pre>
<p>Basically I'm just setting the default value of the DropDownList to the user currently logged in.</p>
<p>Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.</p>
| [
{
"answer_id": 312196,
"author": "Dusda",
"author_id": 36411,
"author_profile": "https://Stackoverflow.com/users/36411",
"pm_score": 3,
"selected": true,
"text": "protected void FrmAdd_DataBound(object sender, EventArgs e)\n{\n // This is the same code as before, but done in the FormView's DataBound event.\n ((DropDownList)FrmAdd.Row.FindControl(\"DdlAssigned\")).SelectedValue =\n ((Guid)Membership.GetUser().ProviderUserKey).ToString();\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36411/"
] |
311,253 | <p>I have a .NET dll which needs to read it's config settings from it's config file. Usually, the config file is placed in the same directory as the DLL. But how do i read the config file if the DLL is GAC'ed, because I can put only the DLLs in the GAC, and not it's config files.</p>
| [
{
"answer_id": 311423,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 4,
"selected": false,
"text": "System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = \"THE PATH TO THE CONFIG\";\nSystem.Configuration.Configuration cfg =\nSystem.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);\n\nstring thevalue=cfg.AppSettings.Settings[variable].Value;\n"
},
{
"answer_id": 20327457,
"author": "Vinod Srivastav",
"author_id": 3057246,
"author_profile": "https://Stackoverflow.com/users/3057246",
"pm_score": 1,
"selected": false,
"text": "AppDomain.CurrentDomain.BaseDirectory var appDomain = AppDomain.CurrentDomain.BaseDirectory;\nstring sFileName = appDomain.Replace(\"\\\\bin\\\\Debug\", \"\");\nsFileName = sFileName + \"Config\\\\config.xml\";\n bin\\Debug Config config.xml sFileName \\bin\\Debug\\Config\\config.xml"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
311,268 | <p>In short: I want to monitor selected calls from an application to a DLL.</p>
<p>We have an old VB6 application for which we lost the source code (the company wasn't using source control back then..). This application uses a 3rd party DLL.</p>
<p>I want to use this DLL in a new C++ application. Unfortunately the DLL API is only partially documented, so I don't know how to call some functions. I do have the functions signature.</p>
<p>Since the VB6 application uses this DLL, I want to see how it calls several functions. So far I've tried or looked at -</p>
<ol>
<li><a href="http://www.codeproject.com/KB/DLL/apihijack.aspx" rel="noreferrer">APIHijack</a> - requires me to write C++ code for each function. Since I only need to log the values, it seems like an overkill.</li>
<li><a href="http://www.codeplex.com/easyhook" rel="noreferrer">EasyHook</a> - same as 1, but allows writing in the code in .NET language.</li>
<li><a href="http://www.ollydbg.de/" rel="noreferrer">OllyDbg</a> with <a href="http://oss.coresecurity.com/uhooker/doc/index.html" rel="noreferrer">uHooker</a> - I still have to write code for each function, this time in Python. Also, I have to do many conversions in Python using the <code>struct</code> module, since most functions pass values using pointers.</li>
</ol>
<p>Since I only need to log functions parameters I want a simple solution. Is there any automated tool, for which I could tell which functions to monitor and their signature, and then get a detailed log file?</p>
| [
{
"answer_id": 311349,
"author": "kshahar",
"author_id": 33982,
"author_profile": "https://Stackoverflow.com/users/33982",
"pm_score": 5,
"selected": true,
"text": "CustomApi.dll|void NameOfFunction(long param1, double& param2);\n NameOfFunction"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33982/"
] |
311,274 | <p>If have a set of classes that all implement an interface. </p>
<pre><code>interface IMyinterface<T>
{
int foo(T Bar);
}
</code></pre>
<p>I want to shove them all in a list and enumerate through them. </p>
<pre><code> List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
</code></pre>
<p>but the compiler wants to know what T is. Can I do this? How can I overcome this issue?</p>
| [
{
"answer_id": 311288,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": true,
"text": "interface IMyinterface { ... }\n interface IMyinterface<T> : IMyinterface { ... }\n"
},
{
"answer_id": 311333,
"author": "KeesDijk",
"author_id": 6434,
"author_profile": "https://Stackoverflow.com/users/6434",
"pm_score": 1,
"selected": false,
"text": " interface IMyinterface\n{\n int foo<T>(T Bar);\n}\n\nList<IMyinterface> list = new List<IMyinterface>();\nforeach(IMyinterface a in list){}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116/"
] |
311,276 | <p>Just could not get this one and googling did not help much either.. </p>
<p>First something that I know: Given a string and a regex, how to replace all the occurrences of strings that matches this regular expression by a replacement string ? Use the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)" rel="nofollow noreferrer">replaceAll()</a> method in the String class.</p>
<p>Now something that I am unable to do. The regex I have in my code now is [^a-zA-Z] and I know for sure that this regex is definitely going to have a range. Only some more characters might be added to the list. What I <em>need</em> as output in the code below is <strong>Worksheet+blah</strong> but what I get using replaceAll() is <strong>Worksheet++++blah</strong></p>
<blockquote>
<pre><code>String homeworkTitle = "Worksheet%#5_blah";
String unwantedCharactersRegex = "[^a-zA-Z]";
String replacementString = "+";
homeworkTitle = homeworkTitle.replaceAll(unwantedCharactersRegex,replacementString);
System.out.println(homeworkTitle);
</code></pre>
</blockquote>
<p>What is the way to achieve the output that I wish for? Are there any Java methods that I am missing here? </p>
| [
{
"answer_id": 311286,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": true,
"text": "[^a-zA-Z]+\n [^a-zA-Z]+? [^a-zA-Z]"
},
{
"answer_id": 311290,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 2,
"selected": false,
"text": "String unwantedCharactersRegex = \"[^a-zA-Z]\"\n String unwantedCharactersRegex = \"[^a-zA-Z]+\"\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27474/"
] |
311,297 | <p>I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with <em>a lot of</em> insertions which hit the same entries (like, 500k, but only 100 different ones).</p>
<p>Currently, I'm using a std::set (only insert and the iterating interface), which is decent, but still not fast enough. std::unordered_set was twice as slow, same for the Google Hash Maps. I wonder what data structure is optimized for this case?</p>
| [
{
"answer_id": 311396,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "array[hash(value)] = 1; array[hash(value)] = 0;"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39912/"
] |
311,299 | <p>I need to extract multiple text/dropdown list fields from an asp.net form and format appropriately ready for sending to recipient via email.</p>
<p>What's the best way of reading those fields without having to hard code each item such as: </p>
<pre><code>item1 = InputField1.Text;
item2 = InputField2.Text;
</code></pre>
<p>I will have about 10 or 20 items on the same input form.</p>
| [
{
"answer_id": 311312,
"author": "Chris",
"author_id": 34942,
"author_profile": "https://Stackoverflow.com/users/34942",
"pm_score": 0,
"selected": false,
"text": "foreach (string key in Request.Form.Keys) {\n string value = Request.Form[key];\n // format and use value here\n}\n Dictionary<string, object> values = new Dictionary<string, object>();\n\nforeach (string key in Request.Form.Keys) {\n if (key.Equals(\"SpecialFieldName\")) {\n // for example, parse an int\n values.Add(key, int.parse(Request.Form[key]));\n } else {\n // no special formatting required\n values.Add(key, Request.Form[key]);\n }\n}\n"
},
{
"answer_id": 311325,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": true,
"text": " foreach (string key in Request.Form.Keys)\n {\n if (key.StartsWith(\"Email.\"))\n {\n ...Process this key...\n }\n }\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26809/"
] |
311,307 | <p>Is there an alternative to history.go(-1) for FireFox and Safari. Any Help would be greatly appreciated. </p>
| [
{
"answer_id": 311311,
"author": "Anteru",
"author_id": 39912,
"author_profile": "https://Stackoverflow.com/users/39912",
"pm_score": 4,
"selected": true,
"text": "history.back()"
},
{
"answer_id": 311319,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<a href=\"javascript:history.go(-1)\">Link</a>\n <a href=\"#\" onclick=\"Javascript:goback();\">some Text</a>\n\nfunction goback() {\n history.go(-1);\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,332 | <p>I have an idea about what it is. My question is :-</p>
<p>1.) If i program my code which is amenable to Tail Call optimization(Last statement in a function[recursive function] being a function call only, no other operation there) then do i need to set any optimization level so that compiler does TCO. In what mode of optimization will compiler perform TCO, optimizer for space or time.</p>
<p>2.) How do i find out which all compilers (MSVC, gcc, ARM-RVCT) does support TCO</p>
<p>3.) Assuming some compiler does TCO, we enable it then, What is the way to find out that the compielr has actually done TCO? Will Code size, tell it or Cycles taken to execute it will tell that or both?</p>
<p>-AD</p>
| [
{
"answer_id": 311340,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "-foptimize-sibling-calls gcc -S"
},
{
"answer_id": 313057,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 0,
"selected": false,
"text": " /* FibTail.c 0.00 UTF-8 dh:2008-11-23\n * --|----1----|----2----|----3----|----4----|----5----|----6----|----*\n *\n * Demonstrate Fibonacci computation by tail call to see whether it is \n * is eliminated through compiler optimization.\n */\n\n #include <stdio.h>\n\n\n long double fibcycle(long double f0, long double f1, unsigned i)\n { /* accumulate successive fib(n-i) values by tail calls */\n\n if (i == 0) return f1;\n return fibcycle(f1, f0+f1, --i);\n }\n\n\n long double fib(unsigned n)\n { /* the basic fib(n) setup and return. */\n return fibcycle(1.0, 0.0, n);\n }\n\n int main(int argc, char* argv[ ])\n { /* compute some fibs until something breaks */\n\n int i;\n\n printf(\"\\n i fib(i)\\n\\n\");\n\n for (i = 1; i > 0; i+=i)\n { /* Do for powers of 2 until i flips negative \n or stack overflow, whichever comes first */\n printf(\"%12d %30.20LG \\n\", i, fib((unsigned) i) );\n }\n\n\n printf(\"\\n\\n\");\n return 0;\n }\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
311,346 | <p>Is there any reason to start a GUI program (application for Windows) written in VB.NET in the Sub Main of a module rather than directly in a form?</p>
<p>EDIT: The program won't take any command line parameters and it will be executed as a GUI program always.</p>
| [
{
"answer_id": 311352,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 2,
"selected": false,
"text": "Sub Main()\n If App.StartMode = vbSModeAutomation Then\n ...\n Else\n ...\n End If\nEnd Sub\n Sub Main()\n If App.PrevInstance Then End\n If InStr(Command, \"/s\") > 0 Then\n Form1.Show\n ElseIf InStr(Command, \"/p\") > 0 Then\n LoadPicture (\"c:\\windows\\Zapotec.bmp\")\n End If\nEnd Sub\n"
},
{
"answer_id": 311404,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 5,
"selected": true,
"text": "AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyExceptionFilter\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38561/"
] |
311,363 | <p>NDoc has an XML element <strong>inheritdoc</strong> which allows you to inherit documentation of a member from the parent class (or an implemented interface). However, Visual Studio (i.e. the C# compiler) does not understand this tag and complains about the documentation not being present or complete. So does StyleCop and some other tools. Is there an alternative approach? How do you go about keeping the docs complete, yet without duplicating the XML descriptions?</p>
| [
{
"answer_id": 1080418,
"author": "Alex Yakunin",
"author_id": 106042,
"author_profile": "https://Stackoverflow.com/users/106042",
"pm_score": 5,
"selected": false,
"text": "<see cref=\"Instance\" /> <CurrentType> <inheritdoc />, <inherited /> <see cref=\"...\" copy=\"...\" /> <see/> <inheritdoc> .xml <see ... copy=\"true\" /> <inheritdoc>"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] |
311,389 | <p>I've created a login submit form in HTML but for some reason autocompletion does not work in firefox.</p>
<p>This is what happens in Firefox:
- I give username and password and click on the login button
- Firefox prompts me if I would like to remember the password. I press 'remember' and login works.
- I log out and return to the login page. I would expect the username and password field to be prefilled but that is not the case. Notice that I don't (want to) use cookies.</p>
<p>Here's the code for this page:</p>
<pre><code><form name="login_form" id="login_form" autocomplete="ON" onsubmit="javascript:xajax_action_login(document.getElementById('user_name').value, document.getElementById('password').value); return false;">
<div class="login_line">
<div class="login_line_left">name</div>
<div id="user_name_id" class="login_line_right"><input size="16" maxlength="16" name="user_name" id="user_name" type="text"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left">password</div>
<div id="password_id" class="login_line_right"><input size="16" maxlength="16" name="password" id="password" type="password"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left">&nbsp;</div>
<div class="login_line_right"><input class="button" value="login" type="submit"></div>
</div> <!-- login_line -->
</form> <!-- login_form -->
</code></pre>
<p>What is wrong with my code? How can I get autocompletion to work in FF with my code?</p>
<p>Autocompletion does work correct with for instance gmail. Each time I visit the login page of gmail, the email and password fields are correctly prefilled. I don't use the 'remember me on this computer' checkbox so no cookies are used.</p>
<p><strong>Update</strong> I'm using php and FF3</p>
<p>Thanks,
Jasper </p>
| [
{
"answer_id": 342520,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 0,
"selected": false,
"text": "onsubmit=\"\" onsubmit=\"\""
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,399 | <p>Does anyone know where I can find an example of how to determine if the Maximize and/or Minimize buttons on a window are available and/or disabled?</p>
<p>The window will not be in the same process as my application. I have the hWnd and I have tried using GetMenuItemInfo, but I can't find any good samples for how to do this.</p>
<p>Thanks!</p>
| [
{
"answer_id": 311409,
"author": "Asher",
"author_id": 38265,
"author_profile": "https://Stackoverflow.com/users/38265",
"pm_score": 0,
"selected": false,
"text": "WINDOWINFO.dwStyle & WS_MAXIMIZEBOX != 0\n"
},
{
"answer_id": 311410,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "typedef struct {\n DWORD cbSize;\n RECT rcTitleBar;\n DWORD rgstate[CCHILDREN_TITLEBAR+1];\n} TITLEBARINFO, *PTITLEBARINFO, *LPTITLEBARINFO;\n rgstate Index Title Bar Element\n----- --------------------\n0 The title bar itself\n1 Reserved.\n2 Minimize button\n3 Maximize button <--------------\n4 Help button\n5 Close button\n Value Meaning\n----- -------------------------------------------\nSTATE_SYSTEM_FOCUSABLE The element can accept the focus.\nSTATE_SYSTEM_INVISIBLE The element is invisible.\nSTATE_SYSTEM_OFFSCREEN The element has no visible representation.\nSTATE_SYSTEM_UNAVAILABLE The element is unavailable. \nSTATE_SYSTEM_PRESSED The element is in the pressed state.rgstate\n"
},
{
"answer_id": 311420,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 4,
"selected": true,
"text": "bool has_maximize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MAXIMIZEBOX) != 0;\nbool has_minimize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MINIMIZEBOX) != 0;\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39171/"
] |
311,408 | <p>I'm using hibernate 3 and want to stop it from dumping all the startup messages to the console. I tried commenting out the stdout lines in log4j.properties but no luck. I've pasted my log file below. Also I'm using eclipse with the standard project structure and have a copy of log4j.properties in both the root of the project folder and the bin folder.</p>
<pre>### direct log messages to stdout ###
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.out
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=hibernate.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trac5</pre>
| [
{
"answer_id": 311445,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 7,
"selected": true,
"text": "info info warn error fatal debug log4j.logger.org.hibernate=info\n <logger name=\"org.hibernate\">\n <level value=\"info\"/> \n</logger>\n"
},
{
"answer_id": 325747,
"author": "rresino",
"author_id": 41589,
"author_profile": "https://Stackoverflow.com/users/41589",
"pm_score": 4,
"selected": false,
"text": "hibernate.show_sql\nhibernate.generate_statistics\nhibernate.use_sql_comments\n org.hibernate"
},
{
"answer_id": 3073023,
"author": "user370677",
"author_id": 370677,
"author_profile": "https://Stackoverflow.com/users/370677",
"pm_score": 1,
"selected": false,
"text": "log4j.rootLogger=debug, stdout, R\n log4j.rootLogger=info, stdout, R \n"
},
{
"answer_id": 10537807,
"author": "Liqun Chen",
"author_id": 1387605,
"author_profile": "https://Stackoverflow.com/users/1387605",
"pm_score": 3,
"selected": false,
"text": " <dependency>\n <groupId>log4j</groupId>\n <artifactId>log4j</artifactId>\n <version>1.2.16</version>\n </dependency>\n\n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-log4j12</artifactId>\n <version>1.6.4</version>\n </dependency>\n"
},
{
"answer_id": 16357416,
"author": "Systfile",
"author_id": 2346585,
"author_profile": "https://Stackoverflow.com/users/2346585",
"pm_score": 3,
"selected": false,
"text": "Hibernate:select HibernateJpaVendorAdapter <bean id=\"jpaVendorAdapter\"\n class=\"org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter\">\n <property name=\"showSql\" value=\"false\"/>\n</bean> \n"
},
{
"answer_id": 18323888,
"author": "acdcjunior",
"author_id": 1850609,
"author_profile": "https://Stackoverflow.com/users/1850609",
"pm_score": 5,
"selected": false,
"text": "java.util.logging.Logger.getLogger(\"org.hibernate\").setLevel(Level.OFF);\n Level.OFF java.util.logging.Logger.getLogger(\"org.hibernate\").setLevel(Level.SEVERE);\n java.util.logging.Level"
},
{
"answer_id": 22977693,
"author": "user1050755",
"author_id": 1050755,
"author_profile": "https://Stackoverflow.com/users/1050755",
"pm_score": 7,
"selected": false,
"text": "hibernate.show_sql\n"
},
{
"answer_id": 25768383,
"author": "Matej Vargovčík",
"author_id": 4003774,
"author_profile": "https://Stackoverflow.com/users/4003774",
"pm_score": 3,
"selected": false,
"text": "public static void main(String[] args) {\n //magical - do not touch\n @SuppressWarnings(\"unused\")\n org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger(\"org.hibernate\");\n java.util.logging.Logger.getLogger(\"org.hibernate\").setLevel(java.util.logging.Level.WARNING); //or whatever level you need\n\n ...\n}\n"
},
{
"answer_id": 34217576,
"author": "Ramesh Gowtham",
"author_id": 4045353,
"author_profile": "https://Stackoverflow.com/users/4045353",
"pm_score": 0,
"selected": false,
"text": "ch.qos.logback.classic.LoggerContext.LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.LoggerFactory.getILoggerFactory();\n\nloggerContext.stop();\n"
},
{
"answer_id": 51880681,
"author": "Christian Hoffmann",
"author_id": 7200161,
"author_profile": "https://Stackoverflow.com/users/7200161",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <logger name=\"org.hibernate\" level=\"WARN\"/>\n</configuration>\n"
},
{
"answer_id": 59686150,
"author": "Chris Meyer",
"author_id": 12690757,
"author_profile": "https://Stackoverflow.com/users/12690757",
"pm_score": 1,
"selected": false,
"text": " <!-- Log everything in hibernate -->\n <Logger name=\"org.hibernate\" level=\"info\" additivity=\"false\">\n <AppenderRef ref=\"Console\" />\n </Logger>\n\n <!-- Log SQL statements -->\n <Logger name=\"org.hibernate.SQL\" level=\"debug\" additivity=\"false\">\n <AppenderRef ref=\"Console\" />\n <AppenderRef ref=\"File\" />\n </Logger>\n\n <!-- Log JDBC bind parameters -->\n <Logger name=\"org.hibernate.type.descriptor.sql\" level=\"trace\" additivity=\"false\">\n <AppenderRef ref=\"Console\" />\n <AppenderRef ref=\"File\" />\n </Logger>\n show-sql:true"
},
{
"answer_id": 59710263,
"author": "Philippe",
"author_id": 5606736,
"author_profile": "https://Stackoverflow.com/users/5606736",
"pm_score": 1,
"selected": false,
"text": "log4j.logger.org.hibernate.orm.deprecation=error\n\nlog4j.logger.org.hibernate=error\n # Root logger option\n#Level/rules TRACE < DEBUG < INFO < WARN < ERROR < FATAL.\n#FATAL: shows messages at a FATAL level only\n#ERROR: Shows messages classified as ERROR and FATAL\n#WARNING: Shows messages classified as WARNING, ERROR, and FATAL\n#INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL\n#DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL\n#TRACE : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL\n#ALL : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL\n#OFF : No log messages display\n\n\nlog4j.rootLogger=INFO, file, console\n\nlog4j.logger.main=DEBUG\nlog4j.logger.org.hibernate.orm.deprecation=error\nlog4j.logger.org.hibernate=error\n\n#######################################\n# Direct log messages to a log file\nlog4j.appender.file.Threshold=ALL\nlog4j.appender.file.file=logs/MyProgram.log\nlog4j.appender.file.layout=org.apache.log4j.PatternLayout\nlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} - %m%n\n\n# set file size limit\nlog4j.appender.file=org.apache.log4j.RollingFileAppender\nlog4j.appender.file.MaxFileSize=5MB\nlog4j.appender.file.MaxBackupIndex=50\n\n\n#############################################\n# Direct log messages to System Out\nlog4j.appender.console.Threshold=INFO\nlog4j.appender.console.Target=System.out\nlog4j.appender.console=org.apache.log4j.ConsoleAppender\nlog4j.appender.console.layout=org.apache.log4j.PatternLayout\nlog4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1} - %m%n\n"
},
{
"answer_id": 67530992,
"author": "Pramod H G",
"author_id": 7895005,
"author_profile": "https://Stackoverflow.com/users/7895005",
"pm_score": 2,
"selected": false,
"text": "application.properties spring.jpa.show-sql=false\n"
},
{
"answer_id": 68822958,
"author": "Ronald Coarite",
"author_id": 2154661,
"author_profile": "https://Stackoverflow.com/users/2154661",
"pm_score": 0,
"selected": false,
"text": " <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-entitymanager</artifactId>\n <version>5.5.6.Final</version>\n </dependency>\n"
},
{
"answer_id": 72873906,
"author": "Clement Cherlin",
"author_id": 4455546,
"author_profile": "https://Stackoverflow.com/users/4455546",
"pm_score": 1,
"selected": false,
"text": "@DataJpaTest @DataJpaTest\npublic class MyTestClass {\n ...\n}\n @DataJpaTest(showSql = false)\npublic class MyTestClass {\n ...\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
] |
311,432 | <p>With generics, is there ever a reason to create specific derived EventArg classes</p>
<p>It seems like now you can simply use them on the fly with a generic implementation.</p>
<p>Should i go thorugh all of my examples and remove my eventArg classes (StringEventArgs, MyFooEventArgs, etc . .)</p>
<pre><code>public class EventArgs<T> : EventArgs
{
public EventArgs(T value)
{
m_value = value;
}
private T m_value;
public T Value
{
get { return m_value; }
}
}
</code></pre>
| [
{
"answer_id": 311442,
"author": "Jonas Oberschweiber",
"author_id": 1522,
"author_profile": "https://Stackoverflow.com/users/1522",
"pm_score": 0,
"selected": false,
"text": "EventArgs<T> EventArgs EventArgs<T>"
},
{
"answer_id": 311519,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 2,
"selected": false,
"text": "public class City {...}\n\npublic delegate void FireNuclearMissile(object sender, EventArgs<City> args);\npublic event FireNuclearMissile FireNuclearMissileEvent;\n\npublic delegate void QueryPopulation(object sender, EventArgs<City> args);\npublic event QueryPopulation QueryPopulationEvent;\n class City {...}\n\npublic class FireNuclearMissileEventArgs : EventArgs\n{\n public FireNuclearMissileEventArgs(City city)\n {\n this.city = city;\n }\n\n private City city;\n\n public City City\n {\n get { return this.city; }\n }\n}\n\npublic delegate void FireNuclearMissile(object sender, FireNuclearMissileEventArgs args);\npublic event FireNuclearMissile FireNuclearMissileEvent;\n\npublic class QueryPopulationEventArgs : EventArgs\n{\n public QueryPopulationEventArgs(City city)\n {\n this.city = city;\n }\n\n private City city;\n\n public City City\n {\n get { return this.city; }\n }\n}\n\npublic delegate void QueryPopulation(object sender, QueryPopulationEventArgs args);\npublic event QueryPopulation QueryPopulationEvent;\n"
},
{
"answer_id": 311614,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 6,
"selected": true,
"text": "EventArgs EventArgs public event EventHandler<EventArgs<double, double, double>> Divided;\n private void OnDivided(object sender, EventArgs<double, double, double> e)\n{\n // I have to just \"know\" this - it is a convention\n\n var numerator = e.Value1;\n var denominator = e.Value2;\n var result = e.Value3;\n}\n EventArgs private void OnDivided(object sender, DividedEventArgs e)\n{\n var numerator = e.Numerator;\n var denominator = e.Denominator;\n var result = e.Result;\n}\n EventArgs"
},
{
"answer_id": 18002323,
"author": "Jimmy",
"author_id": 68936,
"author_profile": "https://Stackoverflow.com/users/68936",
"pm_score": 1,
"selected": false,
"text": "public static class TupleEventArgs\n{\n static public TupleEventArgs<T1> Create<T1>(T1 item1)\n {\n return new TupleEventArgs<T1>(item1);\n }\n\n static public TupleEventArgs<T1, T2> Create<T1, T2>(T1 item1, T2 item2)\n {\n return new TupleEventArgs<T1, T2>(item1, item2);\n }\n\n static public TupleEventArgs<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)\n {\n return new TupleEventArgs<T1, T2, T3>(item1, item2, item3);\n }\n}\n\npublic class TupleEventArgs<T1> : EventArgs\n{\n public T1 Item1;\n\n public TupleEventArgs(T1 item1)\n {\n Item1 = item1;\n }\n}\n\npublic class TupleEventArgs<T1, T2> : EventArgs\n{\n public T1 Item1;\n public T2 Item2;\n\n public TupleEventArgs(T1 item1, T2 item2)\n {\n Item1 = item1;\n Item2 = item2;\n }\n}\n\npublic class TupleEventArgs<T1, T2, T3> : EventArgs\n{\n public T1 Item1;\n public T2 Item2;\n public T3 Item3;\n\n public TupleEventArgs(T1 item1, T2 item2, T3 item3)\n {\n Item1 = item1;\n Item2 = item2;\n Item3 = item3;\n }\n}\n public event EventHandler<TupleEventArgs<string,string,string>> NewEvent;\n\nNewEvent.Raise(this, TupleEventArgs.Create(\"1\", \"2\", \"3\"));\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
311,438 | <p>I have a simple web app, with a few jsp pages, servlets and pojo's. I want to initialise the connection pool before any requests are made. What is the best way to do this? Can it be done when the app is first deployed or do you have to wait till the first request comes in?</p>
| [
{
"answer_id": 311482,
"author": "Yoni",
"author_id": 36071,
"author_profile": "https://Stackoverflow.com/users/36071",
"pm_score": 3,
"selected": false,
"text": "<listener>\n <listener-class>\n com...ApplicationListener\n </listener-class>\n</listener>\n public class ApplicationListener implements ServletContextListener {\n\n private ServletContext sc = null;\n\n private Logger log = Logger\n .getLogger(ApplicationListener.class);\n\n public void contextInitialized(ServletContextEvent arg0) {\n this.sc = arg0.getServletContext();\n try {\n // initialization code\n } catch (Exception e) {\n log.error(\"oops\", e);\n }\n log.info(\"webapp started\");\n }\n\n public void contextDestroyed(ServletContextEvent arg0) {\n try {\n // shutdown code\n } catch (Exception e) {\n log.error(\"oops\", e);\n }\n this.sc = null;\n log.info(\"webapp stopped\");\n }\n\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16684/"
] |
311,439 | <p>I am making a Color class, and provide a standard constructor like</p>
<pre><code>Color(int red, int green, int blue)
</code></pre>
<p>And then I want to provide an easy way to get the most common colors, like
Color.Blue, Color.Red. I see two possible options:</p>
<pre><code>public static readonly Color Red = new Color(255, 0, 0);
public static Color Red { get { return new Color(255, 0, 0); } }
</code></pre>
<p>What I don't fully understand is if there is an advantage of one over the other, and how exactly the static keyword works. My thoughts are: The first creates one instance, and then that instance stays in memory for the entire duration of the program, and every time Red is called, this instance is used. The latter only creates something when first used, but creates a new instance every time. If this is correct, then I would argue that if I supply a lot of predefined colors, then the first would use a lot of unnecessary memory? So it is memory usage vs the runtime overhead of instantiating an object every time I guess. </p>
<p>Is my reasoning correct? Any advice for best practices when designing classes and use of the static keyword would be great.</p>
| [
{
"answer_id": 311470,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 1,
"selected": false,
"text": "Application.Current"
},
{
"answer_id": 311489,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 0,
"selected": false,
"text": "public static readonly Color RED = new Color(255, 0, 0);\n private static readonly Color RED = new Color(255, 0, 0);\n // RED is created once when it is invoked for the first time.\n\npublic static Color Red { \n get { \n return RED; \n // Will return a created RED object or create one \n // for the first time.\n } \n}\n"
},
{
"answer_id": 311499,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 4,
"selected": true,
"text": "Color Color static static Color Color int Color class struct class Heavy{\n static Heavy first;\n static Heavy second;\n\n public static Heavy First{\n get{\n if(first == null)\n first = new Heavy();\n return first;\n }\n }\n public static Heavy Second{\n get{\n if(second == null)\n second = new Heavy();\n return second;\n }\n }\n}\n Color Color Color.Red.G = 255;\n for(int y = 0; y < bmp.Height; y++)\nfor(int x = 0; x < bmp.Width; x++)\n if(bmp.GetPixel(x, y) == Color.Red))\n MessageBox.Show(\"Found a red pixel!\");\n Color Color new"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364245/"
] |
311,454 | <p>How would you format/indent this piece of code?</p>
<pre><code>int ID = Blahs.Add( new Blah( -1, -2, -3) );
</code></pre>
<p>or</p>
<pre><code>int ID = Blahs.Add( new Blah(
1,2,3,55
)
);
</code></pre>
<hr />
<h3>Edit:</h3>
<p>My class has lots of parameters actually, so that might effect your response.</p>
| [
{
"answer_id": 311459,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 2,
"selected": false,
"text": "int ID = Blahs.Add( \n new Blah( 1, 2, 3, 55 ) \n );\n"
},
{
"answer_id": 311468,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": "Blah blah = new Blah(1,2,3,55);\nint ID = Blahs.Add( blah );\n"
},
{
"answer_id": 311492,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "int ID = Blahs.Add\n( \n new Blah\n (\n 1, /* When the answer is within this percentage, accept it. */ \n 2, /* Initial seed for algorithm */ \n 3, /* Maximum threads for calculation */ \n 55 /* Limit on number of hours, a thread may iterate */ \n ) \n);\n"
},
{
"answer_id": 311505,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "int result = Blahs.Add( new Blah(1, 2, 3, 55) );\n Blah int ID = Blahs.Add( new Blah(\n 1, /* wtf is this */ \n 2, /* wtf is this */\n 3, /* wtf is this */\n 55 /* and huh */\n));\n"
},
{
"answer_id": 311508,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 2,
"selected": false,
"text": "int id = BLahs.Add(new Blah(-1, -2, -3));\n"
},
{
"answer_id": 311517,
"author": "Foredecker",
"author_id": 18256,
"author_profile": "https://Stackoverflow.com/users/18256",
"pm_score": 4,
"selected": false,
"text": "Blah aBlah = new Blah( 1, 2, 3, 55 );\nint ID = Blahas.Add( aBlah );\n"
},
{
"answer_id": 311521,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "new_Blah = new Blah(-1, -2, -3)\nint ID = BLahs.Add(new_Blah);\n int ID = BLahs.Add(\n new Blah(-1, -2, -3)\n);\n int ID = BLahs.Add(new Blah(\n (-1 * 24) + 9,\n -2,\n -3\n));\n myArray.append(\n someFunction(-1, -2, -3)\n)\n\nmyArray.append(someFunction(\n otherFunction(\"An Arg\"),\n (x**2) + 4,\n something = True\n))\n"
},
{
"answer_id": 311573,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Blah aBlah = new Blah( 1, 2, 3, 55 );\nint ID = Blahas.Add( aBlah );\n"
},
{
"answer_id": 311638,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 0,
"selected": false,
"text": "new Blah Blah int ID = BLahs.Add(new Blah( foo => -1, bar => -2, baz => -3 ));\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,460 | <p>I'm trying to read data from a.csv file to ouput it on a webpage as text.</p>
<p>It's the first time I'm doing this and I've run into a nasty little problem.</p>
<p>My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.</p>
<p>like this:</p>
<pre><code>$contents = file_get_contents("files/data.csv");
</code></pre>
<p>In this example file I made, there are 2 lines.</p>
<blockquote>
<p>Paul Blueberryroad
85 us Flashlight,Bag November 20,
2008, 4:39 pm</p>
<p>Hellen Blueberryroad
85 us lens13mm,Flashlight,Bag,ExtraBatteries November
20, 2008, 16:41:32</p>
</blockquote>
<p>But the string read by PHP is this:</p>
<p>Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32</p>
<p>I'm splitting this with:</p>
<pre><code>list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);
</code></pre>
<p>What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns.</p>
<p>Instead I get only Paul and the content of $orderdate[] is</p>
<blockquote>
<p>November 20, 2008, 4:39 pmHellen</p>
</blockquote>
<p>So all the rows are concatenated. Can someone show me how i can achieve what I need?</p>
<p>EDIT: solution found, just one werid thing remaining:</p>
<p>I've solved it now by using this piece of code:</p>
<pre><code>$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
</code></pre>
<p>For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.</p>
| [
{
"answer_id": 311467,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 1,
"selected": false,
"text": "$rows = array();\n$name = array();\n$street = array();\n$country = array();\n\n$rows = file(\"file.csv\");\nforeach($rows as $r) {\n $data = explode(\";\", $r);\n $name[] = $data[0];\n $street[] = $data[1];\n $country[] = $data[2];\n}\n"
},
{
"answer_id": 311486,
"author": "Vordreller",
"author_id": 11795,
"author_profile": "https://Stackoverflow.com/users/11795",
"pm_score": 1,
"selected": false,
"text": "$fo = fopen(\"files/users.csv\", \"rb+\");\nwhile(!feof($fo)) {\n $contents[] = fgetcsv($fo,0,';');\n}\nfclose($fo);\n"
},
{
"answer_id": 311512,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 0,
"selected": false,
"text": "$f = fopen ('test.csv', 'r');\nwhile (false !== $data = fgetcsv($f, 0, ';'))\n $arr[] = $data;\nfclose($f);\n function str_split_csv($text, $seperator = ';') {\n $regex = '#' . preg_quote($seperator) . '|\\v#';\n preg_match('|^.*$|m', $text, $firstline);\n $chunks = substr_count($firstline[0], $seperator) + 1;\n $split = array_chunk(preg_split($regex, $text), $chunks);\n $c = count($split) - 1;\n if (isset($split[$c]) && ((count($split[$c]) < $chunks) || (($chunks == 1) && ($split[$c][0] == ''))))\n unset($split[$c]);\n return $split;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
311,463 | <p>I can follow most of Apple's WiTap sample, but am sort of stumped on this bit in the send method:</p>
<pre><code>- (void) send:(const uint8_t)message
{
if (_outStream && [_outStream hasSpaceAvailable])
if([_outStream write:(const uint8_t *)&message maxLength:sizeof(const uint8_t)] == -1)
[self _showAlert:@"Failed sending data to peer"];
}
- (void) activateView:(TapView*)view
{
NSLog(@"ACTIVATE TAG: %d", [view tag]);
//[self send:[view tag] | 0x80];
[self send:[view tag]];
}
- (void) deactivateView:(TapView*)view
{
NSLog(@"DEACTIVATE TAG: %d", [view tag]);
//[self send:[view tag] & 0x7f];
[self send:[view tag]];
}
</code></pre>
<p>Note that I have changed the send: argument to just the tag of the views, which are numbered 1-9. Originally the code had the bitwise AND and OR adjustments.</p>
<p>WHY?</p>
<p>I get the fact that the send method needs a <code>uint8_t</code>, but is that why the bitwise stuff is there? To turn a NSInteger into a unint8_t?</p>
<p>The code doesn't work with my changes above. It will log fine and visually the client will function correctly, but the messages aren't being sent/received correctly from client to client.</p>
<p>Can someone explain in small words what the bitwise stuff is doing? Or am I correct?</p>
<p>Thanks! This is my first question to SO so please be kind. </p>
<hr>
<p>thanks for the response. I am still puzzled a bit. Get it?</p>
<p>Basically, why?</p>
<p>Is this just a geeky way of passing an identifier? Each of those views have a tag #, why not just pass that, and toggle the state (up/down) from the view class?</p>
<p>Is this just a case of "this is how the person who wrote it did it", or am I missing a crucial piece of the puzzle in that this is how I should also be structuring my code.</p>
<p>I would just want to pass a tag # and then have that tag decide what to do in a clearly readable function like <code>toggleUpOrDownState</code> or something.</p>
<p>This bitwise stuff always makes me feel stupid I guess, unless it is necessary, etc. Then I feel stupid but manage to muddle through somehow anyway. : )</p>
| [
{
"answer_id": 311487,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 3,
"selected": true,
"text": "[view tag] | 0x80 [view tag] & 0x7f [AppController stream:handleEvent:] //We received a remote tap update, forward it to the appropriate view\n if(b & 0x80)\n [(TapView*)[_window viewWithTag:b & 0x7f] touchDown:YES];\n else\n [(TapView*)[_window viewWithTag:b] touchUp:YES];\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39932/"
] |
311,479 | <p>Is there a less resource intensive / faster way of performing this query (which is partly based upon: <a href="https://stackoverflow.com/questions/311390/mysql-a-search-a-select-of-multiple-rows-joining-and-all-in-one-query">This StackOverflow question</a> ). Currently it takes 0.008 seconds searching through only a dozen or so rows per table.</p>
<pre><code>SELECT DISTINCT *
FROM (
(
SELECT DISTINCT ta.auto_id, li.address, li.title, GROUP_CONCAT( ta.tag ) , li.description, li.keyword, li.rating, li.timestamp
FROM tags AS ta
INNER JOIN links AS li ON ta.auto_id = li.auto_id
WHERE ta.user_id =1
AND (
ta.tag LIKE '%query%'
)
OR (
li.keyword LIKE '%query%'
)
GROUP BY li.auto_id
)
UNION DISTINCT (
SELECT DISTINCT auto_id, address, title, '', description, keyword, rating, `timestamp`
FROM links
WHERE user_id =1
AND (
keyword LIKE '%query%'
)
)
) AS total
GROUP BY total.auto_id
</code></pre>
<p>Thank you very much,</p>
<p>Ice</p>
| [
{
"answer_id": 311506,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "SELECT DISTINCT *\nFROM (\n (SELECT ta.auto_id, li.address, li.title, GROUP_CONCAT( ta.tag ),\n li.description, li.keyword, li.rating, li.timestamp\n FROM (SELECT auto_id, tag FROM tags WHERE user_id = 1) AS ta\n INNER JOIN links AS li ON ta.auto_id = li.auto_id\n WHERE (ta.tag LIKE '%query%') OR (li.keyword LIKE '%query%')\n GROUP BY li.auto_id\n )\n UNION (\n SELECT auto_id, address, title, '', description, keyword, rating, `timestamp`\n FROM links\n WHERE user_id = 1 AND (keyword LIKE '%query%')\n )\n) AS total\nGROUP BY total.auto_id\n"
},
{
"answer_id": 311594,
"author": "Martin",
"author_id": 37367,
"author_profile": "https://Stackoverflow.com/users/37367",
"pm_score": 0,
"selected": false,
"text": "select li.auto_id, \n address, \n title, \n group_concat(ta.tag), \n description, \n keyword, \n rating, \n timestamp \nfrom links li \nleft join tags ta ON ta.auto_id = li.auto_id \nwhere li.user_id = 1 and ( keyword like '%query%' or ta.tag like '%query%' ) \ngroup by li.auto_id;\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,501 | <p>If tan(x) = y and atan(y) = x why Math.Atan(Math.Tan(x)) != x?</p>
<p>I´m trying to calculate x in something like: </p>
<pre><code>tan(2/x +3) = 5
</code></pre>
<p>so </p>
<pre><code>atan(tan(2/x + 3) = atan(5)
</code></pre>
<p>and so on... but I´ve tried this: </p>
<pre><code>double d = Math.Atan(Math.Tan(10));
</code></pre>
<p>and d != 10. Why?</p>
| [
{
"answer_id": 311513,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 5,
"selected": false,
"text": "math.tan(math.atan(x)) == x abs(number1 - number2) < epsilon // ==\nabs(number1 - number2) >= epsilon // !=\n"
},
{
"answer_id": 1940967,
"author": "Regent",
"author_id": 107718,
"author_profile": "https://Stackoverflow.com/users/107718",
"pm_score": 1,
"selected": false,
"text": "double normalizedAngle = (angle + Math.PI / 2) % Math.PI - Math.PI / 2;\n Double.Epsilon Math.Atan(Math.Tan(-0.49999632679501449)) + 0.49999632679501449 Double.Epsilon 1.1235582092889474E+307"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.