qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
287,474
<p>What is the difference between <code>HAVING</code> and <code>WHERE</code> in an <code>SQL SELECT</code> statement?</p> <p>EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link:</p> <blockquote> <p>When <code>GROUP BY</code> is not used, <code>HAVING</code> behaves like a <code>WHERE</code> clause</p> </blockquote> <p>The situation I had seen the <code>WHERE</code> in did not have <code>GROUP BY</code> and is where my confusion started. Of course, until you know this you can't specify it in the question.</p>
[ { "answer_id": 287475, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "HAVING GROUP BY SELECT edc_country, COUNT(*)\nFROM Ed_Centers\nGROUP BY edc_country\nHAVING COUNT(*) > 1\nORDER BY edc_country;\n" }, { "answer_id": 287480, "author": "Kaiser Advisor", "author_id": 32462, "author_profile": "https://Stackoverflow.com/users/32462", "pm_score": 5, "selected": false, "text": "SELECT column_name, aggregate_function(column_name)\nFROM table_name\nWHERE column_name operator value\nGROUP BY column_name\nHAVING aggregate_function(column_name) operator value\n SELECT column_name, COUNT( column_name ) AS column_name_tally\n FROM table_name\n WHERE column_name < 3\n GROUP \n BY column_name\nHAVING COUNT( column_name ) >= 3;\n HAVING SELECT column_name, column_name_tally\n FROM (\n SELECT column_name, COUNT(column_name) AS column_name_tally\n FROM table_name\n WHERE column_name < 3\n GROUP \n BY column_name\n ) pointless_range_variable_required_here\n WHERE column_name_tally >= 3;\n" }, { "answer_id": 287496, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 9, "selected": false, "text": "select City, CNT=Count(1)\nFrom Address\nWhere State = 'MA'\nGroup By City\n select City, CNT=Count(1)\nFrom Address\nWhere State = 'MA'\nGroup By City\nHaving Count(1)>5\n" }, { "answer_id": 5249204, "author": "Simmoniz", "author_id": 651987, "author_profile": "https://Stackoverflow.com/users/651987", "pm_score": 1, "selected": false, "text": "WHERE HAVING WHERE my_indexed_row = 123 HAVING my_indexed_row = 123" }, { "answer_id": 8294326, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 5, "selected": false, "text": "HAVING WHERE DUAL ON WHERE HAVING WHERE HAVING GROUP BY HAVING SELECT HAVING name T SELECT 1 AS result\n FROM T\nHAVING COUNT( DISTINCT name ) = COUNT( name );\n HAVING 1" }, { "answer_id": 10912397, "author": "Nayan", "author_id": 997566, "author_profile": "https://Stackoverflow.com/users/997566", "pm_score": 0, "selected": false, "text": "userid sum(dailyincome) sum(dailyincome)>100" }, { "answer_id": 36061054, "author": "Achilles Ram Nakirekanti", "author_id": 3052383, "author_profile": "https://Stackoverflow.com/users/3052383", "pm_score": 3, "selected": false, "text": "SELECT name \nFROM bonus \nGROUP BY name \nWHERE sum(salary) > 200 \n SELECT name \nFROM bonus \nGROUP BY name \nHAVING sum(salary) > 200 \n" }, { "answer_id": 39821196, "author": "bebosh", "author_id": 2519297, "author_profile": "https://Stackoverflow.com/users/2519297", "pm_score": 1, "selected": false, "text": "GROUP BY WHERE HAVING GROUP BY WHERE HAVING" }, { "answer_id": 41405701, "author": "M Asad Ali", "author_id": 6798286, "author_profile": "https://Stackoverflow.com/users/6798286", "pm_score": 2, "selected": false, "text": "WHERE HAVING WHERE HAVING WHERE HAVING HAVING WHERE HAVING" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223/" ]
287,489
<p>I have a CSS class called grid which I place on my tables. I want to Zebra strip my even rows so I use the following jQuery code</p> <pre><code>$(".grid tr:nth-child(even)").addClass("even"); </code></pre> <p>This basically says "Apply the css class even to any tr tag which has a parent (at any level) with a class of grid." The problem with this is when I have nested tables, the child table's tr tags will also get the even style. Since I did not specify the child table with a class of grid, I don't want it to pick up the zebra stripe. </p> <p>How can I specify to only apply the even class on tr tags which are a direct descendant of the tag which has the grid class? </p>
[ { "answer_id": 287499, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 4, "selected": true, "text": "$(\".grid > tr:nth-child(even)\").addClass(\"even\");\n .grid" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
287,517
<p>I've <strong>inherited</strong> a web app that I've just discovered stores over 300,000 usernames/passwords in plain text in a SQL Server database. I realize that this is a Very Bad Thing™.</p> <p>Knowing that I'll have to update the login and password update processes to encrypt/decrypt, and with the smallest impact on the rest of the system, what would you recommend as the best way to remove the plain text passwords from the database?</p> <p>Any help is appreciated.</p> <p><strong>Edit: Sorry if I was unclear, I meant to ask what would be your procedure to encrypt/hash the passwords, not specific encryption/hashing methods.</strong> </p> <p>Should I just:</p> <ol> <li>Make a backup of the DB</li> <li>Update login/update password code</li> <li>After hours, go through all records in the users table hashing the password and replacing each one</li> <li>Test to ensure users can still login/update passwords</li> </ol> <p>I guess my concern is more from the sheer number of users so I want to make sure I'm doing this correctly.</p>
[ { "answer_id": 287539, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": -1, "selected": false, "text": "ALTER TABLE users ADD COLUMN hashedPassword varbinary(max);\nALTER TABLE users ADD COLUMN salt char(10);\n--Generate random salts and update the column, after that\nUPDATE users SET hashedPassword = HashBytes('SHA1',salt + '|' + password);\n SELECT count(*) from users WHERE hashedPassword = \nHashBytes('SHA1',salt + '|' + <password>)\n" }, { "answer_id": 287883, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": false, "text": "from hashlib import sha256\nfrom hmac import HMAC\nimport random\n\ndef random_bytes(num_bytes):\n return \"\".join(chr(random.randrange(256)) for i in xrange(num_bytes))\n\ndef pbkdf_sha256(password, salt, iterations):\n result = password\n for i in xrange(iterations):\n result = HMAC(result, salt, sha256).digest() # use HMAC to apply the salt\n return result\n\nNUM_ITERATIONS = 5000\ndef hash_password(plain_password):\n salt = random_bytes(8) # 64 bits\n \n hashed_password = pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)\n\n # return the salt and hashed password, encoded in base64 and split with \",\"\n return salt.encode(\"base64\").strip() + \",\" + hashed_password.encode(\"base64\").strip()\n\ndef check_password(saved_password_entry, plain_password):\n salt, hashed_password = saved_password_entry.split(\",\")\n salt = salt.decode(\"base64\")\n hashed_password = hashed_password.decode(\"base64\")\n\n return hashed_password == pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)\n\npassword_entry = hash_password(\"mysecret\")\nprint password_entry # will print, for example: 8Y1ZO8Y1pi4=,r7Acg5iRiZ/x4QwFLhPMjASESxesoIcdJRSDkqWYfaA=\ncheck_password(password_entry, \"mysecret\") # returns True\n" }, { "answer_id": 778368, "author": "Sergio", "author_id": 94484, "author_profile": "https://Stackoverflow.com/users/94484", "pm_score": 0, "selected": false, "text": "random_bytes def random_bytes(num_bytes):\n return os.urandom(num_bytes)\n os os.urandom" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034/" ]
287,540
<p>I have an object created in a host application and can access it remotely using remoting, is there any way I can test the connection to ensure it is still "alive"? Maybe an event I can use that fires if the remoting connection gets disconnected, or some property that can tell me the state of the remoting connection. Is there something like this available?</p>
[ { "answer_id": 287567, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 4, "selected": true, "text": " public void Ping() {} \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
287,541
<p>What I'd like to do is produce an HTML/CSS/JS version of the following. The gridlines and other aspects are not important. It's more of a question how to do the background databars.</p> <p><a href="https://i.stack.imgur.com/tPLAD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tPLAD.png" alt="alt text"></a><br> <sub>(source: <a href="http://blogs.tech-recipes.com/shamanstears/files/2008/04/excel_databars2.png" rel="nofollow noreferrer">tech-recipes.com</a>)</sub> </p>
[ { "answer_id": 287617, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": true, "text": "<div style=\"background: url(bg.gif) -50px 0 no-repeat;\">5</div>\n<div style=\"background: url(bg.gif) -20px 0 no-repeat;\">8</div>\n <style type=\"text/css\">\n .cell { position: relative; }\n .cell .back { position: absolute; z-index: 1; background: url(bg.gif); }\n .cell .value { position: relative; z-index: 2; }\n</style>\n\n<div class=\"cell\">\n <div class=\"back\" style=\"width: 50%;\">&nbsp;</div>\n <div class=\"value\">5</div>\n</div>\n<div class=\"cell\">\n <div class=\"back\" style=\"width: 80%;\">&nbsp;</div>\n <div class=\"value\">8</div>\n</div>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
287,543
<p>I can't seem to find in the SDK how to programatically sense the mute button/switch on the iPhone. When my app plays background music, it responds properly to the volume button without me having any code to follow that but, when I use the mute switch, it just keeps playing away.</p> <p>How do I test the position of mute?</p> <p>(NOTE: My program has its own mute switch, but I'd like the physical switch to override that.)</p>
[ { "answer_id": 292918, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 6, "selected": true, "text": "// \"Ambient\" makes it respect the mute switch\n// Must call this once to init session\nif (!gAudioSessionInited)\n{\n AudioSessionInterruptionListener inInterruptionListener = NULL;\n OSStatus error;\n if ((error = AudioSessionInitialize (NULL, NULL, inInterruptionListener, NULL)))\n {\n NSLog(@\"*** Error *** error in AudioSessionInitialize: %d.\", error);\n }\n else\n {\n gAudioSessionInited = YES;\n }\n}\n\nSInt32 ambient = kAudioSessionCategory_AmbientSound;\nif (AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (ambient), &ambient))\n{\n NSLog(@\"*** Error *** could not set Session property to ambient.\");\n}\n" }, { "answer_id": 3397936, "author": "Martin Cowie", "author_id": 42429, "author_profile": "https://Stackoverflow.com/users/42429", "pm_score": 3, "selected": false, "text": "-(NSString*)audioRoute\n{\n CFStringRef state;\n UInt32 propertySize = sizeof(CFStringRef);\n OSStatus n = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);\n if( n )\n {\n // TODO: Throw an exception\n NSLog( @\"AudioSessionGetProperty: %@\", osString( n ) );\n }\n\n NSString *result = (NSString*)state;\n [result autorelease];\n return result;\n}\n\n-(Float32)audioVolume\n{\n Float32 state;\n UInt32 propertySize = sizeof(CFStringRef);\n OSStatus n = AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareOutputVolume, &propertySize, &state);\n if( n )\n {\n // TODO: Throw an exception\n NSLog( @\"AudioSessionGetProperty: %@\", osString( n ) );\n }\n return state;\n}\n" }, { "answer_id": 3418147, "author": "Haemish Graham", "author_id": 412297, "author_profile": "https://Stackoverflow.com/users/412297", "pm_score": 3, "selected": false, "text": "-(BOOL)isDeviceMuted\n{\n CFStringRef state;\n UInt32 propertySize = sizeof(CFStringRef);\n AudioSessionInitialize(NULL, NULL, NULL, NULL);\n AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);\n return (CFStringGetLength(state) > 0 ? NO : YES);\n}\n" }, { "answer_id": 4706649, "author": "Chris Ladd", "author_id": 388588, "author_profile": "https://Stackoverflow.com/users/388588", "pm_score": 4, "selected": false, "text": " -(BOOL)silenced {\n #if TARGET_IPHONE_SIMULATOR\n // return NO in simulator. Code causes crashes for some reason.\n return NO;\n #endif\n\n CFStringRef state;\n UInt32 propertySize = sizeof(CFStringRef);\n AudioSessionInitialize(NULL, NULL, NULL, NULL);\n AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);\n if(CFStringGetLength(state) > 0)\n return NO;\n else\n return YES;\n\n }\n" }, { "answer_id": 6910574, "author": "Jane Sales", "author_id": 63994, "author_profile": "https://Stackoverflow.com/users/63994", "pm_score": 3, "selected": false, "text": "-(BOOL)muteSwitchEnabled {\n\n#if TARGET_IPHONE_SIMULATOR\n // set to NO in simulator. Code causes crashes for some reason.\n return NO;\n#endif\n\n// go back to Ambient to detect the switch\nAVAudioSession* sharedSession = [AVAudioSession sharedInstance];\n[sharedSession setCategory:AVAudioSessionCategoryAmbient error:nil];\n\nCFStringRef state;\nUInt32 propertySize = sizeof(CFStringRef);\nAudioSessionInitialize(NULL, NULL, NULL, NULL);\nAudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);\n\nBOOL muteSwitch = (CFStringGetLength(state) <= 0);\nNSLog(@\"Mute switch: %d\",muteSwitch);\n\n// code below here is just restoring my own audio state, YMMV\n_hasMicrophone = [sharedSession inputIsAvailable];\nNSError* setCategoryError = nil;\n\nif (_hasMicrophone) {\n\n [sharedSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &setCategoryError];\n\n // By default PlayAndRecord plays out over the internal speaker. We want the external speakers, thanks.\n UInt32 ASRoute = kAudioSessionOverrideAudioRoute_Speaker;\n AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,\n sizeof (ASRoute),\n &ASRoute\n );\n}\nelse\n // Devices with no mike don't support PlayAndRecord - we don't get playback, so use just playback as we don't have a microphone anyway\n [sharedSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];\n\nif (setCategoryError)\n NSLog(@\"Error setting audio category! %@\", setCategoryError);\n\nreturn muteSwitch;\n}\n" }, { "answer_id": 27386533, "author": "slamor", "author_id": 2773527, "author_profile": "https://Stackoverflow.com/users/2773527", "pm_score": 2, "selected": false, "text": "NSError *error = nil;\n[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];\n[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeVideoRecording error:&error];\n[[AVAudioSession sharedInstance] setActive:YES error:&error];\n [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];\n [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];\n" }, { "answer_id": 49552131, "author": "Govind Prajapati", "author_id": 6138463, "author_profile": "https://Stackoverflow.com/users/6138463", "pm_score": 2, "selected": false, "text": "pod 'Mute'\n import UIKit\nimport Mute\n\nclass ViewController: UIViewController {\n\n @IBOutlet weak var label: UILabel! {\n didSet {\n self.label.text = \"\"\n }\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n // Notify every 2 seconds\n Mute.shared.checkInterval = 2.0\n\n // Always notify on interval\n Mute.shared.alwaysNotify = true\n\n // Update label when notification received\n Mute.shared.notify = { m in\n self.label.text = m ? \"Muted\" : \"Not Muted\"\n }\n\n // Stop after 5 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {\n Mute.shared.isPaused = true\n }\n\n // Re-start after 10 seconds\n DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {\n Mute.shared.isPaused = false\n }\n }\n\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34820/" ]
287,553
<p>Every time I have to build a form with a <code>DateTime</code> field I try to find a decent free custom control - I always fail.</p> <p>I cannot figure out why it isn't built in the .NET but let's forget about for a minute and concentrate on my question :D</p> <p>Anyone got one?</p>
[ { "answer_id": 287815, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": true, "text": "Mask=\"99:99\"\nAutoCompleteValue=\"00:00\"\nAcceptAMPM=\"true\"\nMaskType=\"Time\"\n" }, { "answer_id": 289808, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 0, "selected": false, "text": "<asp:TextBox runat=\"server\" ID=\"startDate\" autocomplete=\"off\" />\n<ajaxToolkit:CalendarExtender \n ID=\"defaultCalendarExtender\" \n runat=\"server\" \n TargetControlID=\"startDate\" />\n<asp:TextBox ID=\"startTime\" runat=\"server\" Columns=\"8\"></asp:TextBox>\n<ajaxToolkit:MaskedEditExtender \n ID=\"startTime_MaskedEditExtender1\" runat=\"server\" \n Enabled=\"True\" \n TargetControlID=\"startTime\" \n MaskType=\"Time\" \n AutoCompleteValue=\"09:00\"\n Mask=\"99:99\"\n AcceptAMPM=\"true\">\n</ajaxToolkit:MaskedEditExtender>\n<ajaxToolkit:MaskedEditValidator \n ID=\"MaskedEditValidator1\" \n runat=\"server\" \n ControlExtender=\"startTime_MaskedEditExtender1\"\n ControlToValidate=\"startTime\" \n IsValidEmpty=\"False\"\n EmptyValueMessage=\"Time is required\"\n InvalidValueMessage=\"Time is invalid\"\n Display=\"Dynamic\"\n TooltipMessage=\"Input a time\"\n EmptyValueBlurredText=\"*\"\n InvalidValueBlurredMessage=\"Check time\">\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
287,563
<p>Is there a way in Oracle to select the date on which daylight savings will switch over for my locale?</p> <p>Something vaguely equivalent to this would be nice:</p> <pre><code>SELECT CHANGEOVER_DATE FROM SOME_SYSTEM_TABLE WHERE DATE_TYPE = 'DAYLIGHT_SAVINGS_CHANGEOVER' AND TO_CHAR(CHANGEOVER_DATE,'YYYY') = TO_CHAR(SYSDATE,'YYYY'); -- in the current year </code></pre> <p><em>Edit: I was hoping for a solution that would not require changes when Congress adjusts DST laws, as they did in 2007. The posted solutions will work, though.</em></p>
[ { "answer_id": 287855, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 3, "selected": true, "text": "Function DaylightSavingTimeStart (p_Date IN Date)\nReturn Date Is\n v_Date Date;\n v_LoopIndex Integer;\nBegin\n --Set the date to the 8th day of March which will effectively skip the first Sunday.\n v_Date := to_date('03/08/' || to_char(p_Date,'YYYY') || '02:00:00 AM','MM/DD/YYYY HH:MI:SS PM');\n --Advance to the second Sunday.\n FOR v_LoopIndex IN 0..6 LOOP\n If (RTRIM(to_char(v_Date + v_LoopIndex,'DAY')) = 'SUNDAY') Then\n Return v_Date + v_LoopIndex;\n End If;\n END LOOP;\nEnd;\n\nFunction DaylightSavingTimeEnd (p_Date IN Date)\nReturn Date Is\n v_Date Date;\n v_LoopIndex Integer;\nBegin\n --Set Date to the first of November this year\n v_Date := to_date('11/01/' || to_char(p_Date,'YYYY') || '02:00:00 AM','MM/DD/YYYY HH:MI:SS PM');\n --Advance to the first Sunday\n FOR v_LoopIndex IN 0..6 LOOP\n If (RTRIM(to_char(v_Date + v_LoopIndex,'DAY')) = 'SUNDAY') Then\n Return v_Date + v_LoopIndex;\n End If;\n END LOOP;\nEnd;\n" }, { "answer_id": 289213, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 1, "selected": false, "text": "ALTER SESSION SET time_zone='America/Phoenix';\nDROP TABLE TimeDifferences;\nCREATE TABLE TimeDifferences(LocalTimeZone TIMESTAMP(0) WITH LOCAL TIME ZONE);\nINSERT INTO TimeDifferences\n(\n SELECT to_date('01/01/' || to_char(sysdate-365,'YYYY') || '12:00:00','MM/DD/YYYYHH24:MI:SS')+rownum-1 \n FROM dual CONNECT BY rownum<=365\n);\nCOMMIT;\n\nALTER SESSION SET time_zone='America/Edmonton';\nSELECT LocalTimeZone-1 DaylightSavingTimeStartAndEnd\nFROM\n(\n SELECT LocalTimeZone, \n to_char(LocalTimeZone,'HH24') Hour1,\n LEAD(to_char(LocalTimeZone,'HH24')) OVER (ORDER BY LocalTimeZone) Hour2 \n FROM TimeDifferences\n)\nWHERE Hour1 <> Hour2; \n" }, { "answer_id": 10743932, "author": "Alon Gingold", "author_id": 1415891, "author_profile": "https://Stackoverflow.com/users/1415891", "pm_score": 0, "selected": false, "text": "create or replace function GetDSTDates\n(\n year integer,\n GetFrom integer\n)\nreturn Date\nas\n cursor c is\n select 12-to_number(to_char(LocalTimeZone at time zone '+00:00','HH24')) offset,\n min(to_char(LocalTimeZone at time zone '+00:00','DD/MM/YYYY')) fromdate,\n max(to_char(LocalTimeZone at time zone '+00:00','DD/MM/YYYY')) todate \n from (\n SELECT cast((to_date('01/01/'||to_char(year)||'12:00:00','MM/DD/YYYYHH24:MI:SS')+rownum-1) as timestamp with local time zone) LocalTimeZone\n FROM dual CONNECT BY rownum<=365\n )\n group by 12-to_number(to_char(LocalTimeZone at time zone '+00:00','HH24'));\n dstoffset integer;\n offset integer;\n dstfrom date;\n dstto date;\nbegin\n offset := 999;\n dstoffset := -999;\n for rec in c\n loop \n if rec.offset<offset\n then\n offset := rec.offset;\n end if;\n if rec.offset>dstoffset\n then\n dstoffset := rec.offset;\n dstfrom := to_date(rec.fromdate,'DD/MM/YYYY');\n dstto :=to_date(rec.todate,'DD/MM/YYYY');\n end if;\n end loop;\n if (offset<999 and dstoffset>-999 and offset<>dstoffset)\n then\n if GetFrom=1\n then\n return dstfrom;\n else \n return dstto;\n end if;\n else\n return null;\n end if;\nend;\n/\nALTER SESSION SET time_zone='Asia/Jerusalem';\nselect GetDSTDates(2012,1) DSTStart,\n GetDSTDates(2012,2) DSTEnd,\n SessionTimeZone TZ from dual;\n" }, { "answer_id": 27451082, "author": "Reimius", "author_id": 1303936, "author_profile": "https://Stackoverflow.com/users/1303936", "pm_score": 3, "selected": false, "text": "Function DaylightSavingTimeStart (p_Date IN Date)\nReturn Date Is\nBegin\n Return NEXT_DAY(TO_DATE(to_char(p_Date,'YYYY') || '/03/01 02:00 AM', 'YYYY/MM/DD HH:MI AM') - 1, 'SUN') + 7;\nEnd;\n\nFunction DaylightSavingTimeEnd (p_Date IN Date)\nReturn Date Is\nBegin\n Return NEXT_DAY(TO_DATE(to_char(p_Date,'YYYY') || '/11/01 02:00 AM', 'YYYY/MM/DD HH:MI AM') - 1, 'SUN');\nEnd;\n" }, { "answer_id": 66659909, "author": "usr-bin-drinking", "author_id": 1112755, "author_profile": "https://Stackoverflow.com/users/1112755", "pm_score": 0, "selected": false, "text": "--Start of DST\nselect next_day(to_date('08-MAR-' || to_char(sysdate, 'YYYY')), 'SUN') from dual\n\n--End of DST\nselect next_day(to_date('01-NOV-' || to_char(sysdate, 'YYYY')), 'SUN') from dual\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
287,585
<p>I'm trying to pass a null value for the first parameter in the code below, but MySQL complains that </p> <pre> Incorrect number of arguments for PROCEDURE myProc; expected 2, got 1 </pre> <p>When I manually call the procedure with the first argument as null, it works, but when <code>EmptyAsNullStartsWith(employeeNumberText.Text)</code> returns null, it complains. </p> <pre><code>Database db = DatabaseFactory.CreateDatabase( ConfigurationManager.AppSettings["dbType"] ); DbCommand cmd = db.GetStoredProcCommand("staff_listforinquiry"); db.AddeParameter( cmd, "in_employeeNumber", DbType.String, EmptyAsNullStartsWith(employeeNumberText.Text) ); db.AddeParameter( cmd, "in_name", DbType.String, EmptyAsNullContains(employeeNameText.Text) ); </code></pre>
[ { "answer_id": 9112404, "author": "yanke", "author_id": 1185115, "author_profile": "https://Stackoverflow.com/users/1185115", "pm_score": 0, "selected": false, "text": "if(employeeNumberText.Text != \"\")\n db.AddInParameter(dbCommand, \"in_employeeNumber\", DbType.String, employeeNumberText.Text);\nelse\n db.AddInParameter(dbCommand, \"in_employeeNumber\", DbType.String, DBNull.Value);\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
287,587
<p>I have the following code, I'm trying to get a table with 4 columns across. If I run out of columns, create a new row and make 4 more coumns. rinse. lather. repeat.</p> <pre><code>&lt;tbody&gt; &lt;% int i = 0; foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) { if (i%4 == 0 &amp;&amp; i== 0) { %&gt;&lt;tr&gt;&lt;% } if (i%4 == 0 &amp;&amp; i != 0) { %&gt;&lt;/tr&gt;&lt;tr&gt;&lt;% } %&gt; &lt;td&gt;&lt;%= multimedia.ImgTag100 %&gt;&lt;/td&gt; &lt;% i++; } %&gt; </code></pre> <p></p> <p>It works, but it sucks. Is there something built in to the framework or an extension method I can use? I guess I could roll my own, but figured there had to be something out there.</p>
[ { "answer_id": 287667, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 0, "selected": false, "text": "foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) \n{\n if (i%4 == 0 && i== 0)\n {\n %><tr><%\n }\n else if (i%4 == 0 && i != 0)\n {\n %></tr><tr><%\n }\n %><td><%= multimedia.ImgTag100 %></td><%\n i++;\n}%>\n" }, { "answer_id": 287700, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 1, "selected": false, "text": " <tbody>\n <tr>\n <%\n int i = 0;\n foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {\n\n if (i%4 == 0)\n {\n %></tr><tr><%\n }\n %> \n <td><%= multimedia.ImgTag100 %></td> \n <%\n i++;\n } %> \n </tbody> \n" }, { "answer_id": 287726, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": -1, "selected": true, "text": "<%\nforeach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {\n manageColumnsForMe( 4 )\n %><td><%= multimedia.ImgTag100 %></td><%\n } \n%>\n" }, { "answer_id": 287748, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 0, "selected": false, "text": "<tbody>\n<%\n for (int i = 0; i < ViewData.Model.ItmXtnMultimedia.Count; i++ )\n {\n %><tr><%\n for (int j = 0; i < 4; j++)\n {\n if (i < ViewData.Model.ItmXtnMultimedia.Count)\n {\n %><td><%= ViewData.Model.ItmXtnMultimedia[i].ImgTag100 %> %></td><%\n }\n else\n {\n %><td></td><%\n }\n }\n %></tr><%\n } \n%>\n</tbody>\n" }, { "answer_id": 287790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static void IDunnoWhatToCallThis<T>(\n this HtmlHelper me, \n T[] items,\n int columns,\n Action headerTemplate,\n Action<T> itemTemplate,\n Action newRowTemplate,\n Action footerTemplate )\n{\n headerTemplate();\n\n for(int i = 0;i < items.Length; i++)\n {\n if(i != 0 && i%columns == 0)\n newRowTemplate();\n\n itemTemplate(items[i]);\n }\n\n footerTemplate();\n}\n <% Html.IDunnoWhatToCallThis(\n ViewData.Model.ItmXtnMultimedia,\n 4,\n () => %><table><tr><%,\n (item) => %><td><%= item.ImgTag100 %></td><%,\n () => %></tr><tr><%,\n () => %></tr></table><%);%>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
287,588
<p>Why does the select statement below return two different values ?</p> <pre><code>declare @tempDec decimal set @tempDec = 1.0 / (1.0 + 1.0) select @tempDec, 1.0 / (1.0 + 1.0) </code></pre>
[ { "answer_id": 288285, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": true, "text": "convert(decimal, [col1]) / ([col2] + [col3])\n convert(decimal(15, 2), [col1]) / ([col2] + [col3])\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16162/" ]
287,592
<p>Why does the following have the effect it does - it prints a terminal full of random characters and then exits leaving a command prompt that produces garbage when you type in it. (I tried it because I thought it would produce a seg fault).</p> <p><img src="https://i.stack.imgur.com/kGkf4.png" alt="http://oi38.tinypic.com/r9qxbt.jpg"></p> <pre><code>#include &lt;stdio.h&gt; int main(){ char* s = "lololololololol"; while(1){ printf("%c", *s); s++; } } </code></pre> <p>it was compiled with:</p> <pre>gcc -std=c99 hello.c</pre>
[ { "answer_id": 287607, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 3, "selected": false, "text": "while(1) *s s++" }, { "answer_id": 287820, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "while #include <stdio.h>\n\nint main() {\n char *s = \"lolololololololol\";\n while (*s != '\\0') {\n printf(\"%c\", *s);\n s++;\n }\n}\n while(1) while(1) break #include <stdio.h>\n\nint main() {\n char *s = \"lolololololololol\";\n while (1) {\n if (*s == '\\0')\n break;\n printf(\"%c\", *s);\n s++;\n }\n}\n" }, { "answer_id": 300133, "author": "tomjen", "author_id": 21133, "author_profile": "https://Stackoverflow.com/users/21133", "pm_score": 1, "selected": false, "text": "while (*s) {\n while (*s != '\\0')\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
287,594
<p>I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B. </p> <p>I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq. </p> <p>What is the best approach ? </p> <p>I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.</p> <pre><code>db.Table.InsertOnSubmit(dbObject); db.SubmitChanges(); Int32 id = dbOject.Id; //Rest of the code </code></pre> <p>Any way to elegantly do this?</p>
[ { "answer_id": 313042, "author": "BigJoe714", "author_id": 37786, "author_profile": "https://Stackoverflow.com/users/37786", "pm_score": 5, "selected": true, "text": "Order order = new Order();\nOrder.OrderDate = DateTime.Now();\ndataContext.InsertOnSubmit(order);\n\nOrderItem item1 = new OrderItem();\nItem1.ItemId = 123;\n//Note: We set the Order property, which is an Order object\n// We do not set the OrderId property\n// LINQ will know to use the Id that is assigned from the order above\nItem1.Order = order; \ndataContext.InsertOnSubmit(item1);\n\ndataContext.SubmitChanges();\n" }, { "answer_id": 6775668, "author": "Hitendra", "author_id": 855875, "author_profile": "https://Stackoverflow.com/users/855875", "pm_score": 1, "selected": false, "text": " Product_Table AddProducttbl = new Product_Table();\n Product_Company Companytbl = new Product_Company();\n Product_Category Categorytbl = new Product_Category();\n\n // genrate product id's\n long Productid = (from p in Accountdc.Product_Tables \n select p.Product_ID ).FirstOrDefault();\n if (Productid == 0)\n Productid++;\n else\n Productid = (from lng in Accountdc.Product_Tables \n select lng.Product_ID ).Max() + 1;\n try\n {\n AddProducttbl.Product_ID = Productid;\n AddProducttbl.Product_Name = Request.Form[\"ProductName\"];\n AddProducttbl.Reorder_Label = Request.Form[\"ReorderLevel\"];\n AddProducttbl.Unit = Convert.ToDecimal(Request.Form[\"Unit\"]);\n AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form[\"Selling_Price\"]);\n AddProducttbl.MRP = Convert.ToDecimal(Request.Form[\"MRP\"]);\n // Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );\n // genrate category id's\n long Companyid = (from c in Accountdc.Product_Companies\n select c.Product_Company_ID).FirstOrDefault();\n if (Companyid == 0)\n Companyid++;\n else\n Companyid = (from Ct in Accountdc.Product_Companies\n select Ct.Product_Company_ID).Max() + 1;\n\n Companytbl.Product_Company_ID = Companyid;\n Companytbl.Product_Company_Name = Request.Form[\"Company\"];\n\n AddProducttbl.Product_Company = Companytbl;\n //Genrate Category id's\n long Categoryid = (from ct in Accountdc.Product_Categories\n select ct.Product_Category_ID).FirstOrDefault();\n if (Categoryid == 0)\n Categoryid++;\n else\n Categoryid = (from Ct in Accountdc.Product_Categories\n select Ct.Product_Category_ID).Max() + 1;\n Categorytbl.Product_Category_ID = Categoryid;\n Categorytbl.Product_Category_Name = Request.Form[\"Category\"];\n AddProducttbl.Product_Category = Categorytbl;\n\n Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);\n Accountdc.SubmitChanges();\n\n }\n catch \n {\n ViewData[\"submit Error\"] = \"No Product Submit\";\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31148/" ]
287,595
<p>This seems like a very simple and a very common problem. The simplest example I can think of is this:</p> <p>The form has five checkboxes with a "check all/check none" checkbox above them. When a user selects checking all checkboxes, I toggle the states of the "children" - obviously I don't want to fire the check events of all the children until I am done setting all of the checkboxes.</p> <p>I can't find a form-wide suspend control event. If I'm simply missing it then great simple answer. Barring a simple solution that I am just missing, what is the best way (best practice? accepted solution?) to suspend form control events?</p>
[ { "answer_id": 287659, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "AddHandler chk1.CheckedChanged, AddressOf DoSomething\n Private Sub DoSomething(ByVal sender As Object, ByVal e As EventArgs)\n ' whatever\nEnd Sub\n RemoveHandler chk1.CheckedChanged, AddressOf DoSomething\n" }, { "answer_id": 287671, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 4, "selected": true, "text": "/*SNIP*/\n\nprivate bool isMassUpdate;\n\npublic void Check1_Check(object sender, EventArgs e)\n{\n if(!isMassUpdate)\n {\n do some stuff\n }\n}\n\n/*SNIP*/\n" }, { "answer_id": 288284, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 1, "selected": false, "text": "Private bSuspendEvents as Boolean\n\nPrivate Sub Button1_Click()\n\n On Error Goto ErrorHandler\n\n If bSuspendEvents then Exit Sub\n\n bSuspendEvents = True\n\n 'Do stuff\n\n NormalExit:\n bSuspendEvents = False\n Exit Sub\n\n ErrorHandler:\n 'Handle Error\n Resume NormalExit\n\nEnd Sub\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35555/" ]
287,596
<p>Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if you never modify a row, but only insert or delete rows?</p> <p>I..e you never do an UPDATE to any of the rows.</p>
[ { "answer_id": 287635, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 4, "selected": true, "text": "SELECT\n my_id,\n my_date\nFROM\n My_Table\nWHERE\n my_date >= '2008-01-01'\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
287,597
<p>If a hacker has access to the hashes in my DB, he has access to the rest of the information in the DB anyways. So why would he bother trying to decrypt the passwords? Should I be storing the passwords on a different server to the rest of my data? That is the only scenario in which I can envision it being useful. </p>
[ { "answer_id": 16133410, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 0, "selected": false, "text": "SELECT * FROM USERS" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37412/" ]
287,630
<p>I have a right outer join, that almost does what I want...</p> <pre><code>SELECT users_usr.firstname_usr, users_usr.lastname_usr, credit_acc.given_credit_acc, users_usr.created_usr, users_usr.sitenum_usr, users_usr.original_aff_usr, users_usr.id_usr FROM credit_acc right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr </code></pre> <p>The problem is, I want to add a </p> <pre><code>where credit_acc.type_acc = 'init' </code></pre> <p>But this gets rid of all users who don't have a row in credit_acc... which is WHY I need a right outer join.</p> <p>Is there a way to get this without having to do two queries and a union?</p>
[ { "answer_id": 287638, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": true, "text": "SELECT\nusers_usr.firstname_usr,\nusers_usr.lastname_usr,\ncredit_acc.given_credit_acc,\nusers_usr.created_usr,\nusers_usr.sitenum_usr,\nusers_usr.original_aff_usr,\nusers_usr.id_usr\nFROM\ncredit_acc\nright Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr\nWHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL\n WHERE COALESCE(credit_acc.type_acc, 'init') = 'init'\n" }, { "answer_id": 287648, "author": "Ben Noland", "author_id": 32899, "author_profile": "https://Stackoverflow.com/users/32899", "pm_score": 1, "selected": false, "text": "SELECT\nusers_usr.firstname_usr,\nusers_usr.lastname_usr,\ncredit_acc.given_credit_acc,\nusers_usr.created_usr,\nusers_usr.sitenum_usr,\nusers_usr.original_aff_usr,\nusers_usr.id_usr\nFROM\ncredit_acc\nright Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr and credit_acc.type_acc = 'init'\n" }, { "answer_id": 287651, "author": "gpojd", "author_id": 28071, "author_profile": "https://Stackoverflow.com/users/28071", "pm_score": 2, "selected": false, "text": "WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc IS NULL;\n" }, { "answer_id": 287664, "author": "Skeolan", "author_id": 9640, "author_profile": "https://Stackoverflow.com/users/9640", "pm_score": 0, "selected": false, "text": "where credit_acc.type_acc is null OR credit_acc.type_acc = 'init'\n" }, { "answer_id": 287861, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "WHERE credit_acc.uid_usr IS NULL OR credit_acc.type_acc = 'init'\n" }, { "answer_id": 287922, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "SELECT U.firstname_usr, U.lastname_usr, C.given_credit_acc, \n U.created_usr, U.sitenum_usr, U.original_aff_usr, U.id_usr\nFrom credit_acc C Right Join users_usr U\n On C.uid_usr = U.id_usr\n And C.type_acc = 'init'\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
287,633
<p>Is it possible to do a "C like" fork in java, using an new independent jvm process ?</p> <p>How?</p>
[ { "answer_id": 21028141, "author": "Markus Malkusch", "author_id": 1346207, "author_profile": "https://Stackoverflow.com/users/1346207", "pm_score": 2, "selected": false, "text": "Isolate" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28921/" ]
287,645
<p>I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.</p>
[ { "answer_id": 287654, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 9, "selected": true, "text": "Modifier.isStatic(method.getModifiers()) /**\n * Returns the public static methods of a class or interface,\n * including those declared in super classes and interfaces.\n */\npublic static List<Method> getStaticMethods(Class<?> clazz) {\n List<Method> methods = new ArrayList<Method>();\n for (Method method : clazz.getMethods()) {\n if (Modifier.isStatic(method.getModifiers())) {\n methods.add(method);\n }\n }\n return Collections.unmodifiableList(methods);\n}\n Modifier" }, { "answer_id": 287674, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "public Method[] getStatics(Class<?> c) {\n Method[] all = c.getDeclaredMethods()\n List<Method> back = new ArrayList<Method>();\n\n for (Method m : all) {\n if (Modifier.isStatic(m.getModifiers())) {\n back.add(m);\n }\n }\n\n return back.toArray(new Method[back.size()]);\n}\n" }, { "answer_id": 287681, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 4, "selected": false, "text": "for (Method m : MyClass.class.getMethods()) {\n if (Modifier.isStatic(m.getModifiers()))\n System.out.println(\"Static Method: \" + m.getName());\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
287,655
<p>In OpenGL I'm trying to rotate a camera around a point, with camera being distance r from the point and facing the point when it rotates. In other words, I want the camera to move along the circumference of a circle at a radius r from the center, with the camera facing the center at any point along the circumference.</p> <p>Lets say that in 3d space the center of the circle is (3, 0, 3);</p> <p>I've tried:</p> <pre><code>// move to center of circle glTranslatef(-3, 0, -3) // move a distance away from the circle glTranslatef(0, 0, r); // rotate along the y "up" axis glRotatef(CameraAngle, 0, 1, 0); </code></pre> <p>where CameraAngle is the degrees being moved around the circle.</p> <p>My end result is the camera is still rotating along the origin, not the center of the circle. Can anyone help me fix this problem? Thanks!</p>
[ { "answer_id": 287675, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 6, "selected": true, "text": "gluLookAt P" }, { "answer_id": 712850, "author": "neoedmund", "author_id": 86600, "author_profile": "https://Stackoverflow.com/users/86600", "pm_score": 4, "selected": false, "text": "// move camera a distance r away from the center\nglTranslatef(0, 0, -r);\n\n// rotate \nglRotatef(angley, 0, 1, 0);\nglRotatef(anglex, 1, 0, 0);\n\n// move to center of circle \nglTranslatef(-cx, -cy, -cz)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ]
287,663
<p>I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?</p>
[ { "answer_id": 287694, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "Delegate[] events = Form1.SomeEvent.GetInvokationList();\n\nforeach (Delegate d in events)\n{\n Form1.SomeEvent -= d;\n}\n" }, { "answer_id": 3426847, "author": "Greg B", "author_id": 413393, "author_profile": "https://Stackoverflow.com/users/413393", "pm_score": 2, "selected": false, "text": "public static void UnregisterAllEvents(object objectWithEvents)\n{\n Type theType = objectWithEvents.GetType();\n\n //Even though the events are public, the FieldInfo associated with them is private\n foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))\n {\n //eventInfo will be null if this is a normal field and not an event.\n System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);\n if (eventInfo != null)\n {\n MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;\n if (multicastDelegate != null)\n {\n foreach (Delegate _delegate in multicastDelegate.GetInvocationList())\n {\n eventInfo.RemoveEventHandler(objectWithEvents, _delegate);\n }\n }\n }\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
287,679
<p>How do I create tabbed navigation with the "Current" tab highlighted in the UI?</p>
[ { "answer_id": 287688, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 4, "selected": true, "text": "public partial class AdminNavigation : ViewUserControl\n{\n /// <summary>\n /// This hold a collection of controllers and their respective \"tabs.\" Each Tab should have at least one controller in the collection.\n /// </summary>\n private readonly IDictionary<Type, string> dict = new Dictionary<Type, string>();\n\n public AdminNavigation()\n {\n dict.Add(typeof(BrandController), \"catalog\");\n dict.Add(typeof(CatalogController), \"catalog\");\n dict.Add(typeof(GroupController), \"catalog\");\n dict.Add(typeof(ItemController), \"catalog\");\n dict.Add(typeof(ConfigurationController), \"configuration\");\n dict.Add(typeof(CustomerController), \"customer\");\n dict.Add(typeof(DashboardController), \"dashboard\");\n dict.Add(typeof(OrderController), \"order\");\n dict.Add(typeof(WebsiteController), \"website\");\n }\n\n protected string SetClass(string linkToCheck)\n {\n Type controller = ViewContext.Controller.GetType();\n // We need to determine if the linkToCheck is equal to the current controller using dict as a Map\n string dictValue;\n dict.TryGetValue(controller, out dictValue);\n\n if (dictValue == linkToCheck)\n {\n return \"current\";\n }\n return \"\";\n }\n}\n <li class=\"<%= SetClass(\"customer\") %>\"><%= Html.ActionLink<CustomerController>(c=>c.Index(),\"Customers\",new{@class=\"nav_customers\"}) %></li>\n <% Html.RenderPartial(\"AdminNavigation\"); %>\n" }, { "answer_id": 1254900, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 2, "selected": false, "text": "public static string BodyClass(RouteData data) {\n return string.Format(\"{0}-{1}\", data.Values[\"Controller\"], data.Values[\"Action\"]).ToLower();\n}\n <body class=\"<%=AppHelper.BodyClass(ViewContext.RouteData) %>\">\n...\n</body>\n #primaryNavigation a { ... }\n.home-index #primaryNavigation a#home { ... }\n.home-about #primaryNavigation a#about { ... }\n.home-contact #primaryNavigation a#contact { ... }\n/* etc. */\n" }, { "answer_id": 2927323, "author": "Tomas Jansson", "author_id": 280693, "author_profile": "https://Stackoverflow.com/users/280693", "pm_score": 3, "selected": false, "text": "public static string ActiveTab(this HtmlHelper helper, string activeController, string[] activeActions, string cssClass) \n{ \n string currentAction = helper.ViewContext.Controller. \n ValueProvider.GetValue(\"action\").RawValue.ToString();\n string currentController = helper.ViewContext.Controller. \n ValueProvider.GetValue(\"controller\").RawValue.ToString(); \n string cssClassToUse = currentController == activeController && \n activeActions.Contains(currentAction) \n ? cssClass \n : string.Empty; \n return cssClassToUse; \n} \n Html.ActiveTab(\"Home\", new string[] {\"Index\", \"Home\"}, \"active\")\n" }, { "answer_id": 17540826, "author": "Ε Г И І И О", "author_id": 687190, "author_profile": "https://Stackoverflow.com/users/687190", "pm_score": 1, "selected": false, "text": "Site.css 'selectedLink' ul _Layout.cshtml @{\n var controller = @HttpContext.Current.Request.RequestContext.RouteData.Values[\"controller\"].ToString();\n}\n<ul id=\"menu\"> \n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\", null, new { @class = controller == \"Home\" ? \"selectedLink\" : \"\" })</li>\n ...\n</ul>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
287,684
<p>I'm using this simple regular expression to validate a hex string:</p> <pre><code>^[A-Fa-f0-9]{16}$ </code></pre> <p>As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).</p>
[ { "answer_id": 287687, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$\n" }, { "answer_id": 287692, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "^[A-Fa-f0-9]{16}([A-Fa-f0-9]{2})?$\n" }, { "answer_id": 287693, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 7, "selected": true, "text": "^([A-Fa-f0-9]{2}){8,9}$\n" }, { "answer_id": 287853, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 0, "selected": false, "text": "/^[a-f0-9]{16}([a-f0-9]{2})?$/i\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24927/" ]
287,685
<p>I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1<br> There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is there a way to call these events manually when any of these buttons are pressed.</p> <p>Thanks.<br> Kishore</p> <p>[Edit]</p> <p>This is how I solved the problem. Thanks <em><a href="https://stackoverflow.com/questions/287685/raise-lostfocus-event-on-a-control-manually-c#287740">Chris Marasti-Georg</a></em> for the pointer. In the button click event I calling focus on the toolstrip instead of the button as the toolstripbutton does not have a focus event. We can access the toolstrip on which the button is placed using</p> <p>((ToolStripButton)sender).Owner.Focus()</p> <p>-Kishore</p>
[ { "answer_id": 287740, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "private void ButtonClick(object sender, EventArgs e) {\n if(sender != null) {\n sender.Focus();\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169/" ]
287,702
<p>I need to read data added to the end of an executable from within that executable .<br> On win32 I have a problem that I cannot open the .exe for reading. I have tried CreateFile and std::ifstream.<br> Is there a way of specifying non-exclusive read access to a file that wasn't initially opened with sharing.</p> <p>EDIT- Great thing about stackoverflow, you ask the wrong question and get the right answer.</p>
[ { "answer_id": 287742, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 1, "selected": false, "text": "HANDLE file=CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);\n" }, { "answer_id": 287743, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "FILE* f = fopen( fname, \"rb\");\n\nhFile = CreateFile( fname, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10897/" ]
287,703
<p>I'm using IIS 6 with EPiserver CMS which requires all requests to go through aspnet_isapi.dll.</p> <p>I want to gzip all my static files (js, css mainly). Trying to setup compression in IIS didn't work.</p> <p>Is there a setting in EPiServer that will allow me to achieve this? Can .net framework compress files automatically?</p>
[ { "answer_id": 287771, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": true, "text": "HcScriptFileExtensions=\"asp\ndll \nexe \njs\ncss\"\n HcFileExtensions" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29555/" ]
287,708
<p>I am looking for any best practices or ideas on how you would create an interface with a DB from a .NET web application to upload data from Excel files Should I use a mechanism that allows all the records to be loaded and flags the errors or should I use a mechanism that stops the load when an error occurs.</p> <p>I've never had to deal with this type of requirement before so any help would be super!</p> <p>Thanks</p>
[ { "answer_id": 287749, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": " public void Load() {\n bool OK = File.Exists(_filename);\n if (OK) {\n string sql = String.Format(\"Select * from {0}\", FileName);\n OleDbConnection csv = new OleDbConnection();\n OleDbCommand cmd = new OleDbCommand(sql, csv);\n OleDbDataReader rs = null;\n SqlConnection db = null;\n SqlCommand clear = null;\n\n SqlBulkCopy bulk_load = null;\n try {\n // Note two connections: one from the csv file\n // and one to the database;\n csv = new OleDbConnection();\n csv.ConnectionString = ConnectionString;\n csv.Open();\n cmd = new OleDbCommand(sql, csv);\n rs = cmd.ExecuteReader();\n\n // Dung out the staging table\n db = // [Create A DB conneciton Here]\n clear = new SqlCommand(\"Truncate table Staging\", db); // Left to the reader\n clear.ExecuteNonQuery();\n\n // Import into the staging table\n bulk_load = new SqlBulkCopy(db);\n bulk_load.DestinationTableName = Destination; // Actually an instance var\n bulk_load.WriteToServer(rs);\n } catch (Exception ee) {\n string summary = ee.Message;\n string detail = ee.StackTrace;\n //Notify(DisplayType.error, summary, detail);\n } finally {\n if (rs != null) rs.Close();\n if (csv != null) csv.Close();\n if (bulk_load != null) bulk_load.Close();\n }\n }\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12255/" ]
287,713
<p>I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.</p> <p>I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.</p> <p>This is my code right now:</p> <pre><code> lines2 = lines.gsub( /\r\n/m, "\n" ) if ( lines == lines2 ) print "still the same\n" else print "made the change\n" end </code></pre> <p>In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part). :)</p>
[ { "answer_id": 287735, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 4, "selected": false, "text": "lines2 = lines.split.join(\"\\n\")\n" }, { "answer_id": 287739, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": false, "text": "irb(main):003:0> my_string = \"Some text with a carriage return \\r\"\n=> \"Some text with a carriage return \\r\"\nirb(main):004:0> my_string.gsub(/\\r/,\"\")\n=> \"Some text with a carriage return \"\nirb(main):005:0>\n irb(main):007:0> my_string = \"Some text with a carriage return \\r\\n\"\n=> \"Some text with a carriage return \\r\\n\"\nirb(main):008:0> my_string.gsub(/\\r\\n/,\"\\n\")\n=> \"Some text with a carriage return \\n\"\nirb(main):009:0>\n" }, { "answer_id": 287810, "author": "localshred", "author_id": 29690, "author_profile": "https://Stackoverflow.com/users/29690", "pm_score": 5, "selected": false, "text": "lines.gsub(/\\r\\n?/, \"\\n\");\n" }, { "answer_id": 287890, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 6, "selected": true, "text": "puts lines File.open \\r\\n \\n lines lines2 rb File.read" }, { "answer_id": 7095275, "author": "Ian Vaughan", "author_id": 119790, "author_profile": "https://Stackoverflow.com/users/119790", "pm_score": 7, "selected": false, "text": "\" hello \".strip #=> \"hello\" \n\"\\tgoodbye\\r\\n\".strip #=> \"goodbye\"\n string = string.gsub(/\\r/,\" \")\nstring = string.gsub(/\\n/,\" \")\n" }, { "answer_id": 8340835, "author": "Joel AZEMAR", "author_id": 552320, "author_profile": "https://Stackoverflow.com/users/552320", "pm_score": 4, "selected": false, "text": "\"still the same\\n\".chomp \"still the same\\n\".chomp!" }, { "answer_id": 8891341, "author": "Vik", "author_id": 387402, "author_profile": "https://Stackoverflow.com/users/387402", "pm_score": 4, "selected": false, "text": "modified_string = string.gsub(/\\s+/, ' ').strip\n" }, { "answer_id": 16900610, "author": "Alain Beauvois", "author_id": 183331, "author_profile": "https://Stackoverflow.com/users/183331", "pm_score": 1, "selected": false, "text": "my_string.strip.gsub(/\\s+/, ' ')\n" }, { "answer_id": 35652555, "author": "neck", "author_id": 2979547, "author_profile": "https://Stackoverflow.com/users/2979547", "pm_score": 5, "selected": false, "text": "squish \"\\tgoodbye\\r\\n\".squish => \"goodbye\" \"\\tgood \\t\\r\\nbye\\r\\n\".squish => \"good bye\"" }, { "answer_id": 45759253, "author": "frenesim", "author_id": 1451180, "author_profile": "https://Stackoverflow.com/users/1451180", "pm_score": 2, "selected": false, "text": "lines.map(&:strip).join(\" \")\n" }, { "answer_id": 46591610, "author": "Nathan Crause", "author_id": 251930, "author_profile": "https://Stackoverflow.com/users/251930", "pm_score": 3, "selected": false, "text": "lines2 = lines.gsub(/[\\r\\n]+/m, \"\\n\")\n" }, { "answer_id": 48784893, "author": "k1r8r0wn", "author_id": 3914672, "author_profile": "https://Stackoverflow.com/users/3914672", "pm_score": 2, "selected": false, "text": "lines.delete(\" \\n\")\n" }, { "answer_id": 49424962, "author": "Dennis", "author_id": 2695716, "author_profile": "https://Stackoverflow.com/users/2695716", "pm_score": 0, "selected": false, "text": "def dos2unix(input)\n input.each_byte.map { |c| c.chr unless c == 13 }.join\nend\n\nremove_all_the_carriage_returns = dos2unix(some_blob)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7893/" ]
287,750
<p>I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.</p> <pre><code>&lt;img src="pic.jpg" usemap="#picmap" /&gt; &lt;map id="picmap" name="picmap"&gt;&lt;area shape="rect" coords ="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /&gt; &lt;/map&gt; &lt;p id="desc"&gt;&lt;/p&gt; </code></pre> <p>Where in the header I defined these functions:</p> <pre><code> &lt;script type="text/javascript"&gt; function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; &lt;/script&gt; </code></pre> <p>It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). <strong>How can I make the image switching more seamless without reduction in picture quality?</strong> On second thought I realize that I could also just have both images displayed, at a small and a large scale, and <strong>on mouse over they would switch places; How would I do this?</strong> Would this reduce lag? </p>
[ { "answer_id": 287766, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "function preloadImage(imagePath)\n{\n var img = document.createElement('IMG');\n img.src = imagePath; \n}\n\npreloadImage('BigImage');\n" }, { "answer_id": 287780, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 6, "selected": true, "text": "tempImg = new Image()\ntempImg.src=\"pic2.jpg\"\n preloads = \"red.gif,green.gif,blue.gif\".split(\",\")\nvar tempImg = []\n\nfor(var x=0;x<preloads.length;x++) {\n tempImg[x] = new Image()\n tempImg[x].src = preloads[x]\n}\n" }, { "answer_id": 287850, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 2, "selected": false, "text": "a { \n background-image: url(back.png); \n background-repeat: no-repeat; \n background-attachment:fixed; \n background-position: 0 0;\n}\n\na:hover {\n background-image: url(back.png); \n background-repeat: no-repeat; \n background-attachment:fixed; \n background-position: 0 20px; \n} \n" }, { "answer_id": 287882, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 0, "selected": false, "text": "display: none; display: inline" }, { "answer_id": 288114, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "var myImgs = ['path/to/img1.jpg', 'path/to/img2.gif'];\n\nfunction preload(imgs) {\n var img;\n for (var i = 0, len = imgs.length; i < len; ++i) {\n img = new Image();\n img.src = imgs[i];\n }\n}\n\npreload(myImgs);\n" }, { "answer_id": 6990691, "author": "Turadg", "author_id": 46040, "author_profile": "https://Stackoverflow.com/users/46040", "pm_score": 3, "selected": false, "text": "imageList.forEach( function(path) { new Image().src=path } );\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30181/" ]
287,757
<p>I read the part of <a href="http://docs.python.org/library/configparser.html" rel="noreferrer">the docs</a> and saw that the <code>ConfigParser</code> returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case:</p> <pre><code>&gt;&gt;&gt; from ConfigParser import ConfigParser &gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; fh = StringIO(""" ... [Some Section] ... spam: eggs ... spam: ham ... """) &gt;&gt;&gt; parser = ConfigParser() &gt;&gt;&gt; parser.readfp(fh) &gt;&gt;&gt; print parser.items('Some Section') [('spam', 'ham')] </code></pre> <p>Then I went back and found the part of the docs that I <em>should</em> have read:</p> <blockquote> <p>Sections are normally stored in a builtin dictionary. An alternative dictionary type can be passed to the ConfigParser constructor. For example, if a dictionary type is passed that sorts its keys, the sections will be sorted on write-back, as will be the keys within each section.</p> </blockquote> <p>To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if <code>ConfigParser</code>'s implementation changes) should I just write a variant of the <code>ConfigParser</code> itself?</p> <p>I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions.</p> <p><strong>[Edit:]</strong> Here's a more precise example of how I'd like to use the same key multiple times:</p> <pre><code>[Ignored Paths] ignore-extension: .swp ignore-filename: tags ignore-directory: bin </code></pre> <p>I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.</p>
[ { "answer_id": 287942, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 4, "selected": true, "text": "[('spam', 'eggs'), ('spam', 'ham')]\n parser.get('Some Section', 'spam')\n [Some Section]\nspam: eggs, ham\n spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')]\n" }, { "answer_id": 13340655, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 0, "selected": false, "text": "name: pyglet\nurl: http://www.pyglet.org/\n\noutput: html\ntarget: doc/api/\n... \nmodule: pyglet\n\nexclude: pyglet.gl.gl\nexclude: pyglet.gl.agl\nexclude: pyglet.gl.lib_agl\nexclude: pyglet.gl.wgl\n...\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
287,783
<p>I am using an ancient version of Oracle (8.something) and my ADO.NET application needs to do some fairly large transactions. Large enough to not fin in our small rollback segments. Now we have a large rollback segment as well but it is not used by default.</p> <p>Oracle has a command to select the rollback segment to be used (<code>SET TRANSACTION USE ROLLBACK SEGMENT MY_ROLLBACK_SEGMENT</code>) but it needs to be the first command issued in the transaction. Unfortunately, it seems that ADO.NET issues some other commands at the beginning of a transaction since issuing this command right after .BeginTransaction() throws an error about SET TRANSACTION not being the first command.</p> <p>I am sure I am not the only one who faced this issue. How do you solve it or how would you get around it?</p> <p>Thanks</p>
[ { "answer_id": 289832, "author": "pablo", "author_id": 16112, "author_profile": "https://Stackoverflow.com/users/16112", "pm_score": 2, "selected": true, "text": "ALTER ROLLBACK SEGMENT <name> OFFLINE;\n\nALTER ROLLBACK SEGMENT <name> ONLINE;\n" }, { "answer_id": 291629, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 1, "selected": false, "text": "begin\ncommit;\nSET TRANSACTION USE ROLLBACK SEGMENT UNDOTBS1;\n--Your code here\nend;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
287,789
<p>I have a huge file that I must parse line by line. Speed is of the essence. </p> <p>Example of a line:</p> <blockquote> <pre><code>Token-1 Here-is-the-Next-Token Last-Token-on-Line ^ ^ Current Position Position after GetToken </code></pre> </blockquote> <p>GetToken is called, returning "Here-is-the-Next-Token" and sets the CurrentPosition to the position of the last character of the token so that it is ready for the next call to GetToken. Tokens are separated by one or more spaces.</p> <p>Assume the file is already in a StringList in memory. It fits in memory easily, say 200 MB.</p> <p>I am worried only about the execution time for the parsing. What code will produce the absolute fastest execution in Delphi (Pascal)?</p>
[ { "answer_id": 287808, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "state := 0;\nresult := tkNoToken;\nwhile (result = tkNoToken) do begin\n if table[state].c1 > table[state].c2 then\n result := table[state].value\n else if (table[state].c1 <= c) and (c <= table[state].c2) then begin\n c := GetNextChar();\n state := table[state].value;\n end else\n Inc(state);\nend;\n" }, { "answer_id": 287865, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 0, "selected": false, "text": "MyStringList.CommaText := s;\nfor i := 0 to MyStringList.Count - 1 do\nbegin\n // process each token here\nend;\n" }, { "answer_id": 287876, "author": "utku_karatas", "author_id": 14716, "author_profile": "https://Stackoverflow.com/users/14716", "pm_score": 2, "selected": false, "text": "{ Implements a simpe lexer class. } \nunit Simplelexer;\n\ninterface\n\nuses Classes, Sysutils, Types, dialogs;\n\ntype\n\n ESimpleLexerFinished = class(Exception) end;\n\n TProcTableProc = procedure of object;\n\n // A very simple lexer that can handle numbers, words, symbols - no comment handling \n TSimpleLexer = class(TObject)\n private\n FLineNo: Integer;\n Run: Integer;\n fOffset: Integer;\n fRunOffset: Integer; // helper for fOffset\n fTokenPos: Integer;\n pSource: PChar;\n fProcTable: array[#0..#255] of TProcTableProc;\n fUseSimpleStrings: Boolean;\n fIgnoreSpaces: Boolean;\n procedure MakeMethodTables;\n procedure IdentProc;\n procedure NewLineProc;\n procedure NullProc;\n procedure NumberProc;\n procedure SpaceProc;\n procedure SymbolProc;\n procedure UnknownProc;\n public\n constructor Create;\n destructor Destroy; override;\n procedure Feed(const S: string);\n procedure Next;\n function GetToken: string;\n function GetLineNo: Integer;\n function GetOffset: Integer;\n\n property IgnoreSpaces: boolean read fIgnoreSpaces write fIgnoreSpaces;\n property UseSimpleStrings: boolean read fUseSimpleStrings write fUseSimpleStrings;\n end;\n\nimplementation\n\n{ TSimpleLexer }\n\nconstructor TSimpleLexer.Create;\nbegin\n makeMethodTables;\n fUseSimpleStrings := false;\n fIgnoreSpaces := false;\nend;\n\ndestructor TSimpleLexer.Destroy;\nbegin\n inherited;\nend;\n\nprocedure TSimpleLexer.Feed(const S: string);\nbegin\n Run := 0;\n FLineNo := 1;\n FOffset := 1;\n pSource := PChar(S);\nend;\n\nprocedure TSimpleLexer.Next;\nbegin\n fTokenPos := Run;\n foffset := Run - frunOffset + 1;\n fProcTable[pSource[Run]];\nend;\n\nfunction TSimpleLexer.GetToken: string;\nbegin\n SetString(Result, (pSource + fTokenPos), Run - fTokenPos);\nend;\n\nfunction TSimpleLexer.GetLineNo: Integer;\nbegin\n Result := FLineNo;\nend;\n\nfunction TSimpleLexer.GetOffset: Integer;\nbegin\n Result := foffset;\nend;\n\nprocedure TSimpleLexer.MakeMethodTables;\nvar\n I: Char;\nbegin\n for I := #0 to #255 do\n case I of\n '@', '&', '}', '{', ':', ',', ']', '[', '*',\n '^', ')', '(', ';', '/', '=', '-', '+', '#', '>', '<', '$',\n '.', '\"', #39:\n fProcTable[I] := SymbolProc;\n #13, #10: fProcTable[I] := NewLineProc;\n 'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;\n #0: fProcTable[I] := NullProc;\n '0'..'9': fProcTable[I] := NumberProc;\n #1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;\n else\n fProcTable[I] := UnknownProc;\n end;\nend;\n\nprocedure TSimpleLexer.UnknownProc;\nbegin\n inc(run);\nend;\n\nprocedure TSimpleLexer.SymbolProc;\nbegin\n if fUseSimpleStrings then\n begin\n if pSource[run] = '\"' then\n begin\n Inc(run);\n while pSource[run] <> '\"' do\n begin\n Inc(run);\n if pSource[run] = #0 then\n begin\n NullProc;\n end;\n end;\n end;\n Inc(run);\n end\n else\n inc(run);\nend;\n\nprocedure TSimpleLexer.IdentProc;\nbegin\n while pSource[Run] in ['_', 'A'..'Z', 'a'..'z', '0'..'9'] do\n Inc(run);\nend;\n\nprocedure TSimpleLexer.NumberProc;\nbegin\n while pSource[run] in ['0'..'9'] do\n inc(run);\nend;\n\nprocedure TSimpleLexer.SpaceProc;\nbegin\n while pSource[run] in [#1..#9, #11, #12, #14..#32] do\n inc(run);\n if fIgnoreSpaces then Next;\nend;\n\nprocedure TSimpleLexer.NewLineProc;\nbegin\n inc(FLineNo);\n inc(run);\n case pSource[run - 1] of\n #13:\n if pSource[run] = #10 then inc(run);\n end;\n foffset := 1;\n fRunOffset := run;\nend;\n\nprocedure TSimpleLexer.NullProc;\nbegin\n raise ESimpleLexerFinished.Create('');\nend;\n\nend.\n" }, { "answer_id": 288195, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 6, "selected": true, "text": "type\n TLexer = class\n private\n FData: string;\n FTokenStart: PChar;\n FCurrPos: PChar;\n function GetCurrentToken: string;\n public\n constructor Create(const AData: string);\n function GetNextToken: Boolean;\n property CurrentToken: string read GetCurrentToken;\n end;\n\n{ TLexer }\n\nconstructor TLexer.Create(const AData: string);\nbegin\n FData := AData;\n FCurrPos := PChar(FData);\nend;\n\nfunction TLexer.GetCurrentToken: string;\nbegin\n SetString(Result, FTokenStart, FCurrPos - FTokenStart);\nend;\n\nfunction TLexer.GetNextToken: Boolean;\nvar\n cp: PChar;\nbegin\n cp := FCurrPos; // copy to local to permit register allocation\n\n // skip whitespace; this test could be converted to an unsigned int\n // subtraction and compare for only a single branch\n while (cp^ > #0) and (cp^ <= #32) do\n Inc(cp);\n\n // using null terminater for end of file\n Result := cp^ <> #0;\n\n if Result then\n begin\n FTokenStart := cp;\n Inc(cp);\n while cp^ > #32 do\n Inc(cp);\n end;\n\n FCurrPos := cp;\nend;\n" }, { "answer_id": 289774, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 2, "selected": false, "text": "procedure TMyReader.InitialiseMapping(szFilename : string);\nvar\n// nError : DWORD;\n bGood : boolean;\nbegin\n bGood := False;\n m_hFile := CreateFile(PChar(szFilename), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);\n if m_hFile <> INVALID_HANDLE_VALUE then\n begin\n m_hMap := CreateFileMapping(m_hFile, nil, PAGE_READONLY, 0, 0, nil);\n if m_hMap <> 0 then\n begin\n m_pMemory := MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);\n if m_pMemory <> nil then\n begin\n htlArray := Pointer(Integer(m_pMemory) + m_dwDataPosition);\n bGood := True;\n end\n else\n begin\n// nError := GetLastError;\n end;\n end;\n end;\n if not bGood then\n raise Exception.Create('Unable to map token file into memory');\nend;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30176/" ]
287,794
<p>How should a relational database be designed to handle multi-valued attributes ?</p> <p><strong>edit</strong>: To elaborate: </p> <p>There are two ways I could think of for doing this -</p> <ol> <li>Trying something like putting comma separated values in the field, which appears a bit clumsy.</li> <li>Create another table for the field and let the multiple values go to the field. This might lead to very large number of tables, if I have too many fields of this kind.</li> </ol> <p>The question is:</p> <ol> <li>Are there any more ways of handling this?</li> <li>Which of the above two methods is generally used?</li> </ol> <p>Thanks in advance</p>
[ { "answer_id": 287836, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "CREATE TABLE team (\n team_id INT PRIMARY KEY,\n team_name VARCHAR(50),\n team_members VARCHAR(200)\n);\nINSERT INTO team VALUES (1,'Dwarfs', 'Sleepy,Dopey,Sneezy,Happy,Grumpy,Doc,Bashful')\n CREATE TABLE team (\n team_id INT PRIMARY KEY,\n team_name VARCHAR(50),\n);\nINSERT INTO team (team_name) VALUES ('Dwarfs');\n\nCREATE TABLE team_members (\n team_id INT,\n member_name VARCHAR(20),\n FOREIGN KEY (team_id) REFERENCES team(team_id)\n);\nINSERT INTO team_members VALUES \n (LAST_INSERT_ID(), 'Sleepy'),\n (LAST_INSERT_ID(), 'Dopey'),\n (LAST_INSERT_ID(), 'Sneezy'),\n (LAST_INSERT_ID(), 'Happy'),\n (LAST_INSERT_ID(), 'Grumpy'),\n (LAST_INSERT_ID(), 'Doc'),\n (LAST_INSERT_ID(), 'Bashful');\n LAST_INSERT_ID()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30252/" ]
287,797
<p>Recently an application I wrote started not working on Internet Explorer. There has been no change to the underlying (ruby on rails) code.</p> <p>In IE 6 or IE 7, I can make one request (HTTP Post) to the app, but when I try to make a 2nd request, I get an "Operation Aborted" message. Everything works fine in firefox. The HTTP Request and Response headers are exactly the same. The response header for the correct and incorrect results both have the same content-length (about 104k). The correct response has the full content, but the incorrect response has the content cut off after bout 40k. (So about 65k of the response is just gone.)</p> <p>The even trickier thing is that if I use the IP address instead of the domain name to make the request, everything works great.</p> <p>This is an apache2 web server.</p> <p>Any ideas?</p>
[ { "answer_id": 287831, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": true, "text": "http://<Web site>.com" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
287,811
<p>I'm working with an existing Java codebase which, while it can be invoked from an HTML page using an &lt;APPLET&gt; tag, does not actually subclass the Applet class. The same jars are also used in a non-browser context, so they did not subclass Applet.</p> <p>Now I need to communicate some values from Java back to the Javascript of the invoking page. Normally one would do this using JSObject, but so far as I can one has to use JSObject.getWindow which only works for subclasses of Applet.</p> <p>Is there either:</p> <ul> <li>a way to use JSObject from something which isn't an Applet subclass?</li> <li>some other mechanism to communicate back to the Javascript of the invoking page?</li> </ul>
[ { "answer_id": 287833, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "JSObject.getWindow(this) JSObject" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
287,828
<p>Is there an .net c# wrapper for the libFLAC library? If not, how can I read FLAC tags using the libFLAC in a .net framework c# application? If neither, are there other opensource libraries to read flac tags in c#? </p> <p>Thanks!</p>
[ { "answer_id": 38485614, "author": "Yoda", "author_id": 3941350, "author_profile": "https://Stackoverflow.com/users/3941350", "pm_score": 2, "selected": false, "text": "SortedList<string, List<string>> ID3PictureFrame BitmapFrame OggPageReader OggTagger FlacTagger using Luminescence.Xiph;\nOggTagger ogg = new OggTagger(@\"C:\\Song.ogg\");\n\n// Load duration\nDateTime time = new DateTime(0);\ntime = time.AddSeconds(ogg.Duration);\n\n// Tags manipulation\nstring artist = ogg.Artist;\nogg.Title = \"Creep\";\nSortedList<string, List<string>> tags = ogg.GetAllTags();\nBitmapFrame cover = ogg.FlacArts[0].Picture;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26754/" ]
287,832
<p>I am creating a form in HTML that will be printed, with fields that need to be written in by the recipient. Basically what I want is a single line that stretches from the end of the field label to the side of the page. Here's how I'm doing it right now:</p> <pre><code>&lt;table width="100%"&gt; &lt;tr&gt; &lt;td width="1%"&gt; Label: &lt;/td&gt; &lt;td style="border-bottom-style:solid; border-bottom-width:1px;"&gt; &amp;nbsp; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>This works, but there must be an easier way to do this without needing a whole table element. Any ideas?</p>
[ { "answer_id": 287838, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 2, "selected": false, "text": "<span style=\"border-bottom....\">Text</span>\n" }, { "answer_id": 287847, "author": "Jon Smock", "author_id": 25538, "author_profile": "https://Stackoverflow.com/users/25538", "pm_score": 3, "selected": false, "text": "span.print_underline\n{\n display: inline-block;\n height: 1em;\n border-bottom: 1px solid #000;\n}\n <span class=\"print_underline\" style=\"width: 200px\">&nbsp;</span>\n" }, { "answer_id": 287859, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 2, "selected": false, "text": "<label>label:</label> <div></div>" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23935/" ]
287,839
<p>[former title: Is there a way to force a relationship structure on a tag-based organizational methodology?]</p> <p>I have some entities, and they have a series of attributes. Some of the attributes affect what other attributes the entity can have, many of the attributes are organized into groups, and occasionally entities are requited to have certain numbers of attributes from certain groups, or possibly a range of attributes from certain groups.</p> <p>Is there a way to model these sorts of tag-to-tag relationships, such as requirement, grouping, exclusion, etc. using a database, or is this only possible with programmed "business rules"? Ideally, I would like the possible tags and their relationships to be easily configurable, and hence highly flexible.</p> <p>One of the ways I have considered is to have the tags and possible relationships, and then you get a tag-tag-applied relationship sort of table, but this seems like a rather brittle approach.</p> <p>So, is this possible in a more rigorous fashion, and if so, how would I even begin to go about it?</p>
[ { "answer_id": 287977, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "CREATE TABLE Vehicles (\n vehicle_id INT PRIMARY KEY\n ...attributes common to all vehicles...\n);\n\nCREATE TABLE Automobiles (\n vehicle_id INT PRIMARY KEY,\n ...attributes specific to autos...\n FOREIGN KEY (vehicle_id) REFERENCES Vehicles(vehicle_id)\n);\n Automobiles Vehicles CREATE TABLE Vehicles (\n vehicle_id INT,\n vehicle_type VARCHAR(10),\n ...attributes common to all vehicles...\n PRIMARY KEY (vehicle_id, vehicle_type),\n FOREIGN KEY (vehicle_type) REFERENCES VehicleTypes (vehicle_type)\n);\n\nCREATE TABLE Automobiles (\n vehicle_id INT,\n vehicle_type VARCHAR(10) CHECK (vehicle_type = 'Automobile'),\n ...attributes specific to autos...\n FOREIGN KEY (vehicle_id, vehicle_type) \n REFERENCES Vehicles(vehicle_id, vehicle_type)\n);\n Automobiles Vehicles vehicle_type" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20770/" ]
287,842
<p>If you have to use String.Replace() to replace test 50 times, you essentially have to create a new string 50 times. Does StringBuilder.Replace() do this more efficiently? E.g., should I use a StringBuilder if I'm going to be replacing a lot of text, even while I won't be appending any data to it?</p> <p>I'm using .NET, but I assume this would be the same as Java and possibly other languages.</p>
[ { "answer_id": 287854, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "String.Replace StringBuilder.Replace" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
[ { "answer_id": 287884, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 2, "selected": false, "text": "__init__.py import Foo\n site-packages" }, { "answer_id": 288123, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "site-packages sys.path someName.pth site-packages site-packages PYTHONPATH" }, { "answer_id": 288174, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 1, "selected": false, "text": "[server]\nPYPATH_APPEND: /home/jason:/usr/share/some_directory\n" }, { "answer_id": 288944, "author": "humble_guru", "author_id": 23961, "author_profile": "https://Stackoverflow.com/users/23961", "pm_score": 0, "selected": false, "text": "import my_util\n\nfoo = myutil.import_script('..//shared1//reusable_foo')\nif foo == None:\n sys.exit(1)\n\n\ndef import_script(script_path, log_status = True):\n \"\"\"\n imports a module and returns the handle\n \"\"\"\n lpath = os.path.split(script_path)\n\n if lpath[1] == '':\n log('Error in script \"%s\" in import_script' % (script_path))\n return None\n\n\n #check if path is already in sys.path so we don't repeat\n npath = None\n if lpath[0] == '':\n npath = '.'\n else:\n if lpath[0] not in sys.path:\n npath = lpath[0]\n\n if npath != None:\n try:\n sys.path.append(npath)\n except:\n if log_status == True:\n log('Error adding path \"%s\" in import_script' % npath)\n return None\n\n try: \n mod = __import__(lpath[1])\n except:\n error_trace,error_reason = FormatExceptionInfo()\n if log_status == True:\n log('Error importing \"%s\" module in import_script: %s' % (script_path, error_trace + error_reason))\n sys.path.remove(npath)\n return None\n\n return mod\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
287,849
<p>I'm trying to replace the programs that run from my startup directory with a batch script. The batch script will simply warn me that the programs are going to run and I can either continue running the script or stop it. </p> <p>Here's the script as I have written so far:</p> <pre><code>@echo off echo You are about to run startup programs! pause ::load outlook cmd /k "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle ::load Visual Studio 2008 call "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" </code></pre> <p>Both of these commands will load the first program and wait until I close it to load the second. I want the script to load the processes simultaneously. How do I accomplish this?</p> <p>Edit: When I use the start command it opens up a new shell with the string that I typed in as the title. The edited script looks like this:</p> <pre><code>start "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" ::load Visual Studio 2008 start "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" </code></pre>
[ { "answer_id": 287866, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 2, "selected": false, "text": "start" }, { "answer_id": 287943, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 2, "selected": false, "text": "START \"\" \"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\"\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
287,871
<p>How do I output colored text to the terminal in Python?</p>
[ { "answer_id": 287896, "author": "UberJumper", "author_id": 34395, "author_profile": "https://Stackoverflow.com/users/34395", "pm_score": 5, "selected": false, "text": "#\n" }, { "answer_id": 287919, "author": "daharon", "author_id": 23597, "author_profile": "https://Stackoverflow.com/users/23597", "pm_score": 4, "selected": false, "text": "for i in range(255):\n print i, chr(i)\n" }, { "answer_id": 287934, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 7, "selected": false, "text": "CSI = \"\\x1B[\"\nprint(CSI+\"31;40m\" + \"Colored Text\" + CSI + \"0m\")\n print(u\"\\u2588\")\n print(CSI+\"31;40m\" + u\"\\u2588\" + CSI + \"0m\")\n" }, { "answer_id": 287944, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 11, "selected": false, "text": "class bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n print(bcolors.WARNING + \"Warning: No active frommets remain. Continue?\" + bcolors.ENDC)\n print(f\"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}\")\n" }, { "answer_id": 287987, "author": "suhib-alsisan", "author_id": 37437, "author_profile": "https://Stackoverflow.com/users/37437", "pm_score": 4, "selected": false, "text": "print \" \"+ \"\\033[01;41m\" + \" \" +\"\\033[01;46m\" + \" \" + \"\\033[01;42m\"\n" }, { "answer_id": 288030, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "import unicodedata\nfp= open(\"character_list\", \"w\")\nfor index in xrange(65536):\n char= unichr(index)\n try: its_name= unicodedata.name(char)\n except ValueError: its_name= \"N/A\"\n fp.write(\"%05d %04x %s %s\\n\" % (index, index, char.encode(\"UTF-8\"), its_name)\nfp.close()\n" }, { "answer_id": 288556, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "import ctypes\n\n# Constants from the Windows API\nSTD_OUTPUT_HANDLE = -11\nFOREGROUND_RED = 0x0004 # text color contains red.\n\ndef get_csbi_attributes(handle):\n # Based on IPython's winconsole.py, written by Alexander Belchenko\n import struct\n csbi = ctypes.create_string_buffer(22)\n res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)\n assert res\n\n (bufx, bufy, curx, cury, wattr,\n left, top, right, bottom, maxx, maxy) = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n return wattr\n\n\nhandle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)\nreset = get_csbi_attributes(handle)\n\nctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)\nprint \"Cherry on top\"\nctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)\n" }, { "answer_id": 293633, "author": "Samat Jain", "author_id": 14878, "author_profile": "https://Stackoverflow.com/users/14878", "pm_score": 10, "selected": false, "text": "from termcolor import colored\n\nprint colored('hello', 'red'), colored('world', 'green')\n print(colored('hello', 'red'), colored('world', 'green'))\n os.system('color')\n" }, { "answer_id": 1073959, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 3, "selected": false, "text": "import curses\n\ndef main(stdscr):\n stdscr.clear()\n if curses.has_colors():\n for i in xrange(1, curses.COLORS):\n curses.init_pair(i, i, curses.COLOR_BLACK)\n stdscr.addstr(\"COLOR %d! \" % i, curses.color_pair(i))\n stdscr.addstr(\"BOLD! \", curses.color_pair(i) | curses.A_BOLD)\n stdscr.addstr(\"STANDOUT! \", curses.color_pair(i) | curses.A_STANDOUT)\n stdscr.addstr(\"UNDERLINE! \", curses.color_pair(i) | curses.A_UNDERLINE)\n stdscr.addstr(\"BLINK! \", curses.color_pair(i) | curses.A_BLINK)\n stdscr.addstr(\"DIM! \", curses.color_pair(i) | curses.A_DIM)\n stdscr.addstr(\"REVERSE! \", curses.color_pair(i) | curses.A_REVERSE)\n stdscr.refresh()\n stdscr.getch()\n\nif __name__ == '__main__':\n print \"init...\"\n curses.wrapper(main)\n" }, { "answer_id": 3332860, "author": "priestc", "author_id": 118495, "author_profile": "https://Stackoverflow.com/users/118495", "pm_score": 10, "selected": false, "text": "from colorama import Fore\nfrom colorama import Style\n\nprint(f\"This is {Fore.GREEN}color{Style.RESET_ALL}!\")\n" }, { "answer_id": 8548994, "author": "Erik Rose", "author_id": 171721, "author_profile": "https://Stackoverflow.com/users/171721", "pm_score": 6, "selected": false, "text": "from blessings import Terminal\n\nt = Terminal()\nprint t.red('This is red.')\nprint t.bold_bright_red_on_black('Bright red on black')\n print t.on_green(' ')\n with t.location(0, 5):\n print t.on_yellow(' ')\n print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)\n" }, { "answer_id": 8774709, "author": "Giacomo Lacava", "author_id": 1129851, "author_profile": "https://Stackoverflow.com/users/1129851", "pm_score": 4, "selected": false, "text": "from clint.textui import colored\nprint colored.red('some warning message')\nprint colored.green('nicely done!')\n" }, { "answer_id": 11178541, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 2, "selected": false, "text": "cformat cprint from icolor import cformat # there is also cprint\n\ncformat(\"This is #RED;a red string, partially with a #xBLUE;blue background\")\n'This is \\x1b[31ma red string, partially with a \\x1b[44mblue background\\x1b[0m'\n #RED; #BLUE; #RESET; #BOLD; x #xGREEN; # ## sudo easy_install icolor" }, { "answer_id": 11193790, "author": "Navweb", "author_id": 1422157, "author_profile": "https://Stackoverflow.com/users/1422157", "pm_score": 4, "selected": false, "text": "# Display text on a Windows console\n# Windows XP with Python 2.7 or Python&nbsp;3.2\nfrom ctypes import windll\n\n# Needed for Python2/Python3 diff\ntry:\n input = raw_input\nexcept:\n pass\nSTD_OUTPUT_HANDLE = -11\nstdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)\n# Look at the output and select the color you want.\n# For instance, hex E is yellow on black.\n# Hex 1E is yellow on blue.\n# Hex 2E is yellow on green and so on.\nfor color in range(0, 75):\n windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)\n print(\"%X --> %s\" % (color, \"Have a fine day!\"))\n input(\"Press Enter to go on ... \")\n" }, { "answer_id": 11278750, "author": "Janus Troelsen", "author_id": 309483, "author_profile": "https://Stackoverflow.com/users/309483", "pm_score": 5, "selected": false, "text": "with from colorama import Fore, Style\nimport sys\n\nclass Highlight:\n def __init__(self, clazz, color):\n self.color = color\n self.clazz = clazz\n def __enter__(self):\n print(self.color, end=\"\")\n def __exit__(self, type, value, traceback):\n if self.clazz == Fore:\n print(Fore.RESET, end=\"\")\n else:\n assert self.clazz == Style\n print(Style.RESET_ALL, end=\"\")\n sys.stdout.flush()\n\nwith Highlight(Fore, Fore.GREEN):\n print(\"this is highlighted\")\nprint(\"this is not\")\n" }, { "answer_id": 15647557, "author": "Vishal", "author_id": 197473, "author_profile": "https://Stackoverflow.com/users/197473", "pm_score": 3, "selected": false, "text": "\"\"\"\n.. versionadded:: 0.9.2\n\nFunctions for wrapping strings in ANSI color codes.\n\nEach function within this module returns the input string ``text``, wrapped\nwith ANSI color codes for the appropriate color.\n\nFor example, to print some text as green on supporting terminals::\n\n from fabric.colors import green\n\n print(green(\"This text is green!\"))\n\nBecause these functions simply return modified strings, you can nest them::\n\n from fabric.colors import red, green\n\n print(red(\"This sentence is red, except for \" + \\\n green(\"these words, which are green\") + \".\"))\n\nIf ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on\nfor that particular invocation, which usually shows up as a bold or brighter\nversion of the original color on most terminals.\n\"\"\"\n\n\ndef _wrap_with(code):\n\n def inner(text, bold=False):\n c = code\n if bold:\n c = \"1;%s\" % c\n return \"\\033[%sm%s\\033[0m\" % (c, text)\n return inner\n\nred = _wrap_with('31')\ngreen = _wrap_with('32')\nyellow = _wrap_with('33')\nblue = _wrap_with('34')\nmagenta = _wrap_with('35')\ncyan = _wrap_with('36')\nwhite = _wrap_with('37')\n" }, { "answer_id": 17064509, "author": "mms", "author_id": 1364048, "author_profile": "https://Stackoverflow.com/users/1364048", "pm_score": 5, "selected": false, "text": "def enable():\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = \"\\033[1m\"\n\ndef disable():\n HEADER = ''\n OKBLUE = ''\n OKGREEN = ''\n WARNING = ''\n FAIL = ''\n ENDC = ''\n\ndef infog(msg):\n print(OKGREEN + msg + ENDC)\n\ndef info(msg):\n print(OKBLUE + msg + ENDC)\n\ndef warn(msg):\n print(WARNING + msg + ENDC)\n\ndef err(msg):\n print(FAIL + msg + ENDC)\n\nenable()\n import log\nlog.info(\"Hello, World!\")\nlog.err(\"System Error\")\n" }, { "answer_id": 18923126, "author": "Diego Navarro", "author_id": 933059, "author_profile": "https://Stackoverflow.com/users/933059", "pm_score": 2, "selected": false, "text": "sudo apt-get install python-pip\npip install pycolorterm\n from pycolorterm import pycolorterm\n\nwith pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:\n out.write('Works OK!')\n" }, { "answer_id": 21786287, "author": "rabin utam", "author_id": 2112485, "author_profile": "https://Stackoverflow.com/users/2112485", "pm_score": 9, "selected": false, "text": "'\\x1b[0m' print('\\x1b[6;30;42m' + 'Success!' + '\\x1b[0m')\n def print_format_table():\n \"\"\"\n prints table of formatted text format options\n \"\"\"\n for style in range(8):\n for fg in range(30,38):\n s1 = ''\n for bg in range(40,48):\n format = ';'.join([str(style), str(fg), str(bg)])\n s1 += '\\x1b[%sm %s \\x1b[0m' % (format, format)\n print(s1)\n print('\\n')\n\nprint_format_table()\n" }, { "answer_id": 26445590, "author": "GI Jack", "author_id": 4157799, "author_profile": "https://Stackoverflow.com/users/4157799", "pm_score": 6, "selected": false, "text": "for class colors:\n '''Colors class:\n Reset all colors with colors.reset\n Two subclasses fg for foreground and bg for background.\n Use as colors.subclass.colorname.\n i.e. colors.fg.red or colors.bg.green\n Also, the generic bold, disable, underline, reverse, strikethrough,\n and invisible work with the main class\n i.e. colors.bold\n '''\n reset='\\033[0m'\n bold='\\033[01m'\n disable='\\033[02m'\n underline='\\033[04m'\n reverse='\\033[07m'\n strikethrough='\\033[09m'\n invisible='\\033[08m'\n class fg:\n black='\\033[30m'\n red='\\033[31m'\n green='\\033[32m'\n orange='\\033[33m'\n blue='\\033[34m'\n purple='\\033[35m'\n cyan='\\033[36m'\n lightgrey='\\033[37m'\n darkgrey='\\033[90m'\n lightred='\\033[91m'\n lightgreen='\\033[92m'\n yellow='\\033[93m'\n lightblue='\\033[94m'\n pink='\\033[95m'\n lightcyan='\\033[96m'\n class bg:\n black='\\033[40m'\n red='\\033[41m'\n green='\\033[42m'\n orange='\\033[43m'\n blue='\\033[44m'\n purple='\\033[45m'\n cyan='\\033[46m'\n lightgrey='\\033[47m'\n" }, { "answer_id": 27233961, "author": "Igor Šarčević", "author_id": 364938, "author_profile": "https://Stackoverflow.com/users/364938", "pm_score": 2, "selected": false, "text": "echo \"\\e[31m Hello, World! \\e[0m\"\n print(\"\\e[31m Hello world \\e[0m\")\n" }, { "answer_id": 28159385, "author": "WebMaster", "author_id": 4285493, "author_profile": "https://Stackoverflow.com/users/4285493", "pm_score": 3, "selected": false, "text": "print(pyfancy.RED + \"Hello Red\" + pyfancy.END)\n" }, { "answer_id": 28388343, "author": "Jossef Harush Kadouri", "author_id": 3191896, "author_profile": "https://Stackoverflow.com/users/3191896", "pm_score": 4, "selected": false, "text": "print colors.draw(\"i'm yellow\", bold=True, fg_yellow=True)\n print colors.error('sorry, ')\n" }, { "answer_id": 29723536, "author": "zahanm", "author_id": 640185, "author_profile": "https://Stackoverflow.com/users/640185", "pm_score": 5, "selected": false, "text": "class PrintInColor:\n RED = '\\033[91m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n LIGHT_PURPLE = '\\033[94m'\n PURPLE = '\\033[95m'\n END = '\\033[0m'\n\n @classmethod\n def red(cls, s, **kwargs):\n print(cls.RED + s + cls.END, **kwargs)\n\n @classmethod\n def green(cls, s, **kwargs):\n print(cls.GREEN + s + cls.END, **kwargs)\n\n @classmethod\n def yellow(cls, s, **kwargs):\n print(cls.YELLOW + s + cls.END, **kwargs)\n\n @classmethod\n def lightPurple(cls, s, **kwargs):\n print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)\n\n @classmethod\n def purple(cls, s, **kwargs):\n print(cls.PURPLE + s + cls.END, **kwargs)\n PrintInColor.red('hello', end=' ')\nPrintInColor.green('world')\n" }, { "answer_id": 29806601, "author": "Grijesh Chauhan", "author_id": 1673391, "author_profile": "https://Stackoverflow.com/users/1673391", "pm_score": 4, "selected": false, "text": ">>> from django.utils.termcolors import colorize\n>>> print colorize(\"Hello, World!\", fg=\"blue\", bg='red',\n... opts=('bold', 'blink', 'underscore',))\nHello World!\n>>> help(colorize)\n $ python -c \"import django; print django.VERSION\"" }, { "answer_id": 31310228, "author": "drevicko", "author_id": 420867, "author_profile": "https://Stackoverflow.com/users/420867", "pm_score": 3, "selected": false, "text": "from __future__ import print from __future__ import print_function\nfrom colorprint import *\n\nprint('Hello', 'world', color='blue', end='', sep=', ')\nprint('!', color='red', format=['bold', 'blink'])\n" }, { "answer_id": 34443116, "author": "gauravds", "author_id": 1084917, "author_profile": "https://Stackoverflow.com/users/1084917", "pm_score": 6, "selected": false, "text": "def prRed(prt):\n print(f\"\\033[91m{prt}\\033[00m\")\n\ndef prGreen(prt):\n print(f\"\\033[92m{prt}\\033[00m\")\n\ndef prYellow(prt):\n print(f\"\\033[93m{prt}\\033[00m\")\n\ndef prLightPurple(prt):\n print(f\"\\033[94m{prt}\\033[00m\")\n\ndef prPurple(prt):\n print(f\"\\033[95m{prt}\\033[00m\")\n\ndef prCyan(prt):\n print(f\"\\033[96m{prt}\\033[00m\")\n\ndef prLightGray(prt):\n print(f\"\\033[97m{prt}\\033[00m\")\n\ndef prBlack(prt):\n print(f\"\\033[98m{prt}\\033[00m\")\n\ndef prReset(prt):\n print(f\"\\033[0m{prt}\\033[00m\")\n\nprGreen(\"Hello, Green World!\")\nprBlack(\"Hello, Black World!\")\nprCyan(\"Hello, Cyan World!\")\nprGreen(\"Hello, Green World!\")\nprLightGray(\"Hello, Light Grey World!\")\nprLightPurple(\"Hello, Light Purple World!\")\nprPurple(\"Hello, Purple World!\")\nprRed(\"Hello, Red World!\")\nprYellow(\"Hello, Yellow World!\")\nprReset(\"Hello, Reset World!\")\n # python2\n def prRed(prt): print(\"\\033[91m {}\\033[00m\" .format(prt))\n def prGreen(prt): print(\"\\033[92m {}\\033[00m\" .format(prt))\n def prYellow(prt): print(\"\\033[93m {}\\033[00m\" .format(prt))\n def prLightPurple(prt): print(\"\\033[94m {}\\033[00m\" .format(prt))\n def prPurple(prt): print(\"\\033[95m {}\\033[00m\" .format(prt))\n def prCyan(prt): print(\"\\033[96m {}\\033[00m\" .format(prt))\n def prLightGray(prt): print(\"\\033[97m {}\\033[00m\" .format(prt))\n def prBlack(prt): print(\"\\033[98m {}\\033[00m\" .format(prt))\n\n prGreen(\"Hello, World!\")\n" }, { "answer_id": 37051472, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env python\nfrom asciimatics.effects import RandomNoise # $ pip install asciimatics\nfrom asciimatics.renderers import SpeechBubble, Rainbow\nfrom asciimatics.scene import Scene\nfrom asciimatics.screen import Screen\nfrom asciimatics.exceptions import ResizeScreenError\n\n\ndef demo(screen):\n render = Rainbow(screen, SpeechBubble('Rainbow'))\n effects = [RandomNoise(screen, signal=render)]\n screen.play([Scene(effects, -1)], stop_on_resize=True)\n\nwhile True:\n try:\n Screen.wrapper(demo)\n break\n except ResizeScreenError:\n pass\n" }, { "answer_id": 39005305, "author": "Ben174", "author_id": 850927, "author_profile": "https://Stackoverflow.com/users/850927", "pm_score": 5, "selected": false, "text": "formatters = {\n 'RED': '\\033[91m',\n 'GREEN': '\\033[92m',\n 'END': '\\033[0m',\n}\n\nprint 'Master is currently {RED}red{END}!'.format(**formatters)\nprint 'Help make master {GREEN}green{END} again!'.format(**formatters)\n" }, { "answer_id": 39452138, "author": "qubodup", "author_id": 188159, "author_profile": "https://Stackoverflow.com/users/188159", "pm_score": 8, "selected": false, "text": "CRED = '\\033[91m'\nCEND = '\\033[0m'\nprint(CRED + \"Error, does not compute!\" + CEND)\n urxvt \\33[5m \\33[6m CEND = '\\33[0m'\nCBOLD = '\\33[1m'\nCITALIC = '\\33[3m'\nCURL = '\\33[4m'\nCBLINK = '\\33[5m'\nCBLINK2 = '\\33[6m'\nCSELECTED = '\\33[7m'\n\nCBLACK = '\\33[30m'\nCRED = '\\33[31m'\nCGREEN = '\\33[32m'\nCYELLOW = '\\33[33m'\nCBLUE = '\\33[34m'\nCVIOLET = '\\33[35m'\nCBEIGE = '\\33[36m'\nCWHITE = '\\33[37m'\n\nCBLACKBG = '\\33[40m'\nCREDBG = '\\33[41m'\nCGREENBG = '\\33[42m'\nCYELLOWBG = '\\33[43m'\nCBLUEBG = '\\33[44m'\nCVIOLETBG = '\\33[45m'\nCBEIGEBG = '\\33[46m'\nCWHITEBG = '\\33[47m'\n\nCGREY = '\\33[90m'\nCRED2 = '\\33[91m'\nCGREEN2 = '\\33[92m'\nCYELLOW2 = '\\33[93m'\nCBLUE2 = '\\33[94m'\nCVIOLET2 = '\\33[95m'\nCBEIGE2 = '\\33[96m'\nCWHITE2 = '\\33[97m'\n\nCGREYBG = '\\33[100m'\nCREDBG2 = '\\33[101m'\nCGREENBG2 = '\\33[102m'\nCYELLOWBG2 = '\\33[103m'\nCBLUEBG2 = '\\33[104m'\nCVIOLETBG2 = '\\33[105m'\nCBEIGEBG2 = '\\33[106m'\nCWHITEBG2 = '\\33[107m'\n x = 0\nfor i in range(24):\n colors = \"\"\n for j in range(5):\n code = str(x+j)\n colors = colors + \"\\33[\" + code + \"m\\\\33[\" + code + \"m\\033[0m \"\n print(colors)\n x = x + 5\n" }, { "answer_id": 42528796, "author": "alvas", "author_id": 610569, "author_profile": "https://Stackoverflow.com/users/610569", "pm_score": 5, "selected": false, "text": "pip install -U lazyme from lazyme.string import color_print\n>>> color_print('abc')\nabc\n>>> color_print('abc', color='pink')\nabc\n>>> color_print('abc', color='red')\nabc\n>>> color_print('abc', color='yellow')\nabc\n>>> color_print('abc', color='green')\nabc\n>>> color_print('abc', color='blue', underline=True)\nabc\n>>> color_print('abc', color='blue', underline=True, bold=True)\nabc\n>>> color_print('abc', color='pink', underline=True, bold=True)\nabc\n color_print >>> from lazyme.string import palette, highlighter, formatter\n>>> from lazyme.string import color_print\n>>> palette.keys() # Available colors.\n['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']\n>>> highlighter.keys() # Available highlights.\n['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']\n>>> formatter.keys() # Available formatter,\n['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']\n italic fast blinking strikethrough >>> color_print('foo bar', color='pink', highlight='white')\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', reverse=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', bold=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', faint=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)\nfoo bar\n>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)\nfoo bar\n" }, { "answer_id": 48723332, "author": "Rotareti", "author_id": 1612318, "author_profile": "https://Stackoverflow.com/users/1612318", "pm_score": 7, "selected": false, "text": "sys.stdout from sty import fg, bg, ef, rs\n\nfoo = fg.red + 'This is red text!' + fg.rs\nbar = bg.blue + 'This has a blue background!' + bg.rs\nbaz = ef.italic + 'This is italic text' + rs.italic\nqux = fg(201) + 'This is pink text using 8bit colors' + fg.rs\nqui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs\n\n# Add custom colors:\n\nfrom sty import Style, RgbFg\n\nfg.orange = Style(RgbFg(255, 150, 50))\n\nbuf = fg.orange + 'Yay, Im orange.' + fg.rs\n\nprint(foo, bar, baz, qux, qui, buf, sep='\\n')\n" }, { "answer_id": 50025330, "author": "Andriy Makukha", "author_id": 5407270, "author_profile": "https://Stackoverflow.com/users/5407270", "pm_score": 6, "selected": false, "text": "# Pure Python 3.x demo, 256 colors\n# Works with bash under Linux and MacOS\n\nfg = lambda text, color: \"\\33[38;5;\" + str(color) + \"m\" + text + \"\\33[0m\"\nbg = lambda text, color: \"\\33[48;5;\" + str(color) + \"m\" + text + \"\\33[0m\"\n\ndef print_six(row, format, end=\"\\n\"):\n for col in range(6):\n color = row*6 + col - 2\n if color>=0:\n text = \"{:3d}\".format(color)\n print (format(text,color), end=\" \")\n else:\n print(end=\" \") # four spaces\n print(end=end)\n\nfor row in range(0, 43):\n print_six(row, fg, \" \")\n print_six(row, bg)\n\n# Simple usage: print(fg(\"text\", 160))\n" }, { "answer_id": 50447424, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 4, "selected": false, "text": "cprint termcolor %s, %d" }, { "answer_id": 52032616, "author": "Al Po", "author_id": 1224072, "author_profile": "https://Stackoverflow.com/users/1224072", "pm_score": 2, "selected": false, "text": "from contextlib import contextmanager\n# FORECOLOR\nBLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'\n# BACKGOUND\nBLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'\n\n@contextmanager\ndef printESC(prefix, color, text):\n print(\"{prefix}{color}{text}\".format(prefix=prefix, color=color, text=text), end='')\n yield\n print(\"{prefix}0m\".format(prefix=prefix))\n\nwith printESC('\\x1B[', REDFC, 'Colored Text'):\n pass\n # FORECOLOR\nBLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'\n# BACKGOUND\nBLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'\n\ndef printESC(prefix, color, text):\n print(\"{prefix}{color}{text}\".format(prefix=prefix, color=color, text=text), end='')\n print(\"{prefix}0m\".format(prefix=prefix))\n\nprintESC('\\x1B[', REDFC, 'Colored Text')\n" }, { "answer_id": 54955094, "author": "SimpleBinary", "author_id": 11073514, "author_profile": "https://Stackoverflow.com/users/11073514", "pm_score": 7, "selected": false, "text": "os.system(\"\") import os\n\n# System call\nos.system(\"\")\n\n# Class of different styles\nclass style():\n BLACK = '\\033[30m'\n RED = '\\033[31m'\n GREEN = '\\033[32m'\n YELLOW = '\\033[33m'\n BLUE = '\\033[34m'\n MAGENTA = '\\033[35m'\n CYAN = '\\033[36m'\n WHITE = '\\033[37m'\n UNDERLINE = '\\033[4m'\n RESET = '\\033[0m'\n\nprint(style.YELLOW + \"Hello, World!\")\n os.system(\"\")" }, { "answer_id": 58149095, "author": "Vishal", "author_id": 197473, "author_profile": "https://Stackoverflow.com/users/197473", "pm_score": 5, "selected": false, "text": "def black(text):\n print('\\033[30m', text, '\\033[0m', sep='')\n\ndef red(text):\n print('\\033[31m', text, '\\033[0m', sep='')\n\ndef green(text):\n print('\\033[32m', text, '\\033[0m', sep='')\n\ndef yellow(text):\n print('\\033[33m', text, '\\033[0m', sep='')\n\ndef blue(text):\n print('\\033[34m', text, '\\033[0m', sep='')\n\ndef magenta(text):\n print('\\033[35m', text, '\\033[0m', sep='')\n\ndef cyan(text):\n print('\\033[36m', text, '\\033[0m', sep='')\n\ndef gray(text):\n print('\\033[90m', text, '\\033[0m', sep='')\n\n\nblack(\"BLACK\")\nred(\"RED\")\ngreen(\"GREEN\")\nyellow(\"YELLOW\")\nblue(\"BLACK\")\nmagenta(\"MAGENTA\")\ncyan(\"CYAN\")\ngray(\"GRAY\")\n" }, { "answer_id": 59274139, "author": "hooman", "author_id": 12168946, "author_profile": "https://Stackoverflow.com/users/12168946", "pm_score": 2, "selected": false, "text": "Fore colorama from colorama import Fore, Style\n\nprint(Fore.MAGENTA + \"IZZ MAGENTA BRUH.\")\n\nprint(Style.RESET_ALL + \"IZZ BACK TO NORMALZ.\")\n print(\"\\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\\u001b[0m\")\n\nprint(\"BACK TO NORMALZ.\")\n" }, { "answer_id": 59582215, "author": "BeastCoder", "author_id": 10146757, "author_profile": "https://Stackoverflow.com/users/10146757", "pm_score": 5, "selected": false, "text": "from colorit import *\n\n# Use this to ensure that ColorIt will be usable by certain command line interfaces\n# Note: This clears the terminal\ninit_colorit()\n\n# Foreground\nprint(color(\"This text is red\", Colors.red))\nprint(color(\"This text is orange\", Colors.orange))\nprint(color(\"This text is yellow\", Colors.yellow))\nprint(color(\"This text is green\", Colors.green))\nprint(color(\"This text is blue\", Colors.blue))\nprint(color(\"This text is purple\", Colors.purple))\nprint(color(\"This text is white\", Colors.white))\n\n# Background\nprint(background(\"This text has a background that is red\", Colors.red))\nprint(background(\"This text has a background that is orange\", Colors.orange))\nprint(background(\"This text has a background that is yellow\", Colors.yellow))\nprint(background(\"This text has a background that is green\", Colors.green))\nprint(background(\"This text has a background that is blue\", Colors.blue))\nprint(background(\"This text has a background that is purple\", Colors.purple))\nprint(background(\"This text has a background that is white\", Colors.white))\n\n# Custom\nprint(color(\"This color has a custom grey text color\", (150, 150, 150)))\nprint(background(\"This color has a custom grey background\", (150, 150, 150)))\n\n# Combination\nprint(\n background(\n color(\"This text is blue with a white background\", Colors.blue), Colors.white\n )\n)\n\n# If you are using Windows Command Line, this is so that it doesn't close immediately\ninput()\n colorit pip install color-it pip3 install color-it" }, { "answer_id": 60252056, "author": "Gerry P", "author_id": 10798917, "author_profile": "https://Stackoverflow.com/users/10798917", "pm_score": 2, "selected": false, "text": "def print_in_color(txt_msg, fore_tuple, back_tuple, ):\n # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple\n # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)\n rf,bf,gf = fore_tuple\n rb,gb,bb = back_tuple\n msg = '{0}' + txt_msg\n mat = '\\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'\n print(msg .format(mat))\n print('\\33[0m') # Returns default print color to back to black\n\n# Example of use using a message with variables\nfore_color = 'cyan'\nback_color = 'dark green'\nmsg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)\nprint_in_color(msg, (0,255,255), (0,127,127))\n" }, { "answer_id": 61219634, "author": "Edgardo Obregón", "author_id": 12901164, "author_profile": "https://Stackoverflow.com/users/12901164", "pm_score": 3, "selected": false, "text": "from printy import printy\n\n# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text\nprinty(\"Hello, World!\", \"rBU\")\n\n# With inline formats, this will apply a dim (D)\n#blue (b) to the word 'Hello' and a stroken (S)\n#yellow (y) to the word 'world', and the rest will remain as the predefined format\nprinty(\"this is a [bD]Hello@ [yS]world@ text\")\n" }, { "answer_id": 61960902, "author": "CircuitSacul", "author_id": 13314450, "author_profile": "https://Stackoverflow.com/users/13314450", "pm_score": 6, "selected": false, "text": "def colored(r, g, b, text):\n return f\"\\033[38;2;{r};{g};{b}m{text}\\033[0m\"\n text = 'Hello, World!'\ncolored_text = colored(255, 0, 0, text)\nprint(colored_text)\n\n#or\n\nprint(colored(255, 0, 0, 'Hello, World!'))\n text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')\nprint(text)\n" }, { "answer_id": 62530462, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 3, "selected": false, "text": "console-color pip install console-color # cprint is something like below\n# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')\n# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.\n# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)\n\n# from console_color import RGB, Fore, Style, cprint, create_print\nfrom console_color import *\n\ncprint(\"Hello, World!\", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)\ncprint(\"Hello, World!\", fore=(255, 0, 0), bg=\"ffff00\", style=Style.BOLD+Style.URL+Style.STRIKE)\n f\"\\033[{target};2;{r};{g};{b}m{text}{style}\"" }, { "answer_id": 63551578, "author": "ijoseph", "author_id": 588437, "author_profile": "https://Stackoverflow.com/users/588437", "pm_score": 4, "selected": false, "text": "import click\n\nclick.secho('Hello, World!', fg='green')\nclick.secho('Some more text', bg='blue', fg='white')\nclick.secho('ATTENTION', blink=True, bold=True)\n click" }, { "answer_id": 64099955, "author": "Mojtaba Hosseini", "author_id": 5623035, "author_profile": "https://Stackoverflow.com/users/5623035", "pm_score": 4, "selected": false, "text": "⚠️ : error message\n: warning message\n: ok status message\n: action message\n: canceled status message\n: Or anything you like and want to recognize immediately by color\n\n" }, { "answer_id": 65088582, "author": "Will McGugan", "author_id": 673463, "author_profile": "https://Stackoverflow.com/users/673463", "pm_score": 6, "selected": false, "text": "from rich import print\nprint(\"[red]Color[/] in the [bold magenta]Terminal[/]!\")\n" }, { "answer_id": 65238905, "author": "prerakl123", "author_id": 13458018, "author_profile": "https://Stackoverflow.com/users/13458018", "pm_score": 2, "selected": false, "text": "fg = lambda text, color: \"\\33[38;5;\" + str(color) + \"m\" + text + \"\\33[0m\"\nbg = lambda text, color: \"\\33[48;5;\" + str(color) + \"m\" + text + \"\\33[0m\"\n\ndef print_six(row, format, end=\"\\n\"):\n for col in range(6):\n color = row*6 + col - 2\n if color>=0:\n text = \"{:3d}\".format(color)\n print (format(text,color), end=\" \")\n else:\n print(end=\" \") # Four spaces\n print(end=end)\n\nfor row in range(0, 43):\n print_six(row, fg, \" \")\n print_six(row, bg)\n\nprint(fg(\"text\", 160))\n\n def colored(r, g, b, text):\n return \"\\033[38;2;{};{};{}m{} \\033[38;2;255;255;255m\".format(r, g, b, text)\n\n\ntext = 'Hello, World!'\ncolored_text = colored(255, 0, 0, text)\nprint(colored_text)\n\n class Color:\n COLOR = [f\"\\33[{i}m\" for i in range(44)]\n\nfor i in range(44):\n print(Color.COLOR[i] + 'text')\n\n import os\nos.system('')\n os.system('')" }, { "answer_id": 65475628, "author": "Proud", "author_id": 13877426, "author_profile": "https://Stackoverflow.com/users/13877426", "pm_score": 2, "selected": false, "text": "print(\"\\033[1;32;40m Bright Green \\n\")\n" }, { "answer_id": 66780271, "author": "Benyamin Jafari - aGn", "author_id": 3702377, "author_profile": "https://Stackoverflow.com/users/3702377", "pm_score": 3, "selected": false, "text": "print() end= .store() # utility.py\n\nfrom datetime import datetime\n\nclass ColoredPrint:\n def __init__(self):\n self.PINK = '\\033[95m'\n self.OKBLUE = '\\033[94m'\n self.OKGREEN = '\\033[92m'\n self.WARNING = '\\033[93m'\n self.FAIL = '\\033[91m'\n self.ENDC = '\\033[0m'\n\n def disable(self):\n self.PINK = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n\n def store(self):\n date = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n with open('logfile.log', mode='a') as file_:\n file_.write(f\"{self.msg} -- {date}\")\n file_.write(\"\\n\")\n\n def success(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.OKGREEN + self.msg + self.ENDC, **kwargs)\n return self\n\n def info(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.OKBLUE + self.msg + self.ENDC, **kwargs)\n return self\n\n def warn(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.WARNING + self.msg + self.ENDC, **kwargs)\n return self\n\n def err(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.FAIL + self.msg + self.ENDC, **kwargs)\n return self\n\n def pink(self, *args, **kwargs):\n self.msg = ' '.join(map(str, args))\n print(self.PINK + self.msg + self.ENDC, **kwargs)\n return self\n from utility import ColoredPrint\n\nlog = ColoredPrint()\n\nlog.success(\"Hello\" , 123, \"Bye\").store()\nlog.info(\"Hello\" , 123, \"Bye\")\nlog.warn(\"Hello\" , 123, \"Bye\")\nlog.err(\"Hello\" , 123, \"Bye\").store()\nlog.pink(\"Hello\" , 123, \"Bye\")\n pip install python-colored-print\n" }, { "answer_id": 68132906, "author": "Life is complex", "author_id": 6083423, "author_profile": "https://Stackoverflow.com/users/6083423", "pm_score": 2, "selected": false, "text": "import random\nimport re as regex\nfrom rich import color\nfrom rich import print\n\n\ndef create_dynamic_regex(search_words):\n \"\"\"\n This function is used to create a dynamic regular expression\n string and a list of random colors. Both these elements will\n be used in the function colorize_text()\n\n :param search_words: list of search terms\n :return: regular expression search string and a list of colors\n :rtype: string, list\n \"\"\"\n colors_required = create_list_of_colors(len(search_words))\n number_of_search_words = len(search_words)\n combined_string = ''\n for search_word in search_words:\n number_of_search_words -= 1\n if number_of_search_words != 0:\n current_string = ''.join(r'(\\b' + search_word + r'\\b)|')\n combined_string = (combined_string + current_string)\n elif number_of_search_words == 0:\n current_string = ''.join(r'(\\b' + search_word + r'\\b)')\n combined_string = (combined_string + current_string)\n return combined_string, colors_required\n\n\ndef random_color():\n \"\"\"\n This function is used to create a random color using the\n Python package rich.\n :return: color name\n :rtype: string\n \"\"\"\n selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))\n return selected_color\n\n\ndef create_list_of_colors(number_of_colors):\n \"\"\"\n This function is used to generate a list of colors,\n which will be used in the function colorize_text()\n :param number_of_colors:\n :return: list of colors\n :rtype: list\n \"\"\"\n list_of_colors = [random_color() for _ in range(number_of_colors)]\n return list_of_colors\n\n\ndef colorize_text(text, regex_string, array_of_colors):\n \"\"\"\n This function is used to colorize specific words in a text string.\n :param text: text string potentially containing specific words to colorize.\n :param regex_string: regular expression search string\n :param array_of_colors: list of colors\n :return: colorized text\n :rtype: string\n \"\"\"\n available_colors = array_of_colors\n word_regex = regex.compile(f\"{regex_string}\", regex.IGNORECASE)\n i = 0\n output = \"\"\n for word in word_regex.finditer(text):\n get_color = available_colors[word.lastindex - 1]\n output += \"\".join([text[i:word.start()],\n \"[%s]\" % available_colors[word.lastindex - 1],\n text[word.start():word.end()], \"[/%s]\" % available_colors[word.lastindex - 1]])\n i = word.end()\n return ''.join([output, text[word.end():]])\n\n\ndef generate_console_output(text_to_search, words_to_find):\n \"\"\"\n This function is used generate colorized text that will\n be outputting to the console.\n\n :param text_to_search: text string potentially containing specific words to colorize.\n :param words_to_find: list of search terms.\n :return: A string containing colorized words.\n :rtype: string\n \"\"\"\n search_terms, colors = create_dynamic_regex(words_to_find)\n colorize_html = colorize_text(text_to_search, search_terms, colors)\n print(colorize_html)\n\n\ntext = \"The dog chased the cat that was looking for the mouse that the dog was playing with.\"\nwords = ['dog', 'cat', 'mouse']\ngenerate_console_output(text, words)\n" }, { "answer_id": 68748316, "author": "ToTamire", "author_id": 15964568, "author_profile": "https://Stackoverflow.com/users/15964568", "pm_score": 3, "selected": false, "text": "pip install coloredlogs\n import logging\nimport coloredlogs\n\ncoloredlogs.install() # install a handler on the root logger\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n import logging\nimport coloredlogs\n\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n import logging\nimport coloredlogs\n\nlogger = logging.getLogger(__name__) # get a specific logger object\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\ncoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n import logging\nimport coloredlogs\n\nlogger = logging.getLogger(__name__) # get a specific logger object\ncoloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug\ncoloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object\ncoloredlogs.install(\n level='DEBUG', logger=logger,\n fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'\n)\n\nlogging.debug('message with level debug')\nlogging.info('message with level info')\nlogging.warning('message with level warning')\nlogging.error('message with level error')\nlogging.critical('message with level critical')\n %(asctime)s %(created)f %(filename)s %(funcName)s %(hostname)s %(levelname)s %(levelno)s %(lineno)d %(message)s %(msg)s %(module)s %(msecs)d %(msg)s %(message)s %(name)s %(pathname)s %(process)d %(processName)s %(programname)s %(relativeCreated)d %(thread)d %(threadName)s %(username)s" }, { "answer_id": 69050278, "author": "Sylvester Kruin", "author_id": 16775594, "author_profile": "https://Stackoverflow.com/users/16775594", "pm_score": 2, "selected": false, "text": "pygments from pygments import console\nprint(pygments.console.colorize(\"red\", \"This text is red.\"))\n" }, { "answer_id": 70599663, "author": "Vinod Srivastav", "author_id": 3057246, "author_profile": "https://Stackoverflow.com/users/3057246", "pm_score": 3, "selected": false, "text": "import os\n\nos.system('')\n\n\ndef RGB(red=None, green=None, blue=None,bg=False):\n if(bg==False and red!=None and green!=None and blue!=None):\n return f'\\u001b[38;2;{red};{green};{blue}m'\n elif(bg==True and red!=None and green!=None and blue!=None):\n return f'\\u001b[48;2;{red};{green};{blue}m'\n elif(red==None and green==None and blue==None):\n return '\\u001b[0m'\n g0 = RGB()\ng1 = RGB(0,255,0)\ng2 = RGB(0,100,0,True)+\"\"+RGB(100,255,100)\ng3 = RGB(0,255,0,True)+\"\"+RGB(0,50,0)\n\nprint(f\"{g1}green1{g0}\")\nprint(f\"{g2}green2{g0}\")\nprint(f\"{g3}green3{g0}\")\n RGB() RGB(0,0,0) RGB(255,255,255) RGB(0,255,0) RGB(150,255,150) bg=True False RGB(255,0,0,True) RGB(255,0,0,False) bg False RGB(255,0,0)" }, { "answer_id": 72752520, "author": "Abhijeet", "author_id": 18522747, "author_profile": "https://Stackoverflow.com/users/18522747", "pm_score": 3, "selected": false, "text": "os.system('color') import os\nos.system('color')\n\nCOLOR = '\\033[91m' # change it, according to the color need\n\nEND = '\\033[0m'\n\nprint(COLOR + \"Hello World\" + END) #print a message\n\n\nexit=input() #to avoid closing the terminal windows\n" }, { "answer_id": 72768499, "author": "catwith", "author_id": 13651701, "author_profile": "https://Stackoverflow.com/users/13651701", "pm_score": 2, "selected": false, "text": "class log:\n f = lambda color: lambda string: print(color + string + \"\\33[0m\")\n\n black = f(\"\\33[30m\")\n red = f(\"\\33[31m\")\n green = f(\"\\33[32m\")\n yellow = f(\"\\33[33m\")\n blue = f(\"\\33[34m\")\n magenta = f(\"\\33[35m\")\n cyan = f(\"\\33[36m\")\n white = f(\"\\33[37m\")\n\n# Usage\nlog.blue(\"Blue World!\")\n" }, { "answer_id": 73036565, "author": "CPP_is_no_STANDARD", "author_id": 18032104, "author_profile": "https://Stackoverflow.com/users/18032104", "pm_score": 2, "selected": false, "text": "# Colours\npure_red = \"\\033[0;31m\"\ndark_green = \"\\033[0;32m\"\norange = \"\\033[0;33m\"\ndark_blue = \"\\033[0;34m\"\nbright_purple = \"\\033[0;35m\"\ndark_cyan = \"\\033[0;36m\"\ndull_white = \"\\033[0;37m\"\npure_black = \"\\033[0;30m\"\nbright_red = \"\\033[0;91m\"\nlight_green = \"\\033[0;92m\"\nyellow = \"\\033[0;93m\"\nbright_blue = \"\\033[0;94m\"\nmagenta = \"\\033[0;95m\"\nlight_cyan = \"\\033[0;96m\"\nbright_black = \"\\033[0;90m\"\nbright_white = \"\\033[0;97m\"\ncyan_back = \"\\033[0;46m\"\npurple_back = \"\\033[0;45m\"\nwhite_back = \"\\033[0;47m\"\nblue_back = \"\\033[0;44m\"\norange_back = \"\\033[0;43m\"\ngreen_back = \"\\033[0;42m\"\npink_back = \"\\033[0;41m\"\ngrey_back = \"\\033[0;40m\"\ngrey = '\\033[38;4;236m'\nbold = \"\\033[1m\"\nunderline = \"\\033[4m\"\nitalic = \"\\033[3m\"\ndarken = \"\\033[2m\"\ninvisible = '\\033[08m'\nreverse_colour = '\\033[07m'\nreset_colour = '\\033[0m'\ngrey = \"\\x1b[90m\"\n reverse_colour pink_back green_back reset_colour" }, { "answer_id": 73158800, "author": "Nazime Lakehal", "author_id": 7730121, "author_profile": "https://Stackoverflow.com/users/7730121", "pm_score": 0, "selected": false, "text": "pip install coloring import coloring\n\n# Directly use print-like functions\ncoloring.print_red('Hello', 12)\ncoloring.print_green('Hey', end=\"\", sep=\";\")\nprint()\n\n# Get str as return\nprint(coloring.red('hello'))\n\n# Use the generic colorize function\nprint(coloring.colorize(\"I'm red\", \"red\")) # Using color names\nprint(coloring.colorize(\"I'm green\", (0, 255, 0))) # Using RGB colors\nprint(coloring.colorize(\"I'm blue\", \"#0000ff\")) # Using hex colors\n\n# Or using styles (underline, bold, italic, ...)\nprint(coloring.colorize('Hello', 'red', s='ub')) # underline and bold\n\n" }, { "answer_id": 73917459, "author": "stackunderflow", "author_id": 1436741, "author_profile": "https://Stackoverflow.com/users/1436741", "pm_score": 2, "selected": false, "text": "def color_text(text, rgb):\n r, g, b = rgb\n return f\"\\033[38;2;{r};{g};{b}m{text}\\033[0m\"\n\nclass rgb():\n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n GREEN = (0, 255, 0)\n BLUE = (0, 0, 255)\n YELLOW = (255, 255, 0)\n # and so on ...\n\nprint(color_text(\"hello colored world\", rgb.GREEN))\n" }, { "answer_id": 74238803, "author": "BML", "author_id": 5531578, "author_profile": "https://Stackoverflow.com/users/5531578", "pm_score": 0, "selected": false, "text": "class ColorText:\n \"\"\"\n Use ANSI escape sequences to print colors +/- bold/underline to bash terminal.\n\n Examples\n --------\n >>> ColorText('HelloWorld').bold()\n >>> ColorText('HelloWorld').blue()\n >>> ColorText('HelloWorld').bold().custom(\"#bebebe\")\n >>> ColorText('HelloWorld').underline().custom('dodgerblue')\n >>> ColorText.demo()\n\n Notes\n -----\n - execute ColorText.demo() for a printout of colors.\n \"\"\"\n\n @classmethod\n def demo(cls):\n \"\"\"Prints examples of all colors in normal, bold, underline, bold+underline.\"\"\"\n for color in dir(ColorText):\n if all([color.startswith(\"_\") is False,\n color not in [\"bold\", \"underline\", \"demo\", \"custom\"],\n callable(getattr(ColorText, color))]):\n print(getattr(ColorText(color), color)(),\n \"\\t\",\n getattr(ColorText(f\"bold {color}\").bold(), color)(),\n \"\\t\",\n getattr(ColorText(f\"underline {color}\").underline(), color)(),\n \"\\t\",\n getattr(ColorText(f\"bold underline {color}\").underline().bold(), color)())\n print(ColorText(\"Input can also be color hex or R,G,B with ColorText.custom()\").bold())\n pass\n\n def __init__(self, text: str = \"\"):\n self.text = text\n self.ending = \"\\033[0m\"\n self.colors = []\n pass\n\n def __repr__(self):\n return self.text\n\n def __str__(self):\n return self.text\n\n def bold(self):\n self.text = \"\\033[1m\" + self.text + self.ending\n return self\n\n def underline(self):\n self.text = \"\\033[4m\" + self.text + self.ending\n return self\n\n def green(self):\n self.text = \"\\033[92m\" + self.text + self.ending\n self.colors.append(\"green\")\n return self\n\n def purple(self):\n self.text = \"\\033[95m\" + self.text + self.ending\n self.colors.append(\"purple\")\n return self\n\n def blue(self):\n self.text = \"\\033[94m\" + self.text + self.ending\n self.colors.append(\"blue\")\n return self\n\n def ltblue(self):\n self.text = \"\\033[34m\" + self.text + self.ending\n self.colors.append(\"lightblue\")\n return self\n\n def pink(self):\n self.text = \"\\033[35m\" + self.text + self.ending\n self.colors.append(\"pink\")\n return self\n\n def gray(self):\n self.text = \"\\033[30m\" + self.text + self.ending\n self.colors.append(\"gray\")\n return self\n\n def ltgray(self):\n self.text = \"\\033[37m\" + self.text + self.ending\n self.colors.append(\"ltgray\")\n return self\n\n def warn(self):\n self.text = \"\\033[93m\" + self.text + self.ending\n self.colors.append(\"yellow\")\n return self\n\n def fail(self):\n self.text = \"\\033[91m\" + self.text + self.ending\n self.colors.append(\"red\")\n return self\n\n def ltred(self):\n self.text = \"\\033[31m\" + self.text + self.ending\n self.colors.append(\"lightred\")\n return self\n\n def cyan(self):\n self.text = \"\\033[36m\" + self.text + self.ending\n self.colors.append(\"cyan\")\n return self\n\n def custom(self, *color_hex):\n \"\"\"Print in custom color, `color_hex` - either actual hex, or tuple(r,g,b)\"\"\"\n if color_hex != (None, ): # allows printing white on black background, black otherwise\n if len(color_hex) == 1:\n c = rgb2hex(colorConverter.to_rgb(color_hex[0]))\n rgb = ImageColor.getcolor(c, \"RGB\")\n else:\n assert (\n len(color_hex) == 3\n ), \"If not a color hex, ColorText.custom should have R,G,B as input\"\n rgb = color_hex\n self.text = \"\\033[{};2;{};{};{}m\".format(38, *rgb) + self.text + self.ending\n self.colors.append(rgb)\n return self\n\n pass\n" }, { "answer_id": 74439656, "author": "Tim", "author_id": 371122, "author_profile": "https://Stackoverflow.com/users/371122", "pm_score": 0, "selected": false, "text": "from stryle import Stryle\n\nprint(Stryle.okgreen.bold@\"Hello World\" + Stryle.underline@'!' + ' back to normal')\nprint(f\"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}\")\nprint(\"Merry \"@Stryle.red + \"Christmas\"@Stryle.okgreen.underline)\n _decorations = {\n \"header\" : '\\033[95m',\n \"okblue\" : '\\033[94m',\n \"okcyan\" : '\\033[96m',\n \"okgreen\" : '\\033[92m',\n \"yellow\" : '\\033[93m',\n \"red\" : '\\033[91m',\n \"warning\" : '\\033[93m',\n \"fail\" : '\\033[91m',\n \"off\" : '\\033[0m',\n \"bold\" : '\\033[1m',\n \"underline\" : '\\033[4m',\n}\n\nclass _StringStyle(str):\n def __getattribute__(self, decoration: str = _decorations[\"off\"]):\n if decoration in _decorations:\n return _StringStyle(self.decorations + _decorations[decoration])\n return self\n def __matmul__(self, other):\n return self.decorations + str(other) + _decorations[\"off\"]\n def __rmatmul__(self, other):\n return self.decorations + str(other) + _decorations[\"off\"]\n def __str__(self):\n return self.decorations\n\nStryle = _StringStyle()\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35062/" ]
287,875
<p>I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another. </p> <p>I've seen a model of testing for </p> <pre><code>$b.parents('nodename').length&gt;0 </code></pre> <p>Which is fantastic when you only need to check if an element is a child of any node by that name.</p> <p>But what about a specific node? You can't test</p> <pre><code>$b.parents($a).length&gt;0 </code></pre> <p>Because jQuery parents takes a nodename expression as an argument to filter.</p> <p>As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.</p> <p>Thanks!</p>
[ { "answer_id": 287889, "author": "picardo", "author_id": 32816, "author_profile": "https://Stackoverflow.com/users/32816", "pm_score": 2, "selected": false, "text": "$('#foo').filter(function(){\n\n return $(this).parent().is('#foo-parent');\n\n});\n $('#foo').filter(function(){\n\n return $(this).parents().is('#foo-parent');\n\n});\n" }, { "answer_id": 287923, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 5, "selected": true, "text": "if ($(obj1).parents().index($(obj2)) >= 0) {\n // obj1 is a descendant of obj2\n}\n" }, { "answer_id": 13588053, "author": "Alexey Lebedev", "author_id": 8338, "author_profile": "https://Stackoverflow.com/users/8338", "pm_score": 5, "selected": false, "text": "a.contains(b)\n a.contains(a) b contains" }, { "answer_id": 71885668, "author": "Rafael Atías", "author_id": 6951887, "author_profile": "https://Stackoverflow.com/users/6951887", "pm_score": 0, "selected": false, "text": "Node.contains Node.contains Element.children const sapiens = document.querySelector(\"#homo-sapiens\")\n\nconst isSapiensAnAustralopithecusDescendant = [\n ...document.querySelector(\"#australopithecus\").children\n].some(child => child?.contains(sapiens))\n\nconsole.log(isSapiensAnAustralopithecusDescendant) // true <div id=\"australopithecus\">\n <div id=\"homo-erectus\">\n <div id=\"homo-neanderthalensis\"></div>\n <div id=\"homo-sapiens\"></div>\n </div>\n</div> Node.contains Element.closest Element.closest document.body.closest(\"body\") document.body Element.closest null Element.closest const sapiens = document.querySelector(\"#homo-sapiens\");\n\nconst isAustralopithecusAnAncestorOfSapiens = sapiens.parentElement.closest(\"#australopithecus\")\n\nconsole.log(isAustralopithecusAnAncestorOfSapiens != null) // true <div id=\"australopithecus\">\n <div id=\"homo-erectus\">\n <div id=\"homo-neanderthalensis\"></div>\n <div id=\"homo-sapiens\"></div>\n </div>\n</div>" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37429/" ]
287,897
<p>I have a .NET 3.5 Web application on VS 2008 SP1 running on Vista Ultimate 32 SP1. I created an Application under the Default Web Site. So the url to the app is "<a href="http://localhost/mysite" rel="noreferrer">http://localhost/mysite</a>". The application folder is pointing to the solution folder and it is outside the iisroot folder. Anonymous and Integrated Auth (Windows) is enabled in IIS7 for this web application "mysite".</p> <p>I gave full permissions to "Network Service" user to the application folder (which is outside of iisroot).</p> <p>When I hit F5 to star debugging, I get the "Unable to start debugging on the web server. The web server could not find the requested resource." error.</p> <hr> <p>I fired up TcpView (Sysinternals) to see what app is actually running and keeping an handle on that port and I found out there is no app listening on that port. This is really weird... Any creative ideas?</p> <hr> <p>I can hit the URL "<a href="http://localhost/mysite" rel="noreferrer">http://localhost/mysite</a>" without a problem. That web application is set up to be the start up project and Default.aspx is the start up page.</p> <p>There is an .asmx service in the prject as well. The Default.aspx is making use of that asmx service. The AutoCompleteExtender (From the AJAX Control Toolkit) is using this asmx service.</p> <p>Everything works by the way. The issue is the debugging... I suspect the asmx service is causing this but i don't know. This is driving me nuts...</p>
[ { "answer_id": 13691092, "author": "Chuck Savage", "author_id": 353147, "author_profile": "https://Stackoverflow.com/users/353147", "pm_score": 5, "selected": false, "text": "Asp.Net 3.5 Asp.Net 4.5 IIS > WWW Service > Application Development Features" }, { "answer_id": 17152725, "author": "Ciaran", "author_id": 65765, "author_profile": "https://Stackoverflow.com/users/65765", "pm_score": 1, "selected": false, "text": "http://localhost/service" }, { "answer_id": 18974598, "author": "solo", "author_id": 1335665, "author_profile": "https://Stackoverflow.com/users/1335665", "pm_score": 2, "selected": false, "text": "systemroot\\Microsoft.NET\\Framework\\ versionNumber \\aspnet_regiis -i\n C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_regiis -i" }, { "answer_id": 30026437, "author": "Denis", "author_id": 758815, "author_profile": "https://Stackoverflow.com/users/758815", "pm_score": 0, "selected": false, "text": "<security>\n <requestFiltering>\n <hiddenSegments>\n <add segment=\"......\" />\n <add segment=\".....\" />\n ........\n </hiddenSegments>\n </requestFiltering>\n</security>\n" }, { "answer_id": 34412397, "author": "DomBat", "author_id": 54170, "author_profile": "https://Stackoverflow.com/users/54170", "pm_score": 1, "selected": false, "text": "<verbs allowUnlisted=\"false\">\n <add verb=\"GET\" allowed=\"true\" />\n <add verb=\"POST\" allowed=\"true\" />\n <add verb=\"DEBUG\" allowed=\"true\"/>\n</verbs>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35609/" ]
287,899
<p>Can anyone think of a good solution for getting IOC into a console application?</p> <p>At the moment we are just using a static class with the following method:</p> <pre><code>public static T Resolve&lt;T&gt;() { return dependencyResolver.Resolve&lt;T&gt;(); } </code></pre> <p>I would like the experience to be seamless but cannot think of a way of achieving this from a console application.</p>
[ { "answer_id": 433902, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 4, "selected": true, "text": "Resolve<T>() Main()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11755/" ]
287,903
<p>Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:</p> <pre class="lang-js prettyprint-override"><code>my.namespace.ColorEnum = { RED : 0, GREEN : 1, BLUE : 2 } // later on if(currentColor == my.namespace.ColorEnum.RED) { // whatever } </code></pre> <p>Or is there some other way I can do this?</p>
[ { "answer_id": 1314191, "author": "Randolpho", "author_id": 12716, "author_profile": "https://Stackoverflow.com/users/12716", "pm_score": 7, "selected": false, "text": "var DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\n\nDocument.Write(\"Enumerant: \" + DaysEnum.tuesday);\n DaysEnum.monday = 4; // whoops, monday is now thursday, too\n Object.freeze Object.freeze" }, { "answer_id": 2383215, "author": "Stijn de Witt", "author_id": 286685, "author_profile": "https://Stackoverflow.com/users/286685", "pm_score": 9, "selected": false, "text": "if (currentColor == my.namespace.ColorEnum.RED) {\n // alert name of currentColor (RED: 0)\n var col = my.namespace.ColorEnum;\n for (var name in col) {\n if (col[name] == col.RED)\n alert(name);\n }\n}\n var SIZE = {\n SMALL : {value: 0, name: \"Small\", code: \"S\"}, \n MEDIUM: {value: 1, name: \"Medium\", code: \"M\"}, \n LARGE : {value: 2, name: \"Large\", code: \"L\"}\n};\n\nvar currentSize = SIZE.MEDIUM;\nif (currentSize == SIZE.MEDIUM) {\n // this alerts: \"1: Medium\"\n alert(currentSize.value + \": \" + currentSize.name);\n}\n // Add EXTRALARGE size\nSIZE.EXTRALARGE = {value: 3, name: \"Extra Large\", code: \"XL\"};\n // Add 'Extra Large' size, only knowing it's name\nvar name = \"Extra Large\";\nSIZE[name] = {value: -1, name: name, code: \"?\"};\n for (var sz in SIZE) {\n // sz will be the names of the objects in SIZE, so\n // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'\n var size = SIZE[sz]; // Get the object mapped to the name in sz\n for (var prop in size) {\n // Get all the properties of the size object, iterates over\n // 'value', 'name' and 'code'. You can inspect everything this way. \n }\n} \n" }, { "answer_id": 5040502, "author": "Artur Czajka", "author_id": 572370, "author_profile": "https://Stackoverflow.com/users/572370", "pm_score": 11, "selected": true, "text": "const DaysEnum = Object.freeze({\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...})\n const DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\nObject.freeze(DaysEnum)\n let day = DaysEnum.tuesday\nday = 298832342 // goes through without any errors\n" }, { "answer_id": 6672823, "author": "Andre 'Fi'", "author_id": 841793, "author_profile": "https://Stackoverflow.com/users/841793", "pm_score": 6, "selected": false, "text": "function Enum(constantsList) {\n for (var i in constantsList) {\n this[constantsList[i]] = i;\n }\n}\n var YesNo = new Enum(['NO', 'YES']);\nvar Color = new Enum(['RED', 'GREEN', 'BLUE']);\n Enum.prototype.values = function() {\n return this.allValues;\n /* for the above to work, you'd need to do\n this.allValues = constantsList at the constructor */\n};\n function Enum() {\n for (var i in arguments) {\n this[arguments[i]] = i;\n }\n}\n\nvar YesNo = new Enum('NO', 'YES');\nvar Color = new Enum('RED', 'GREEN', 'BLUE');\n" }, { "answer_id": 10299613, "author": "Yaroslav", "author_id": 1351319, "author_profile": "https://Stackoverflow.com/users/1351319", "pm_score": 4, "selected": false, "text": "// enum instance members, optional\nvar Color = Backbone.Model.extend({\n print : function() {\n console.log(\"I am \" + this.get(\"name\"))\n }\n});\n\n// enum creation\nvar Colors = new Backbone.Collection([\n { id : 1, name : \"Red\", rgb : 0xFF0000},\n { id : 2, name : \"Green\" , rgb : 0x00FF00},\n { id : 3, name : \"Blue\" , rgb : 0x0000FF}\n], {\n model : Color\n});\n\n// Expose members through public fields.\nColors.each(function(color) {\n Colors[color.get(\"name\")] = color;\n});\n\n// using\nColors.Red.print()\n" }, { "answer_id": 10597813, "author": "Chris", "author_id": 1395768, "author_profile": "https://Stackoverflow.com/users/1395768", "pm_score": 4, "selected": false, "text": "function Enum() {\n this._enums = [];\n this._lookups = {};\n}\n\nEnum.prototype.getEnums = function() {\n return _enums;\n}\n\nEnum.prototype.forEach = function(callback){\n var length = this._enums.length;\n for (var i = 0; i < length; ++i){\n callback(this._enums[i]);\n }\n}\n\nEnum.prototype.addEnum = function(e) {\n this._enums.push(e);\n}\n\nEnum.prototype.getByName = function(name) {\n return this[name];\n}\n\nEnum.prototype.getByValue = function(field, value) {\n var lookup = this._lookups[field];\n if(lookup) {\n return lookup[value];\n } else {\n this._lookups[field] = ( lookup = {});\n var k = this._enums.length - 1;\n for(; k >= 0; --k) {\n var m = this._enums[k];\n var j = m[field];\n lookup[j] = m;\n if(j == value) {\n return m;\n }\n }\n }\n return null;\n}\n\nfunction defineEnum(definition) {\n var k;\n var e = new Enum();\n for(k in definition) {\n var j = definition[k];\n e[k] = j;\n e.addEnum(j)\n }\n return e;\n}\n var COLORS = defineEnum({\n RED : {\n value : 1,\n string : 'red'\n },\n GREEN : {\n value : 2,\n string : 'green'\n },\n BLUE : {\n value : 3,\n string : 'blue'\n }\n});\n COLORS.BLUE.string\nCOLORS.BLUE.value\nCOLORS.getByName('BLUE').string\nCOLORS.getByValue('value', 1).string\n\nCOLORS.forEach(function(e){\n // do what you want with e\n});\n" }, { "answer_id": 15948460, "author": "David Miró", "author_id": 2270217, "author_profile": "https://Stackoverflow.com/users/2270217", "pm_score": 3, "selected": false, "text": " function Enum() {\n var that = this;\n for (var i in arguments) {\n that[arguments[i]] = i;\n }\n this.name = function(value) {\n for (var key in that) {\n if (that[key] == value) {\n return key;\n }\n }\n };\n this.exist = function(value) {\n return (typeof that.name(value) !== \"undefined\");\n };\n if (Object.freeze) {\n Object.freeze(that);\n }\n }\n var Color = new Enum('RED', 'GREEN', 'BLUE');\nundefined\nColor.name(Color.REDs)\nundefined\nColor.name(Color.RED)\n\"RED\"\nColor.exist(Color.REDs)\nfalse\nColor.exist(Color.RED)\ntrue\n" }, { "answer_id": 17280078, "author": "Rob Hardy", "author_id": 1733091, "author_profile": "https://Stackoverflow.com/users/1733091", "pm_score": 4, "selected": false, "text": "var MyEnum;\n(function (MyEnum) {\n MyEnum[MyEnum[\"Foo\"] = 0] = \"Foo\";\n MyEnum[MyEnum[\"FooBar\"] = 2] = \"FooBar\";\n MyEnum[MyEnum[\"Bar\"] = 1] = \"Bar\";\n})(MyEnum|| (MyEnum= {}));\n MyEnum.Bar MyEnum[1]" }, { "answer_id": 18355123, "author": "Duncan", "author_id": 945011, "author_profile": "https://Stackoverflow.com/users/945011", "pm_score": 5, "selected": false, "text": "Object.defineProperty Object.defineProperty(Object.prototype,'Enum', {\n value: function() {\n for(i in arguments) {\n Object.defineProperty(this,arguments[i], {\n value:parseInt(i),\n writable:false,\n enumerable:true,\n configurable:true\n });\n }\n return this;\n },\n writable:false,\n enumerable:false,\n configurable:false\n}); \n writable:false Enum() var EnumColors={};\nEnumColors.Enum('RED','BLUE','GREEN','YELLOW');\nEnumColors.RED; // == 0\nEnumColors.BLUE; // == 1\nEnumColors.GREEN; // == 2\nEnumColors.YELLOW; // == 3\n" }, { "answer_id": 19034005, "author": "GTF", "author_id": 907981, "author_profile": "https://Stackoverflow.com/users/907981", "pm_score": 2, "selected": false, "text": "__defineGetter__ __defineSetter__ defineProperty var Colours = Enum('RED', 'GREEN', 'BLUE');\n" }, { "answer_id": 19112051, "author": "user2254487", "author_id": 2254487, "author_profile": "https://Stackoverflow.com/users/2254487", "pm_score": 2, "selected": false, "text": "var Colors = function(){\nreturn {\n 'WHITE':0,\n 'BLACK':1,\n 'RED':2,\n 'GREEN':3\n }\n}();\n\nconsole.log(Colors.WHITE) //this prints out \"0\"\n" }, { "answer_id": 23455550, "author": "arcseldon", "author_id": 1882064, "author_profile": "https://Stackoverflow.com/users/1882064", "pm_score": 2, "selected": false, "text": "_ = require('underscore');\n\nvar _Enum = function () {\n\n var keys = _.map(arguments, function (value) {\n return value;\n });\n var self = {\n keys: keys\n };\n for (var i = 0; i < arguments.length; i++) {\n self[keys[i]] = i;\n }\n return self;\n};\n\nvar fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));\nvar encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));\n\nexports.fileFormatEnum = fileFormatEnum;\nexports.encodingEnum = encodingEnum;\n var chai = require(\"chai\"),\n assert = chai.assert,\n expect = chai.expect,\n should = chai.should(),\n enums = require('./enums'),\n _ = require('underscore');\n\n\ndescribe('enums', function () {\n\n describe('fileFormatEnum', function () {\n it('should return expected fileFormat enum declarations', function () {\n var fileFormatEnum = enums.fileFormatEnum;\n should.exist(fileFormatEnum);\n assert('{\"keys\":[\"CSV\",\"TSV\"],\"CSV\":0,\"TSV\":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');\n assert('[\"CSV\",\"TSV\"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');\n });\n });\n\n describe('encodingEnum', function () {\n it('should return expected encoding enum declarations', function () {\n var encodingEnum = enums.encodingEnum;\n should.exist(encodingEnum);\n assert('{\"keys\":[\"UTF8\",\"SHIFT_JIS\"],\"UTF8\":0,\"SHIFT_JIS\":1}' === JSON.stringify(encodingEnum), 'Unexpected format');\n assert('[\"UTF8\",\"SHIFT_JIS\"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');\n });\n });\n\n});\n" }, { "answer_id": 23669178, "author": "Xeltor", "author_id": 1330674, "author_profile": "https://Stackoverflow.com/users/1330674", "pm_score": 3, "selected": false, "text": "var buildSet = function(array) {\n var set = {};\n for (var i in array) {\n var item = array[i];\n set[item] = item;\n }\n return set;\n}\n\nvar myEnum = buildSet(['RED','GREEN','BLUE']);\n// myEnum.RED == 'RED' ...etc\n" }, { "answer_id": 25692451, "author": "Andrew Philips", "author_id": 314114, "author_profile": "https://Stackoverflow.com/users/314114", "pm_score": 1, "selected": false, "text": "function mkenum_1()\n{\n var o = new Object();\n var c = -1;\n var f = function(e, v) { Object.defineProperty(o, e, { value:v, writable:false, enumerable:true, configurable:true })};\n\n for (i in arguments) {\n var e = arguments[i];\n if ((!!e) & (e.constructor == Object))\n for (j in e)\n f(j, (c=e[j]));\n else\n f(e, ++c);\n }\n\n return Object.freeze ? Object.freeze(o) : o;\n}\n\nvar Sizes = mkenum_1('SMALL','MEDIUM',{LARGE: 100},'XLARGE');\n\nconsole.log(\"MED := \" + Sizes.MEDIUM);\nconsole.log(\"LRG := \" + Sizes.LARGE);\n\n// Output is:\n// MED := 1\n// LRG := 100\n function mkenum_2(seed)\n{\n var p = {};\n\n console.log(\"Seed := \" + seed);\n\n for (k in seed) {\n var v = seed[k];\n\n if (v instanceof Array)\n p[(seed[k]=v[0])] = { value: v[0], name: v[1], code: v[2] };\n else\n p[v] = { value: v, name: k.toLowerCase(), code: k.substring(0,1) };\n }\n seed.properties = p;\n\n return Object.freeze ? Object.freeze(seed) : seed;\n}\n var SizeEnum2 = mkenum_2({ SMALL: 1, MEDIUM: 2, LARGE: 3});\nvar SizeEnum3 = mkenum_2({ SMALL: [1, \"small\", \"S\"], MEDIUM: [2, \"medium\", \"M\"], LARGE: [3, \"large\", \"L\"] });\n" }, { "answer_id": 28205581, "author": "Shivanshu Goyal", "author_id": 1544818, "author_profile": "https://Stackoverflow.com/users/1544818", "pm_score": 3, "selected": false, "text": "var ColorEnum = {\n red: {},\n green: {},\n blue: {}\n}\n" }, { "answer_id": 28526471, "author": "Gildas.Tambo", "author_id": 2065597, "author_profile": "https://Stackoverflow.com/users/2065597", "pm_score": 1, "selected": false, "text": "var findInEnum,\n colorEnum = {\n red : 0,\n green : 1,\n blue : 2\n};\n\n// later on\n\nfindInEnum = function (enumKey) {\n if (colorEnum.hasOwnProperty(enumKey)) {\n return enumKey+' Value: ' + colorEnum[enumKey]\n }\n}\n\nalert(findInEnum(\"blue\"))" }, { "answer_id": 29074825, "author": "Blake Bowen", "author_id": 2760155, "author_profile": "https://Stackoverflow.com/users/2760155", "pm_score": 2, "selected": false, "text": "function _enum(list) { \n for (var key in list) {\n list[list[key] = list[key]] = key;\n }\n return Object.freeze(list);\n}\n\nvar Color = _enum({\n Red: 0,\n Green: 5,\n Blue: 2\n});\n\n// Color → {0: \"Red\", 2: \"Blue\", 5: \"Green\", \"Red\": 0, \"Green\": 5, \"Blue\": 2}\n// Color.Red → 0\n// Color.Green → 5\n// Color.Blue → 2\n// Color[5] → Green\n// Color.Blue > Color.Green → false\n function enum() {\n var key, val = -1, list = {};\n _.reduce(_.toArray(arguments), function(result, kvp) { \n kvp = kvp.split(\"=\");\n key = _.trim(kvp[0]);\n val = _.parseInt(kvp[1]) || ++val; \n result[result[val] = key] = val;\n return result;\n }, list);\n return Object.freeze(list);\n} \n\n// Add enum to lodash \n_.mixin({ \"enum\": enum });\n\nvar Color = _.enum(\n \"Red\",\n \"Green\",\n \"Blue = 5\",\n \"Yellow\",\n \"Purple = 20\",\n \"Gray\"\n);\n\n// Color.Red → 0\n// Color.Green → 1\n// Color.Blue → 5\n// Color.Yellow → 6\n// Color.Purple → 20\n// Color.Gray → 21\n// Color[5] → Blue\n" }, { "answer_id": 29094597, "author": "Tschallacka", "author_id": 1356107, "author_profile": "https://Stackoverflow.com/users/1356107", "pm_score": 1, "selected": false, "text": "if(something instanceof enum) if(somevar instanceof EnumFieldSegment) /**\n * simple parameter object instantiator\n * @param name\n * @param value\n * @returns\n */\nfunction p(name,value) {\n this.name = name;\n this.value = value;\n return Object.freeze(this);\n}\n/**\n * EnumFieldSegmentBase\n */\nfunction EnumFieldSegmentBase() {\n this.fieldType = \"STRING\";\n}\nfunction dummyregex() {\n}\ndummyregex.prototype.test = function(str) {\n if(this.fieldType === \"STRING\") {\n maxlength = arguments[1];\n return str.length <= maxlength;\n }\n return true;\n};\n\ndummyregexposer = new dummyregex();\nEnumFieldSegmentBase.prototype.getInputRegex = function() { \n switch(this.fieldType) {\n case \"STRING\" : return dummyregexposer; \n case \"INT\": return /^(\\d+)?$/;\n case \"DECIMAL2\": return /^\\d+(\\.\\d{1,2}|\\d+|\\.)?$/;\n case \"DECIMAL8\": return /^\\d+(\\.\\d{1,8}|\\d+|\\.)?$/;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": return dummyregexposer;\n }\n};\nEnumFieldSegmentBase.prototype.convertToType = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\" : val = $input;break;\n case \"INT\": val==\"\"? val=0 :val = parseInt($input);break;\n case \"DECIMAL2\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal2($input).toDP(2);break;\n case \"DECIMAL8\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal8($input).toDP(8);break;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": val = (typeof $input == 'boolean' ? $input : (typeof $input === 'string' ? (($input === \"false\" || $input === \"\" || $input === \"0\") ? false : true) : new Boolean($input).valueOf())) ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.convertToString = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\": val = $input;break;\n case \"INT\": val = $input+\"\";break;\n case \"DECIMAL2\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+2 : $input.toString().indexOf('.')+2)) ;break;\n case \"DECIMAL8\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+8 : $input.toString().indexOf('.')+8)) ;break;\n case \"BOOLEAN\": val = $input ? \"true\" : \"false\" ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.compareValue = function($val1,$val2) {\n var val = false;\n switch(this.fieldType) {\n case \"STRING\": val = ($val1===$val2);break;\n case \"INT\": val = ($val1===$val2);break;\n case \"DECIMAL2\": val = ($val1.comparedTo($val2)===0);break;\n case \"DECIMAL8\": val = ($val1.comparedTo($val2)===0);break;\n case \"BOOLEAN\": val = ($val1===$val2);break;\n }\n return val;\n};\n\n/**\n * EnumFieldSegment is an individual segment in the \n * EnumField\n * @param $array An array consisting of object p\n */\nfunction EnumFieldSegment() {\n for(c=0;c<arguments.length;c++) {\n if(arguments[c] instanceof p) {\n this[arguments[c].name] = arguments[c].value;\n }\n }\n return Object.freeze(this); \n}\nEnumFieldSegment.prototype = new EnumFieldSegmentBase();\nEnumFieldSegment.prototype.constructor = EnumFieldSegment;\n\n\n/**\n * Simple enum to show what type of variable a Field type is.\n * @param STRING\n * @param INT\n * @param DECIMAL2\n * @param DECIMAL8\n * @param BOOLEAN\n * \n */\nEnumField = Object.freeze({STRING: new EnumFieldSegment(new p(\"fieldType\",\"STRING\")), \n INT: new EnumFieldSegment(new p(\"fieldType\",\"INT\")), \n DECIMAL2: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL2\")), \n DECIMAL8: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL8\")), \n BOOLEAN: new EnumFieldSegment(new p(\"fieldType\",\"BOOLEAN\"))});\n" }, { "answer_id": 29894175, "author": "Gelin Luo", "author_id": 391227, "author_profile": "https://Stackoverflow.com/users/391227", "pm_score": 2, "selected": false, "text": "var genEnum = require('gen_enum');\n\nvar AppMode = genEnum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n gen_enum gen_enum constjs var genEnum = require('gen_enum');\n var genEnum = require('constjs').enum;\n" }, { "answer_id": 30045582, "author": "Pylinux", "author_id": 1465640, "author_profile": "https://Stackoverflow.com/users/1465640", "pm_score": 0, "selected": false, "text": "var DaysEnum = Object.freeze ({ monday: {}, tuesday: {}, ... });\n if (incommingEnum === DaysEnum.monday) //incommingEnum is monday\n" }, { "answer_id": 30058506, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 6, "selected": false, "text": "Symbol() != Symbol() const COLOR = Object.freeze({RED: Symbol(), BLUE: Symbol()});\n const COLOR = Object.freeze({RED: Symbol(\"RED\"), BLUE: Symbol(\"BLUE\")});\n const color = new Enum(\"RED\", \"BLUE\")\n\ncolor.RED.toString() // Symbol(RED)\ncolor.getName(color.RED) // RED\ncolor.size // 2\ncolor.values() // Symbol(RED), Symbol(BLUE)\ncolor.toString() // RED,BLUE\n" }, { "answer_id": 31185447, "author": "Manohar Reddy Poreddy", "author_id": 984471, "author_profile": "https://Stackoverflow.com/users/984471", "pm_score": 3, "selected": false, "text": "var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n var CONST_WILD_TYPES = {\n REGULAR: 'RE',\n EXPANDING: 'EX',\n STICKY: 'ST',\n SHIFTING: 'SH'\n};\n var CONST_WILD_TYPES = {\n REGULAR: '1',\n EXPANDING: '2',\n STICKY: '3',\n SHIFTING: '4'\n};\n var wildType = CONST_WILD_TYPES.REGULAR;\n if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n" }, { "answer_id": 31636748, "author": "hvdd", "author_id": 2326407, "author_profile": "https://Stackoverflow.com/users/2326407", "pm_score": 4, "selected": false, "text": "const Modes = {\n DRAGGING: 'drag',\n SCALING: 'scale',\n CLICKED: 'click'\n};\n" }, { "answer_id": 32245965, "author": "Sherali Turdiyev", "author_id": 4365315, "author_profile": "https://Stackoverflow.com/users/4365315", "pm_score": 2, "selected": false, "text": "var A = {a:11, b:22}, \nenumA = new TypeHelper(A);\n\nif(enumA.Value === A.b || enumA.Key === \"a\"){ \n... \n}\n\nvar keys = enumA.getAsList();//[object, object]\n\n//set\nenumA.setType(22, false);//setType(val, isKey)\n\nenumA.setType(\"a\", true);\n\nenumA.setTypeByIndex(1);\n TypeHelper var Helper = {\n isEmpty: function (obj) {\n return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;\n },\n\n isObject: function (obj) {\n return (typeof obj === 'object');\n },\n\n sortObjectKeys: function (object) {\n return Object.keys(object)\n .sort(function (a, b) {\n c = a - b;\n return c\n });\n },\n containsItem: function (arr, item) {\n if (arr && Array.isArray(arr)) {\n return arr.indexOf(item) > -1;\n } else {\n return arr === item;\n }\n },\n\n pushArray: function (arr1, arr2) {\n if (arr1 && arr2 && Array.isArray(arr1)) {\n arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);\n }\n }\n};\nfunction TypeHelper() {\n var _types = arguments[0],\n _defTypeIndex = 0,\n _currentType,\n _value,\n _allKeys = Helper.sortObjectKeys(_types);\n\n if (arguments.length == 2) {\n _defTypeIndex = arguments[1];\n }\n\n Object.defineProperties(this, {\n Key: {\n get: function () {\n return _currentType;\n },\n set: function (val) {\n _currentType.setType(val, true);\n },\n enumerable: true\n },\n Value: {\n get: function () {\n return _types[_currentType];\n },\n set: function (val) {\n _value.setType(val, false);\n },\n enumerable: true\n }\n });\n this.getAsList = function (keys) {\n var list = [];\n _allKeys.forEach(function (key, idx, array) {\n if (key && _types[key]) {\n\n if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {\n var json = {};\n json.Key = key;\n json.Value = _types[key];\n Helper.pushArray(list, json);\n }\n }\n });\n return list;\n };\n\n this.setType = function (value, isKey) {\n if (!Helper.isEmpty(value)) {\n Object.keys(_types).forEach(function (key, idx, array) {\n if (Helper.isObject(value)) {\n if (value && value.Key == key) {\n _currentType = key;\n }\n } else if (isKey) {\n if (value && value.toString() == key.toString()) {\n _currentType = key;\n }\n } else if (value && value.toString() == _types[key]) {\n _currentType = key;\n }\n });\n } else {\n this.setDefaultType();\n }\n return isKey ? _types[_currentType] : _currentType;\n };\n\n this.setTypeByIndex = function (index) {\n for (var i = 0; i < _allKeys.length; i++) {\n if (index === i) {\n _currentType = _allKeys[index];\n break;\n }\n }\n };\n\n this.setDefaultType = function () {\n this.setTypeByIndex(_defTypeIndex);\n };\n\n this.setDefaultType();\n}\n\nvar TypeA = {\n \"-1\": \"Any\",\n \"2\": \"2L\",\n \"100\": \"100L\",\n \"200\": \"200L\",\n \"1000\": \"1000L\"\n};\n\nvar enumA = new TypeHelper(TypeA, 4);\n\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\n\nenumA.setType(\"200L\", false);\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\nenumA.setDefaultType();\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\n\nenumA.setTypeByIndex(1);\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\ndocument.writeln(\"is equals = \", (enumA.Value == TypeA[\"2\"]));" }, { "answer_id": 32658453, "author": "Vivin Paliath", "author_id": 263004, "author_profile": "https://Stackoverflow.com/users/263004", "pm_score": 3, "selected": false, "text": "instanceof var Days = Enum.define(\"Days\", [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]);\n Days Days Days.Monday instanceof Days; // true\n\nDays.Friday.name(); // \"Friday\"\nDays.Friday.ordinal(); // 4\n\nDays.Sunday === Days.Sunday; // true\nDays.Sunday === Days.Friday; // false\n\nDays.Sunday.toString(); // \"Sunday\"\n\nDays.toString() // \"Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } \"\n\nDays.values().map(function(e) { return e.name(); }); //[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\nDays.values()[4].name(); //\"Friday\"\n\nDays.fromName(\"Thursday\") === Days.Thursday // true\nDays.fromName(\"Wednesday\").name() // \"Wednesday\"\nDays.Friday.fromName(\"Saturday\").name() // \"Saturday\"\n var Enum = (function () {\n /**\n * Function to define an enum\n * @param typeName - The name of the enum.\n * @param constants - The constants on the enum. Can be an array of strings, or an object where each key is an enum\n * constant, and the values are objects that describe attributes that can be attached to the associated constant.\n */\n function define(typeName, constants) {\n\n /** Check Arguments **/\n if (typeof typeName === \"undefined\") {\n throw new TypeError(\"A name is required.\");\n }\n\n if (!(constants instanceof Array) && (Object.getPrototypeOf(constants) !== Object.prototype)) {\n\n throw new TypeError(\"The constants parameter must either be an array or an object.\");\n\n } else if ((constants instanceof Array) && constants.length === 0) {\n\n throw new TypeError(\"Need to provide at least one constant.\");\n\n } else if ((constants instanceof Array) && !constants.reduce(function (isString, element) {\n return isString && (typeof element === \"string\");\n }, true)) {\n\n throw new TypeError(\"One or more elements in the constant array is not a string.\");\n\n } else if (Object.getPrototypeOf(constants) === Object.prototype && !Object.keys(constants).reduce(function (isObject, constant) {\n return Object.getPrototypeOf(constants[constant]) === Object.prototype;\n }, true)) {\n\n throw new TypeError(\"One or more constants do not have an associated object-value.\");\n\n }\n\n var isArray = (constants instanceof Array);\n var isObject = !isArray;\n\n /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/\n function __() { };\n\n /** Dynamically define a function with the same name as the enum we want to define. **/\n var __enum = new Function([\"__\"],\n \"return function \" + typeName + \"(sentinel, name, ordinal) {\" +\n \"if(!(sentinel instanceof __)) {\" +\n \"throw new TypeError(\\\"Cannot instantiate an instance of \" + typeName + \".\\\");\" +\n \"}\" +\n\n \"this.__name = name;\" +\n \"this.__ordinal = ordinal;\" +\n \"}\"\n )(__);\n\n /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/\n var __values = [];\n var __dict = {};\n\n /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/\n Object.defineProperty(__enum, \"values\", {\n value: function () {\n return __values;\n }\n });\n\n Object.defineProperty(__enum, \"fromName\", {\n value: function (name) {\n var __constant = __dict[name]\n if (__constant) {\n return __constant;\n } else {\n throw new TypeError(typeName + \" does not have a constant with name \" + name + \".\");\n }\n }\n });\n\n /**\n * The following methods are available to all instances of the enum. values() and fromName() need to be\n * available to each constant, and so we will attach them on the prototype. But really, they're just\n * aliases to their counterparts on the prototype.\n */\n Object.defineProperty(__enum.prototype, \"values\", {\n value: __enum.values\n });\n\n Object.defineProperty(__enum.prototype, \"fromName\", {\n value: __enum.fromName\n });\n\n Object.defineProperty(__enum.prototype, \"name\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"ordinal\", {\n value: function () {\n return this.__ordinal;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"valueOf\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"toString\", {\n value: function () {\n return this.__name;\n }\n });\n\n /**\n * If constants was an array, we can the element values directly. Otherwise, we will have to use the keys\n * from the constants object.\n */\n var _constants = constants;\n if (isObject) {\n _constants = Object.keys(constants);\n }\n\n /** Iterate over all constants, create an instance of our enum for each one, and attach it to the enum type **/\n _constants.forEach(function (name, ordinal) {\n // Create an instance of the enum\n var __constant = new __enum(new __(), name, ordinal);\n\n // If constants was an object, we want to attach the provided attributes to the instance.\n if (isObject) {\n Object.keys(constants[name]).forEach(function (attr) {\n Object.defineProperty(__constant, attr, {\n value: constants[name][attr]\n });\n });\n }\n\n // Freeze the instance so that it cannot be modified.\n Object.freeze(__constant);\n\n // Attach the instance using the provided name to the enum type itself.\n Object.defineProperty(__enum, name, {\n value: __constant\n });\n\n // Update our private objects\n __values.push(__constant);\n __dict[name] = __constant;\n });\n\n /** Define a friendly toString method for the enum **/\n var string = typeName + \" { \" + __enum.values().map(function (c) {\n return c.name();\n }).join(\", \") + \" } \";\n\n Object.defineProperty(__enum, \"toString\", {\n value: function () {\n return string;\n }\n });\n\n /** Freeze our private objects **/\n Object.freeze(__values);\n Object.freeze(__dict);\n\n /** Freeze the prototype on the enum and the enum itself **/\n Object.freeze(__enum.prototype);\n Object.freeze(__enum);\n\n /** Return the enum **/\n return __enum;\n }\n\n return {\n define: define\n }\n\n})();\n" }, { "answer_id": 33326060, "author": "Jules Sam. Randolph", "author_id": 2779871, "author_profile": "https://Stackoverflow.com/users/2779871", "pm_score": 2, "selected": false, "text": "var CloseEventCodes = new Enumeration(\"closeEventCodes\", {\n CLOSE_NORMAL: { _id: 1000, info: \"Connection closed normally\" },\n CLOSE_GOING_AWAY: { _id: 1001, info: \"Connection closed going away\" },\n CLOSE_PROTOCOL_ERROR: { _id: 1002, info: \"Connection closed due to protocol error\" },\n CLOSE_UNSUPPORTED: { _id: 1003, info: \"Connection closed due to unsupported operation\" },\n CLOSE_NO_STATUS: { _id: 1005, info: \"Connection closed with no status\" },\n CLOSE_ABNORMAL: { _id: 1006, info: \"Connection closed abnormally\" },\n CLOSE_TOO_LARGE: { _id: 1009, info: \"Connection closed due to too large packet\" }\n},{ talk: function(){\n console.log(this.info); \n }\n});\n\n\nCloseEventCodes.CLOSE_TOO_LARGE.talk(); //prints \"Connection closed due to too large packet\"\nCloseEventCodes.CLOSE_TOO_LARGE instanceof CloseEventCodes //evaluates to true\n Enumeration" }, { "answer_id": 34636629, "author": "Oooogi", "author_id": 4274373, "author_profile": "https://Stackoverflow.com/users/4274373", "pm_score": 2, "selected": false, "text": "function Enum(obj) {\n // Names must be unique, Values do not.\n // Putting same values for different Names is risky for this implementation\n\n this._reserved = {\n _namesObj: {},\n _objArr: [],\n _namesArr: [],\n _valuesArr: [],\n _selectOptionsHTML: \"\"\n };\n\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n this[k] = obj[k];\n this._reserved._namesObj[obj[k]] = k;\n }\n }\n}\n(function () {\n this.GetName = function (val) {\n if (typeof this._reserved._namesObj[val] === \"undefined\")\n return null;\n return this._reserved._namesObj[val];\n };\n\n this.GetValue = function (name) {\n if (typeof this[name] === \"undefined\")\n return null;\n return this[name];\n };\n\n this.GetObjArr = function () {\n if (this._reserved._objArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push({\n Name: k,\n Value: this[k]\n });\n }\n this._reserved._objArr = arr;\n }\n return this._reserved._objArr;\n };\n\n this.GetNamesArr = function () {\n if (this._reserved._namesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(k);\n }\n this._reserved._namesArr = arr;\n }\n return this._reserved._namesArr;\n };\n\n this.GetValuesArr = function () {\n if (this._reserved._valuesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(this[k]);\n }\n this._reserved._valuesArr = arr;\n }\n return this._reserved._valuesArr;\n };\n\n this.GetSelectOptionsHTML = function () {\n if (this._reserved._selectOptionsHTML.length == 0) {\n var html = \"\";\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n html += \"<option value='\" + this[k] + \"'>\" + k + \"</option>\";\n }\n this._reserved._selectOptionsHTML = html;\n }\n return this._reserved._selectOptionsHTML;\n };\n}).call(Enum.prototype);\n var enum1 = new Enum({\n item1: 0,\n item2: 1,\n item3: 2\n});\n var val2 = enum1.item2;\n var name1 = enum1.GetName(0); // \"item1\"\n var arr = enum1.GetObjArr();\n [{ Name: \"item1\", Value: 0}, { ... }, ... ]\n var html = enum1.GetSelectOptionsHTML();\n \"<option value='0'>item1</option>...\"\n" }, { "answer_id": 37159989, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 2, "selected": false, "text": " var Enum = Object.freeze({\n Role: Object.freeze({ Administrator: 1, Manager: 2, Supervisor: 3 }),\n Color:Object.freeze({RED : 0, GREEN : 1, BLUE : 2 })\n });\n\n alert(Enum.Role.Supervisor);\n alert(Enum.Color.GREEN);\n var currentColor=0;\n if(currentColor == Enum.Color.RED) {\n alert('Its Red');\n }\n" }, { "answer_id": 37429406, "author": "LNT", "author_id": 3335776, "author_profile": "https://Stackoverflow.com/users/3335776", "pm_score": 2, "selected": false, "text": " var Enum = (function(foo) {\n\n var EnumItem = function(item){\n if(typeof item == \"string\"){\n this.name = item;\n } else {\n this.name = item.name;\n }\n }\n EnumItem.prototype = new String(\"DEFAULT\");\n EnumItem.prototype.toString = function(){\n return this.name;\n }\n EnumItem.prototype.equals = function(item){\n if(typeof item == \"string\"){\n return this.name == item;\n } else {\n return this == item && this.name == item.name;\n }\n }\n\n function Enum() {\n this.add.apply(this, arguments);\n Object.freeze(this);\n }\n Enum.prototype.add = function() {\n for (var i in arguments) {\n var enumItem = new EnumItem(arguments[i]);\n this[enumItem.name] = enumItem;\n }\n };\n Enum.prototype.toList = function() {\n return Object.keys(this);\n };\n foo.Enum = Enum;\n return Enum;\n})(this);\nvar STATUS = new Enum(\"CLOSED\",\"PENDING\", { name : \"CONFIRMED\", ackd : true });\nvar STATE = new Enum(\"CLOSED\",\"PENDING\",\"CONFIRMED\",{ name : \"STARTED\"},{ name : \"PROCESSING\"});\n" }, { "answer_id": 38996905, "author": "Ilya Gazman", "author_id": 1129332, "author_profile": "https://Stackoverflow.com/users/1129332", "pm_score": 3, "selected": false, "text": "var Status = Object.freeze({\n \"Connecting\":0,\n \"Ready\":1,\n \"Loading\":2,\n \"Processing\": 3\n});\n console.log(Status.Ready) // 1\n console.log(Object.keys(Status)[Status.Ready]) // Ready\n" }, { "answer_id": 39222211, "author": "Marcus Junius Brutus", "author_id": 274677, "author_profile": "https://Stackoverflow.com/users/274677", "pm_score": 2, "selected": false, "text": "es2015 class CellState {\n v: string;\n constructor(v: string) {\n this.v = v;\n Object.freeze(this);\n }\n static EMPTY = new CellState('e');\n static OCCUPIED = new CellState('o');\n static HIGHLIGHTED = new CellState('h');\n static values = function(): Array<CellState> {\n const rv = [];\n rv.push(CellState.EMPTY);\n rv.push(CellState.OCCUPIED);\n rv.push(CellState.HIGHLIGHTED);\n return rv;\n }\n}\nObject.freeze(CellState);\n CellState CellState CellState CellState CellState values 'use strict';\n\nclass Status {\n\nconstructor(code, displayName = code) {\n if (Status.INSTANCES.has(code))\n throw new Error(`duplicate code value: [${code}]`);\n if (!Status.canCreateMoreInstances)\n throw new Error(`attempt to call constructor(${code}`+\n `, ${displayName}) after all static instances have been created`);\n this.code = code;\n this.displayName = displayName;\n Object.freeze(this);\n Status.INSTANCES.set(this.code, this);\n}\n\ntoString() {\n return `[code: ${this.code}, displayName: ${this.displayName}]`;\n}\nstatic INSTANCES = new Map();\nstatic canCreateMoreInstances = true;\n\n// the values:\nstatic ARCHIVED = new Status('Archived');\nstatic OBSERVED = new Status('Observed');\nstatic SCHEDULED = new Status('Scheduled');\nstatic UNOBSERVED = new Status('Unobserved');\nstatic UNTRIGGERED = new Status('Untriggered');\n\nstatic values = function() {\n return Array.from(Status.INSTANCES.values());\n}\n\nstatic fromCode(code) {\n if (!Status.INSTANCES.has(code))\n throw new Error(`unknown code: ${code}`);\n else\n return Status.INSTANCES.get(code);\n}\n}\n\nStatus.canCreateMoreInstances = false;\nObject.freeze(Status);\nexports.Status = Status;\n" }, { "answer_id": 40390784, "author": "Little Alien", "author_id": 6267925, "author_profile": "https://Stackoverflow.com/users/6267925", "pm_score": 1, "selected": false, "text": "const enumerate = spec => spec.split(/\\s*,\\s*/)\n .reduce((e, n) => Object.assign(e,{[n]:n}), {}) \n const kwords = enumerate(\"begin,end, procedure,if\")\nconsole.log(kwords, kwords.if, kwords.if == \"if\", kwords.undef)\n" }, { "answer_id": 41500700, "author": "Abdennour TOUMI", "author_id": 747579, "author_profile": "https://Stackoverflow.com/users/747579", "pm_score": 4, "selected": false, "text": "class ColorEnum {\n static RED = 0 ;\n static GREEN = 1;\n static BLUE = 2;\n}\n if (currentColor === ColorEnum.GREEN ) {/*-- coding --*/}\n Enum class ColorEnum extends Enum {/*....*/}\n" }, { "answer_id": 43363905, "author": "mika", "author_id": 4910883, "author_profile": "https://Stackoverflow.com/users/4910883", "pm_score": 0, "selected": false, "text": "my.namespace.ColorEnum = new Enum(\n \"RED = 0\",\n \"GREEN\",\n \"BLUE\"\n)\n" }, { "answer_id": 45325303, "author": "David Lemon", "author_id": 2739274, "author_profile": "https://Stackoverflow.com/users/2739274", "pm_score": 0, "selected": false, "text": "var objInvert = function (obj) {\n var invert = {}\n for (var i in obj) {\n if (i.match(/^\\d+$/)) i = parseInt(i,10)\n invert[obj[i]] = i\n }\n return invert\n}\n \nvar musicStyles = Object.freeze(objInvert(['ROCK', 'SURF', 'METAL',\n'BOSSA-NOVA','POP','INDIE']))\n\nconsole.log(musicStyles)" }, { "answer_id": 48798027, "author": "Joseph Merdrignac", "author_id": 4696005, "author_profile": "https://Stackoverflow.com/users/4696005", "pm_score": 3, "selected": false, "text": "const ThreeWiseMen = new Enum('Melchior', 'Caspar', 'Balthazar')\n\nfor (let name of ThreeWiseMen)\n console.log(name)\n\n\n// with a given key\nlet key = ThreeWiseMen.Melchior\n\nconsole.log(key in ThreeWiseMen) // true (string conversion, also true: 'Melchior' in ThreeWiseMen)\n\nfor (let entry from key.enum)\n console.log(entry)\n\n\n// prevent alteration (throws TypeError in strict mode)\nThreeWiseMen.Me = 'Me too!'\nThreeWiseMen.Melchior.name = 'Foo'\n class EnumKey {\n\n constructor(props) { Object.freeze(Object.assign(this, props)) }\n\n toString() { return this.name }\n\n}\n\nexport class Enum {\n\n constructor(...keys) {\n\n for (let [index, key] of keys.entries()) {\n\n Object.defineProperty(this, key, {\n\n value: new EnumKey({ name:key, index, enum:this }),\n enumerable: true,\n\n })\n\n }\n\n Object.freeze(this)\n\n }\n\n *[Symbol.iterator]() {\n\n for (let key of Object.keys(this))\n yield this[key]\n\n }\n\n toString() { return [...this].join(', ') }\n\n}\n" }, { "answer_id": 49309248, "author": "Govind Rai", "author_id": 2757916, "author_profile": "https://Stackoverflow.com/users/2757916", "pm_score": 5, "selected": false, "text": "Object.freeze() class Enum {\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name];\n }\n throw new Error(`No such enumerator: ${name}`);\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n };\n\n return new Proxy(enumObj, handler);\n }\n}\n const roles = new Enum({\n ADMIN: 'Admin',\n USER: 'User',\n});\n undefined undefined // Class for creating enums (13 lines)\n// Feel free to add this to your utility library in \n// your codebase and profit! Note: As Proxies are an ES6 \n// feature, some browsers/clients may not support it and \n// you may need to transpile using a service like babel\n\nclass Enum {\n // The Enum class instantiates a JavaScript Proxy object.\n // Instantiating a `Proxy` object requires two parameters, \n // a `target` object and a `handler`. We first define the handler,\n // then use the handler to instantiate a Proxy.\n\n // A proxy handler is simply an object whose properties\n // are functions which define the behavior of the proxy \n // when an operation is performed on it. \n \n // For enums, we need to define behavior that lets us check what enumerator\n // is being accessed and what enumerator is being set. This can be done by \n // defining \"get\" and \"set\" traps.\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name]\n }\n throw new Error(`No such enumerator: ${name}`)\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n }\n\n\n // Freeze the target object to prevent modifications\n return new Proxy(enumObj, handler)\n }\n}\n\n\n// Now that we have a generic way of creating Enums, lets create our first Enum!\nconst httpMethods = new Enum({\n DELETE: \"DELETE\",\n GET: \"GET\",\n OPTIONS: \"OPTIONS\",\n PATCH: \"PATCH\",\n POST: \"POST\",\n PUT: \"PUT\"\n})\n\n// Sanity checks\nconsole.log(httpMethods.DELETE)\n// logs \"DELETE\"\n\ntry {\n httpMethods.delete = \"delete\"\n} catch (e) {\nconsole.log(\"Error: \", e.message)\n}\n// throws \"Cannot add/update properties on an Enum instance after it is defined\"\n\ntry {\n console.log(httpMethods.delete)\n} catch (e) {\n console.log(\"Error: \", e.message)\n}\n// throws \"No such enumerator: delete\"" }, { "answer_id": 50115744, "author": "Julius Dzidzevičius", "author_id": 4554116, "author_profile": "https://Stackoverflow.com/users/4554116", "pm_score": 2, "selected": false, "text": "enum var makeEnum = function(obj) {\n obj[ obj['Active'] = 1 ] = 'Active';\n obj[ obj['Closed'] = 2 ] = 'Closed';\n obj[ obj['Deleted'] = 3 ] = 'Deleted';\n}\n makeEnum( NewObj = {} )\n// => {1: \"Active\", 2: \"Closed\", 3: \"Deleted\", Active: 1, Closed: 2, Deleted: 3}\n obj[1] 'Active' obj['foo'] = 1\n// => 1\n" }, { "answer_id": 50355530, "author": "Jack G", "author_id": 5601591, "author_profile": "https://Stackoverflow.com/users/5601591", "pm_score": 5, "selected": false, "text": "ENUM_ INDEX_ ENUM_ INDEX_ ENUMLENGTH_ ENUMLEN_ INDEXLENGTH_ INDEXLEN_ LEN_ LENGTH_ 0 0 == null 0 == false 0 == \"\" === == typeof typeof X == \"string\" === 1 ENUM_ INDEX_ const ENUM_COLORENUM_RED = 0;\nconst ENUM_COLORENUM_GREEN = 1;\nconst ENUM_COLORENUM_BLUE = 2;\nconst ENUMLEN_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n INDEX_ ENUM_ // Precondition: var arr = []; //\narr[INDEX_] = ENUM_;\n ENUM_ const ENUM_PET_CAT = 0,\n ENUM_PET_DOG = 1,\n ENUM_PET_RAT = 2,\n ENUMLEN_PET = 3;\n\nvar favoritePets = [ENUM_PET_CAT, ENUM_PET_DOG, ENUM_PET_RAT,\n ENUM_PET_DOG, ENUM_PET_DOG, ENUM_PET_CAT,\n ENUM_PET_RAT, ENUM_PET_CAT, ENUM_PET_DOG];\n\nvar petsFrequency = [];\n\nfor (var i=0; i<ENUMLEN_PET; i=i+1|0)\n petsFrequency[i] = 0;\n\nfor (var i=0, len=favoritePets.length|0, petId=0; i<len; i=i+1|0)\n petsFrequency[petId = favoritePets[i]|0] = (petsFrequency[petId]|0) + 1|0;\n\nconsole.log({\n \"cat\": petsFrequency[ENUM_PET_CAT],\n \"dog\": petsFrequency[ENUM_PET_DOG],\n \"rat\": petsFrequency[ENUM_PET_RAT]\n}); ENUM_PET_RAT ENUMLEN_PET LEN_ LEN_ (function(window){\n \"use strict\";\n var parseInt = window.parseInt;\n\n // use INDEX_ when representing the index in an array instance\n const INDEX_PIXELCOLOR_TYPE = 0, // is a ENUM_PIXELTYPE\n INDEXLEN_PIXELCOLOR = 1,\n INDEX_SOLIDCOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_SOLIDCOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_SOLIDCOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEXLEN_SOLIDCOLOR = INDEXLEN_PIXELCOLOR+3,\n INDEX_ALPHACOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_ALPHACOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_ALPHACOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEX_ALPHACOLOR_A = INDEXLEN_PIXELCOLOR+3,\n INDEXLEN_ALPHACOLOR = INDEXLEN_PIXELCOLOR+4,\n // use ENUM_ when representing a mutually-exclusive species or type\n ENUM_PIXELTYPE_SOLID = 0,\n ENUM_PIXELTYPE_ALPHA = 1,\n ENUM_PIXELTYPE_UNKNOWN = 2,\n ENUMLEN_PIXELTYPE = 2;\n\n function parseHexColor(inputString) {\n var rawstr = inputString.trim().substring(1);\n var result = [];\n if (rawstr.length === 8) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 4) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr[3], 16) * 0x11;\n } else if (rawstr.length === 6) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 3) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n } else {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_UNKNOWN;\n }\n return result;\n }\n\n // the red component of green\n console.log(parseHexColor(\"#0f0\")[INDEX_SOLIDCOLOR_R]);\n // the alpha of transparent purple\n console.log(parseHexColor(\"#f0f7\")[INDEX_ALPHACOLOR_A]); \n // the enumerated array for turquoise\n console.log(parseHexColor(\"#40E0D0\"));\n})(self); 'use strict';(function(e){function d(a){a=a.trim().substring(1);var b=[];8===a.length?(b[0]=1,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16),b[4]=c(a.substring(4,6),16)):4===a.length?(b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16),b[4]=17*c(a[3],16)):6===a.length?(b[0]=0,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16)):3===a.length?(b[0]=0,b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16)):b[0]=2;return b}var c=\ne.parseInt;console.log(d(\"#0f0\")[1]);console.log(d(\"#f0f7\")[4]);console.log(d(\"#40E0D0\"))})(self); // JG = Jack Giffin\nconst ENUM_JG_COLORENUM_RED = 0,\n ENUM_JG_COLORENUM_GREEN = 1,\n ENUM_JG_COLORENUM_BLUE = 2,\n ENUMLEN_JG_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_JG_COLORENUM_RED) {\n // whatever\n}\n\n// PL = Pepper Loftus\n// BK = Bob Knight\nconst ENUM_PL_ARRAYTYPE_UNSORTED = 0,\n ENUM_PL_ARRAYTYPE_ISSORTED = 1,\n ENUM_BK_ARRAYTYPE_CHUNKED = 2, // added by Bob Knight\n ENUM_JG_ARRAYTYPE_INCOMPLETE = 3, // added by jack giffin\n ENUMLEN_PL_COLORENUM = 4;\n\n// later on\n\nif(\n randomArray === ENUM_PL_ARRAYTYPE_UNSORTED ||\n randomArray === ENUM_BK_ARRAYTYPE_CHUNKED\n) {\n // whatever\n}\n /// Hashmaps are slow, even with JIT juice\nvar ref = {};\nref.count = 10;\nref.value = \"foobar\";\n /// Arrays, however, are always lightning fast\nconst INDEX_REFERENCE_COUNT = 0;\nconst INDEX_REFERENCE_VALUE = 1;\nconst INDEXLENGTH_REFERENCE = 2;\n\nvar ref = [];\nref[INDEX_REFERENCE_COUNT] = 10;\nref[INDEX_REFERENCE_VALUE] = \"foobar\";\n /// Hashmaps are slow, even with JIT juice\nvar a={count:10,value:\"foobar\"};\n /// Arrays, however, are always lightning fast\nvar a=[10,\"foobar\"];\n var [variable name] is not defined const ENUM_COLORENUM_RED = 0,\n ENUM_COLORENUM_GREEN = 1,\n ENUM_COLORENUM_BLUE = 2,\n ENUMLEN_COLORENUM = 3;\nvar currentColor = ENUM_COLORENUM_GREEN;\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n\nif(currentColor === ENUM_COLORENUM_DNE) {\n // whatever\n} ENUM_COLORENUM_DNE" }, { "answer_id": 52019639, "author": "jamess", "author_id": 4941356, "author_profile": "https://Stackoverflow.com/users/4941356", "pm_score": 0, "selected": false, "text": "if (value & Ez.G) {...}\n class Ez {\nconstructor() {\n let rgba = [\"R\", \"G\", \"B\", \"A\"];\n let rgbm = rgba.slice();\n rgbm.push(\"M\"); // for feColorMatrix values attribute\n this.createValues(rgba);\n this.createValues([\"H\", \"S\", \"L\"]);\n this.createValues([rgba, rgbm]);\n this.createValues([attX, attY, attW, attH]);\n}\ncreateValues(a) { // a for array\n let i, j;\n if (isA(a[0])) { // max 2 dimensions\n let k = 1;\n for (i of a[0]) {\n for (j of a[1]) {\n this[i + j] = k;\n k *= 2;\n }\n }\n }\n else { // 1D array is simple loop\n for (i = 0, j = 1; i < a.length; i++, j *= 2)\n this[a[i]] = j;\n }\n}\n" }, { "answer_id": 52409064, "author": "papiro", "author_id": 3878933, "author_profile": "https://Stackoverflow.com/users/3878933", "pm_score": 2, "selected": false, "text": "class Enum {\n constructor (...vals) {\n vals.forEach( val => {\n const CONSTANT = Symbol(val);\n Object.defineProperty(this, val.toUpperCase(), {\n get () {\n return CONSTANT;\n },\n set (val) {\n const enum_val = \"CONSTANT\";\n // generate TypeError associated with attempting to change the value of a constant\n enum_val = val;\n }\n });\n });\n }\n}\n const COLORS = new Enum(\"red\", \"blue\", \"green\");\n" }, { "answer_id": 55695903, "author": "oluckyman", "author_id": 823778, "author_profile": "https://Stackoverflow.com/users/823778", "pm_score": 1, "selected": false, "text": "const modes = ['DRAW', 'SCALE', 'DRAG'].reduce((o, v) => ({ ...o, [v]: v }), {});\n {\n DRAW: 'DRAW',\n SCALE: 'SCALE',\n DRAG: 'DRAG'\n}\n" }, { "answer_id": 60309416, "author": "Andrew", "author_id": 1599699, "author_profile": "https://Stackoverflow.com/users/1599699", "pm_score": 3, "selected": false, "text": "colors.RED colors[\"RED\"] colors[0] toString() valueOf() class Enums {\n static create({ name = undefined, items = [] }) {\n let newEnum = {};\n newEnum.length = items.length;\n newEnum.items = items;\n for (let itemIndex in items) {\n //Map by name.\n newEnum[items[itemIndex]] = parseInt(itemIndex, 10);\n //Map by index.\n newEnum[parseInt(itemIndex, 10)] = items[itemIndex];\n }\n newEnum.toString = Enums.enumToString.bind(newEnum);\n newEnum.valueOf = newEnum.toString;\n //Optional naming and global registration.\n if (name != undefined) {\n newEnum.name = name;\n Enums[name] = newEnum;\n }\n //Prevent modification of the enum object.\n Object.freeze(newEnum);\n return newEnum;\n }\n static enumToString() {\n return \"Enum \" +\n (this.name != undefined ? this.name + \" \" : \"\") +\n \"[\" + this.items.toString() + \"]\";\n }\n}\n let colors = Enums.create({\n name: \"COLORS\",\n items: [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\n});\n\n//Global access, if named.\nEnums.COLORS;\n\ncolors.items; //Array(4) [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\ncolors.length; //4\n\ncolors.RED; //0\ncolors.GREEN; //1\ncolors.BLUE; //2\ncolors.PORPLE; //3\ncolors[0]; //\"RED\"\ncolors[1]; //\"GREEN\"\ncolors[2]; //\"BLUE\"\ncolors[3]; //\"PORPLE\"\n\ncolors.toString(); //\"Enum COLORS [RED,GREEN,BLUE,PORPLE]\"\n\n//Enum frozen, makes it a real enum.\ncolors.RED = 9001;\ncolors.RED; //0\n" }, { "answer_id": 62358238, "author": "Aral Roca", "author_id": 4467741, "author_profile": "https://Stackoverflow.com/users/4467741", "pm_score": 3, "selected": false, "text": "const [CATS, DOGS, BIRDS] = ENUM();\n function * ENUM(count=1) { while(true) yield count++ }\n 1" }, { "answer_id": 62929829, "author": "Idan", "author_id": 6591688, "author_profile": "https://Stackoverflow.com/users/6591688", "pm_score": 0, "selected": false, "text": "export const ButtonType = Object.freeze({ \n DEFAULT: 'default', \n BIG: 'big', \n SMALL: 'small'\n})\n" }, { "answer_id": 64416419, "author": "dsanchez", "author_id": 1514122, "author_profile": "https://Stackoverflow.com/users/1514122", "pm_score": 2, "selected": false, "text": "class Sizes {\n // Private Fields\n static #_SMALL = 0;\n static #_MEDIUM = 1;\n static #_LARGE = 2;\n\n // Accessors for \"get\" functions only (no \"set\" functions)\n static get SMALL() { return this.#_SMALL; }\n static get MEDIUM() { return this.#_MEDIUM; }\n static get LARGE() { return this.#_LARGE; }\n}\n Sizes.SMALL; // 0\nSizes.MEDIUM; // 1\nSizes.LARGE; // 2\n Sizes.SMALL = 10 // Sizes.SMALL is still 0\nSizes._SMALL = 10 // Sizes.SMALL is still 0\nSizes.#_SMALL = 10 // Sizes.SMALL is still 0\n" }, { "answer_id": 64631389, "author": "KooiInc", "author_id": 58186, "author_profile": "https://Stackoverflow.com/users/58186", "pm_score": 0, "selected": false, "text": "Enum /*\n * Notes: \n * The proxy handler enables case insensitive property queries\n * BigInt is used to enable bitflag strings /w length > 52\n*/\nfunction EnumFactory() {\n const proxyfy = {\n construct(target, args) { \n const caseInsensitiveHandler = { \n get(target, key) {\n return target[key.toUpperCase()] || target[key]; \n } \n };\n const proxified = new Proxy(new target(...args), caseInsensitiveHandler ); \n return Object.freeze(proxified);\n },\n }\n const ProxiedEnumCtor = new Proxy(EnumCtor, proxyfy);\n const throwIf = (\n assertion = false, \n message = `Unspecified error`, \n ErrorType = Error ) => \n assertion && (() => { throw new ErrorType(message); })();\n const hasFlag = (val, sub) => {\n throwIf(!val || !sub, \"valueIn: missing parameters\", RangeError);\n const andVal = (sub & val);\n return andVal !== BigInt(0) && andVal === val;\n };\n\n function EnumCtor(values) {\n throwIf(values.constructor !== Array || \n values.length < 2 || \n values.filter( v => v.constructor !== String ).length > 0,\n `EnumFactory: expected Array of at least 2 strings`, TypeError);\n const base = BigInt(1);\n this.NONE = BigInt(0);\n values.forEach( (v, i) => this[v.toUpperCase()] = base<<BigInt(i) );\n }\n\n EnumCtor.prototype = {\n get keys() { return Object.keys(this).slice(1); },\n subset(sub) {\n const arrayValues = this.keys;\n return new ProxiedEnumCtor(\n [...sub.toString(2)].reverse()\n .reduce( (acc, v, i) => ( +v < 1 ? acc : [...acc, arrayValues[i]] ), [] )\n );\n },\n getLabel(enumValue) {\n const tryLabel = Object.entries(this).find( value => value[1] === enumValue );\n return !enumValue || !tryLabel.length ? \n \"getLabel: no value parameter or value not in enum\" :\n tryLabel.shift();\n },\n hasFlag(val, sub = this) { return hasFlag(val, sub); },\n };\n \n return arr => new ProxiedEnumCtor(arr);\n}\n" }, { "answer_id": 71026153, "author": "Sebastian Norr", "author_id": 7880517, "author_profile": "https://Stackoverflow.com/users/7880517", "pm_score": 0, "selected": false, "text": "const Summer1 = Symbol(\"summer\")\nconst Summer2 = Symbol(\"summer\")\n\n// Even though they have the same apparent value\n// Summer1 and Summer2 don't equate\nconsole.log(Summer1 === Summer2)\n// false\n\nconsole.log(Summer1)\n const Summer = Symbol(\"summer\")\nconst Autumn = Symbol(\"autumn\")\nconst Winter = Symbol(\"winter\")\nconst Spring = Symbol(\"spring\")\n\nlet season = Spring\n\nswitch (season) {\n case Summer:\n console.log('the season is summer')\n break;\n case Winter:\n console.log('the season is winter')\n break;\n case Spring:\n console.log('the season is spring')\n break;\n case Autumn:\n console.log('the season is autumn')\n break;\n default:\n console.log('season not defined')\n}\n // Season enums can be grouped as static members of a class\nclass Season {\n // Create new instances of the same class as static attributes\n static Summer = new Season(\"summer\")\n static Autumn = new Season(\"autumn\")\n static Winter = new Season(\"winter\")\n static Spring = new Season(\"spring\")\n\n constructor(name) {\n this.name = name\n }\n}\n\n// Now we can access enums using namespaced assignments\n// this makes it semantically clear that \"Summer\" is a \"Season\"\nlet season = Season.Summer\n\n// We can verify whether a particular variable is a Season enum\nconsole.log(season instanceof Season)\n// true\nconsole.log(Symbol('something') instanceof Season)\n//false\n\n// We can explicitly check the type based on each enums class\nconsole.log(season.constructor.name)\n// 'Season'\n this.name .description Seasons.summer.name Seasons.summer constructor(name) {\n this.name = Symbol(name).description\n }\n Object.keys(Season).forEach(season => console.log(\"season:\", season))\n// season: Summer\n// season: Autumn\n// season: Winter\n// season: Spring\n" }, { "answer_id": 71432477, "author": "LEMUEL ADANE", "author_id": 1347816, "author_profile": "https://Stackoverflow.com/users/1347816", "pm_score": 2, "selected": false, "text": "export const ColorEnum = Object.freeze({\n // you can only change the property values here\n // in the object declaration like in the Java enumaration\n RED: 0,\n GREEN: 1,\n BLUE: 2,\n});\n\nColorEnum.RED = 22 // assigning here will throw an error\nColorEnum.VIOLET = 45 // even adding a new property will throw an error\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
287,907
<p>I want to transfer data between a smart phone app and a website. What are the conventional and not-so-conventional ways of doing it? </p> <p>Here's what I have thought of so far:</p> <ol> <li>Simple HTTP GET/POST with data being represented as JSON array string, variations of this being encrypted/compressed string as parameter.</li> <li>Webservice calls ( I am not sure if this is even possible, just a guess)</li> <li>Two step communication : Smartphone to/fro Desktop App to/fro Website) (Cumbersome to develop/use)</li> </ol> <p>Also, what do I need to consider to avoid spamming/snooping?</p>
[ { "answer_id": 1314191, "author": "Randolpho", "author_id": 12716, "author_profile": "https://Stackoverflow.com/users/12716", "pm_score": 7, "selected": false, "text": "var DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\n\nDocument.Write(\"Enumerant: \" + DaysEnum.tuesday);\n DaysEnum.monday = 4; // whoops, monday is now thursday, too\n Object.freeze Object.freeze" }, { "answer_id": 2383215, "author": "Stijn de Witt", "author_id": 286685, "author_profile": "https://Stackoverflow.com/users/286685", "pm_score": 9, "selected": false, "text": "if (currentColor == my.namespace.ColorEnum.RED) {\n // alert name of currentColor (RED: 0)\n var col = my.namespace.ColorEnum;\n for (var name in col) {\n if (col[name] == col.RED)\n alert(name);\n }\n}\n var SIZE = {\n SMALL : {value: 0, name: \"Small\", code: \"S\"}, \n MEDIUM: {value: 1, name: \"Medium\", code: \"M\"}, \n LARGE : {value: 2, name: \"Large\", code: \"L\"}\n};\n\nvar currentSize = SIZE.MEDIUM;\nif (currentSize == SIZE.MEDIUM) {\n // this alerts: \"1: Medium\"\n alert(currentSize.value + \": \" + currentSize.name);\n}\n // Add EXTRALARGE size\nSIZE.EXTRALARGE = {value: 3, name: \"Extra Large\", code: \"XL\"};\n // Add 'Extra Large' size, only knowing it's name\nvar name = \"Extra Large\";\nSIZE[name] = {value: -1, name: name, code: \"?\"};\n for (var sz in SIZE) {\n // sz will be the names of the objects in SIZE, so\n // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'\n var size = SIZE[sz]; // Get the object mapped to the name in sz\n for (var prop in size) {\n // Get all the properties of the size object, iterates over\n // 'value', 'name' and 'code'. You can inspect everything this way. \n }\n} \n" }, { "answer_id": 5040502, "author": "Artur Czajka", "author_id": 572370, "author_profile": "https://Stackoverflow.com/users/572370", "pm_score": 11, "selected": true, "text": "const DaysEnum = Object.freeze({\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...})\n const DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\nObject.freeze(DaysEnum)\n let day = DaysEnum.tuesday\nday = 298832342 // goes through without any errors\n" }, { "answer_id": 6672823, "author": "Andre 'Fi'", "author_id": 841793, "author_profile": "https://Stackoverflow.com/users/841793", "pm_score": 6, "selected": false, "text": "function Enum(constantsList) {\n for (var i in constantsList) {\n this[constantsList[i]] = i;\n }\n}\n var YesNo = new Enum(['NO', 'YES']);\nvar Color = new Enum(['RED', 'GREEN', 'BLUE']);\n Enum.prototype.values = function() {\n return this.allValues;\n /* for the above to work, you'd need to do\n this.allValues = constantsList at the constructor */\n};\n function Enum() {\n for (var i in arguments) {\n this[arguments[i]] = i;\n }\n}\n\nvar YesNo = new Enum('NO', 'YES');\nvar Color = new Enum('RED', 'GREEN', 'BLUE');\n" }, { "answer_id": 10299613, "author": "Yaroslav", "author_id": 1351319, "author_profile": "https://Stackoverflow.com/users/1351319", "pm_score": 4, "selected": false, "text": "// enum instance members, optional\nvar Color = Backbone.Model.extend({\n print : function() {\n console.log(\"I am \" + this.get(\"name\"))\n }\n});\n\n// enum creation\nvar Colors = new Backbone.Collection([\n { id : 1, name : \"Red\", rgb : 0xFF0000},\n { id : 2, name : \"Green\" , rgb : 0x00FF00},\n { id : 3, name : \"Blue\" , rgb : 0x0000FF}\n], {\n model : Color\n});\n\n// Expose members through public fields.\nColors.each(function(color) {\n Colors[color.get(\"name\")] = color;\n});\n\n// using\nColors.Red.print()\n" }, { "answer_id": 10597813, "author": "Chris", "author_id": 1395768, "author_profile": "https://Stackoverflow.com/users/1395768", "pm_score": 4, "selected": false, "text": "function Enum() {\n this._enums = [];\n this._lookups = {};\n}\n\nEnum.prototype.getEnums = function() {\n return _enums;\n}\n\nEnum.prototype.forEach = function(callback){\n var length = this._enums.length;\n for (var i = 0; i < length; ++i){\n callback(this._enums[i]);\n }\n}\n\nEnum.prototype.addEnum = function(e) {\n this._enums.push(e);\n}\n\nEnum.prototype.getByName = function(name) {\n return this[name];\n}\n\nEnum.prototype.getByValue = function(field, value) {\n var lookup = this._lookups[field];\n if(lookup) {\n return lookup[value];\n } else {\n this._lookups[field] = ( lookup = {});\n var k = this._enums.length - 1;\n for(; k >= 0; --k) {\n var m = this._enums[k];\n var j = m[field];\n lookup[j] = m;\n if(j == value) {\n return m;\n }\n }\n }\n return null;\n}\n\nfunction defineEnum(definition) {\n var k;\n var e = new Enum();\n for(k in definition) {\n var j = definition[k];\n e[k] = j;\n e.addEnum(j)\n }\n return e;\n}\n var COLORS = defineEnum({\n RED : {\n value : 1,\n string : 'red'\n },\n GREEN : {\n value : 2,\n string : 'green'\n },\n BLUE : {\n value : 3,\n string : 'blue'\n }\n});\n COLORS.BLUE.string\nCOLORS.BLUE.value\nCOLORS.getByName('BLUE').string\nCOLORS.getByValue('value', 1).string\n\nCOLORS.forEach(function(e){\n // do what you want with e\n});\n" }, { "answer_id": 15948460, "author": "David Miró", "author_id": 2270217, "author_profile": "https://Stackoverflow.com/users/2270217", "pm_score": 3, "selected": false, "text": " function Enum() {\n var that = this;\n for (var i in arguments) {\n that[arguments[i]] = i;\n }\n this.name = function(value) {\n for (var key in that) {\n if (that[key] == value) {\n return key;\n }\n }\n };\n this.exist = function(value) {\n return (typeof that.name(value) !== \"undefined\");\n };\n if (Object.freeze) {\n Object.freeze(that);\n }\n }\n var Color = new Enum('RED', 'GREEN', 'BLUE');\nundefined\nColor.name(Color.REDs)\nundefined\nColor.name(Color.RED)\n\"RED\"\nColor.exist(Color.REDs)\nfalse\nColor.exist(Color.RED)\ntrue\n" }, { "answer_id": 17280078, "author": "Rob Hardy", "author_id": 1733091, "author_profile": "https://Stackoverflow.com/users/1733091", "pm_score": 4, "selected": false, "text": "var MyEnum;\n(function (MyEnum) {\n MyEnum[MyEnum[\"Foo\"] = 0] = \"Foo\";\n MyEnum[MyEnum[\"FooBar\"] = 2] = \"FooBar\";\n MyEnum[MyEnum[\"Bar\"] = 1] = \"Bar\";\n})(MyEnum|| (MyEnum= {}));\n MyEnum.Bar MyEnum[1]" }, { "answer_id": 18355123, "author": "Duncan", "author_id": 945011, "author_profile": "https://Stackoverflow.com/users/945011", "pm_score": 5, "selected": false, "text": "Object.defineProperty Object.defineProperty(Object.prototype,'Enum', {\n value: function() {\n for(i in arguments) {\n Object.defineProperty(this,arguments[i], {\n value:parseInt(i),\n writable:false,\n enumerable:true,\n configurable:true\n });\n }\n return this;\n },\n writable:false,\n enumerable:false,\n configurable:false\n}); \n writable:false Enum() var EnumColors={};\nEnumColors.Enum('RED','BLUE','GREEN','YELLOW');\nEnumColors.RED; // == 0\nEnumColors.BLUE; // == 1\nEnumColors.GREEN; // == 2\nEnumColors.YELLOW; // == 3\n" }, { "answer_id": 19034005, "author": "GTF", "author_id": 907981, "author_profile": "https://Stackoverflow.com/users/907981", "pm_score": 2, "selected": false, "text": "__defineGetter__ __defineSetter__ defineProperty var Colours = Enum('RED', 'GREEN', 'BLUE');\n" }, { "answer_id": 19112051, "author": "user2254487", "author_id": 2254487, "author_profile": "https://Stackoverflow.com/users/2254487", "pm_score": 2, "selected": false, "text": "var Colors = function(){\nreturn {\n 'WHITE':0,\n 'BLACK':1,\n 'RED':2,\n 'GREEN':3\n }\n}();\n\nconsole.log(Colors.WHITE) //this prints out \"0\"\n" }, { "answer_id": 23455550, "author": "arcseldon", "author_id": 1882064, "author_profile": "https://Stackoverflow.com/users/1882064", "pm_score": 2, "selected": false, "text": "_ = require('underscore');\n\nvar _Enum = function () {\n\n var keys = _.map(arguments, function (value) {\n return value;\n });\n var self = {\n keys: keys\n };\n for (var i = 0; i < arguments.length; i++) {\n self[keys[i]] = i;\n }\n return self;\n};\n\nvar fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));\nvar encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));\n\nexports.fileFormatEnum = fileFormatEnum;\nexports.encodingEnum = encodingEnum;\n var chai = require(\"chai\"),\n assert = chai.assert,\n expect = chai.expect,\n should = chai.should(),\n enums = require('./enums'),\n _ = require('underscore');\n\n\ndescribe('enums', function () {\n\n describe('fileFormatEnum', function () {\n it('should return expected fileFormat enum declarations', function () {\n var fileFormatEnum = enums.fileFormatEnum;\n should.exist(fileFormatEnum);\n assert('{\"keys\":[\"CSV\",\"TSV\"],\"CSV\":0,\"TSV\":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');\n assert('[\"CSV\",\"TSV\"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');\n });\n });\n\n describe('encodingEnum', function () {\n it('should return expected encoding enum declarations', function () {\n var encodingEnum = enums.encodingEnum;\n should.exist(encodingEnum);\n assert('{\"keys\":[\"UTF8\",\"SHIFT_JIS\"],\"UTF8\":0,\"SHIFT_JIS\":1}' === JSON.stringify(encodingEnum), 'Unexpected format');\n assert('[\"UTF8\",\"SHIFT_JIS\"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');\n });\n });\n\n});\n" }, { "answer_id": 23669178, "author": "Xeltor", "author_id": 1330674, "author_profile": "https://Stackoverflow.com/users/1330674", "pm_score": 3, "selected": false, "text": "var buildSet = function(array) {\n var set = {};\n for (var i in array) {\n var item = array[i];\n set[item] = item;\n }\n return set;\n}\n\nvar myEnum = buildSet(['RED','GREEN','BLUE']);\n// myEnum.RED == 'RED' ...etc\n" }, { "answer_id": 25692451, "author": "Andrew Philips", "author_id": 314114, "author_profile": "https://Stackoverflow.com/users/314114", "pm_score": 1, "selected": false, "text": "function mkenum_1()\n{\n var o = new Object();\n var c = -1;\n var f = function(e, v) { Object.defineProperty(o, e, { value:v, writable:false, enumerable:true, configurable:true })};\n\n for (i in arguments) {\n var e = arguments[i];\n if ((!!e) & (e.constructor == Object))\n for (j in e)\n f(j, (c=e[j]));\n else\n f(e, ++c);\n }\n\n return Object.freeze ? Object.freeze(o) : o;\n}\n\nvar Sizes = mkenum_1('SMALL','MEDIUM',{LARGE: 100},'XLARGE');\n\nconsole.log(\"MED := \" + Sizes.MEDIUM);\nconsole.log(\"LRG := \" + Sizes.LARGE);\n\n// Output is:\n// MED := 1\n// LRG := 100\n function mkenum_2(seed)\n{\n var p = {};\n\n console.log(\"Seed := \" + seed);\n\n for (k in seed) {\n var v = seed[k];\n\n if (v instanceof Array)\n p[(seed[k]=v[0])] = { value: v[0], name: v[1], code: v[2] };\n else\n p[v] = { value: v, name: k.toLowerCase(), code: k.substring(0,1) };\n }\n seed.properties = p;\n\n return Object.freeze ? Object.freeze(seed) : seed;\n}\n var SizeEnum2 = mkenum_2({ SMALL: 1, MEDIUM: 2, LARGE: 3});\nvar SizeEnum3 = mkenum_2({ SMALL: [1, \"small\", \"S\"], MEDIUM: [2, \"medium\", \"M\"], LARGE: [3, \"large\", \"L\"] });\n" }, { "answer_id": 28205581, "author": "Shivanshu Goyal", "author_id": 1544818, "author_profile": "https://Stackoverflow.com/users/1544818", "pm_score": 3, "selected": false, "text": "var ColorEnum = {\n red: {},\n green: {},\n blue: {}\n}\n" }, { "answer_id": 28526471, "author": "Gildas.Tambo", "author_id": 2065597, "author_profile": "https://Stackoverflow.com/users/2065597", "pm_score": 1, "selected": false, "text": "var findInEnum,\n colorEnum = {\n red : 0,\n green : 1,\n blue : 2\n};\n\n// later on\n\nfindInEnum = function (enumKey) {\n if (colorEnum.hasOwnProperty(enumKey)) {\n return enumKey+' Value: ' + colorEnum[enumKey]\n }\n}\n\nalert(findInEnum(\"blue\"))" }, { "answer_id": 29074825, "author": "Blake Bowen", "author_id": 2760155, "author_profile": "https://Stackoverflow.com/users/2760155", "pm_score": 2, "selected": false, "text": "function _enum(list) { \n for (var key in list) {\n list[list[key] = list[key]] = key;\n }\n return Object.freeze(list);\n}\n\nvar Color = _enum({\n Red: 0,\n Green: 5,\n Blue: 2\n});\n\n// Color → {0: \"Red\", 2: \"Blue\", 5: \"Green\", \"Red\": 0, \"Green\": 5, \"Blue\": 2}\n// Color.Red → 0\n// Color.Green → 5\n// Color.Blue → 2\n// Color[5] → Green\n// Color.Blue > Color.Green → false\n function enum() {\n var key, val = -1, list = {};\n _.reduce(_.toArray(arguments), function(result, kvp) { \n kvp = kvp.split(\"=\");\n key = _.trim(kvp[0]);\n val = _.parseInt(kvp[1]) || ++val; \n result[result[val] = key] = val;\n return result;\n }, list);\n return Object.freeze(list);\n} \n\n// Add enum to lodash \n_.mixin({ \"enum\": enum });\n\nvar Color = _.enum(\n \"Red\",\n \"Green\",\n \"Blue = 5\",\n \"Yellow\",\n \"Purple = 20\",\n \"Gray\"\n);\n\n// Color.Red → 0\n// Color.Green → 1\n// Color.Blue → 5\n// Color.Yellow → 6\n// Color.Purple → 20\n// Color.Gray → 21\n// Color[5] → Blue\n" }, { "answer_id": 29094597, "author": "Tschallacka", "author_id": 1356107, "author_profile": "https://Stackoverflow.com/users/1356107", "pm_score": 1, "selected": false, "text": "if(something instanceof enum) if(somevar instanceof EnumFieldSegment) /**\n * simple parameter object instantiator\n * @param name\n * @param value\n * @returns\n */\nfunction p(name,value) {\n this.name = name;\n this.value = value;\n return Object.freeze(this);\n}\n/**\n * EnumFieldSegmentBase\n */\nfunction EnumFieldSegmentBase() {\n this.fieldType = \"STRING\";\n}\nfunction dummyregex() {\n}\ndummyregex.prototype.test = function(str) {\n if(this.fieldType === \"STRING\") {\n maxlength = arguments[1];\n return str.length <= maxlength;\n }\n return true;\n};\n\ndummyregexposer = new dummyregex();\nEnumFieldSegmentBase.prototype.getInputRegex = function() { \n switch(this.fieldType) {\n case \"STRING\" : return dummyregexposer; \n case \"INT\": return /^(\\d+)?$/;\n case \"DECIMAL2\": return /^\\d+(\\.\\d{1,2}|\\d+|\\.)?$/;\n case \"DECIMAL8\": return /^\\d+(\\.\\d{1,8}|\\d+|\\.)?$/;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": return dummyregexposer;\n }\n};\nEnumFieldSegmentBase.prototype.convertToType = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\" : val = $input;break;\n case \"INT\": val==\"\"? val=0 :val = parseInt($input);break;\n case \"DECIMAL2\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal2($input).toDP(2);break;\n case \"DECIMAL8\": if($input === \"\" || $input === null) {$input = \"0\"}if($input.substr(-1) === \".\"){$input = $input+0};val = new Decimal8($input).toDP(8);break;\n // boolean is tricky dicky. if its a boolean false, if its a string if its empty 0 or false its false, otherwise lets see what Boolean produces\n case \"BOOLEAN\": val = (typeof $input == 'boolean' ? $input : (typeof $input === 'string' ? (($input === \"false\" || $input === \"\" || $input === \"0\") ? false : true) : new Boolean($input).valueOf())) ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.convertToString = function($input) {\n var val = $input;\n switch(this.fieldType) {\n case \"STRING\": val = $input;break;\n case \"INT\": val = $input+\"\";break;\n case \"DECIMAL2\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+2 : $input.toString().indexOf('.')+2)) ;break;\n case \"DECIMAL8\": val = $input.toPrecision(($input.toString().indexOf('.') === -1 ? $input.toString().length+8 : $input.toString().indexOf('.')+8)) ;break;\n case \"BOOLEAN\": val = $input ? \"true\" : \"false\" ;break;\n }\n return val;\n};\nEnumFieldSegmentBase.prototype.compareValue = function($val1,$val2) {\n var val = false;\n switch(this.fieldType) {\n case \"STRING\": val = ($val1===$val2);break;\n case \"INT\": val = ($val1===$val2);break;\n case \"DECIMAL2\": val = ($val1.comparedTo($val2)===0);break;\n case \"DECIMAL8\": val = ($val1.comparedTo($val2)===0);break;\n case \"BOOLEAN\": val = ($val1===$val2);break;\n }\n return val;\n};\n\n/**\n * EnumFieldSegment is an individual segment in the \n * EnumField\n * @param $array An array consisting of object p\n */\nfunction EnumFieldSegment() {\n for(c=0;c<arguments.length;c++) {\n if(arguments[c] instanceof p) {\n this[arguments[c].name] = arguments[c].value;\n }\n }\n return Object.freeze(this); \n}\nEnumFieldSegment.prototype = new EnumFieldSegmentBase();\nEnumFieldSegment.prototype.constructor = EnumFieldSegment;\n\n\n/**\n * Simple enum to show what type of variable a Field type is.\n * @param STRING\n * @param INT\n * @param DECIMAL2\n * @param DECIMAL8\n * @param BOOLEAN\n * \n */\nEnumField = Object.freeze({STRING: new EnumFieldSegment(new p(\"fieldType\",\"STRING\")), \n INT: new EnumFieldSegment(new p(\"fieldType\",\"INT\")), \n DECIMAL2: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL2\")), \n DECIMAL8: new EnumFieldSegment(new p(\"fieldType\",\"DECIMAL8\")), \n BOOLEAN: new EnumFieldSegment(new p(\"fieldType\",\"BOOLEAN\"))});\n" }, { "answer_id": 29894175, "author": "Gelin Luo", "author_id": 391227, "author_profile": "https://Stackoverflow.com/users/391227", "pm_score": 2, "selected": false, "text": "var genEnum = require('gen_enum');\n\nvar AppMode = genEnum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n gen_enum gen_enum constjs var genEnum = require('gen_enum');\n var genEnum = require('constjs').enum;\n" }, { "answer_id": 30045582, "author": "Pylinux", "author_id": 1465640, "author_profile": "https://Stackoverflow.com/users/1465640", "pm_score": 0, "selected": false, "text": "var DaysEnum = Object.freeze ({ monday: {}, tuesday: {}, ... });\n if (incommingEnum === DaysEnum.monday) //incommingEnum is monday\n" }, { "answer_id": 30058506, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 6, "selected": false, "text": "Symbol() != Symbol() const COLOR = Object.freeze({RED: Symbol(), BLUE: Symbol()});\n const COLOR = Object.freeze({RED: Symbol(\"RED\"), BLUE: Symbol(\"BLUE\")});\n const color = new Enum(\"RED\", \"BLUE\")\n\ncolor.RED.toString() // Symbol(RED)\ncolor.getName(color.RED) // RED\ncolor.size // 2\ncolor.values() // Symbol(RED), Symbol(BLUE)\ncolor.toString() // RED,BLUE\n" }, { "answer_id": 31185447, "author": "Manohar Reddy Poreddy", "author_id": 984471, "author_profile": "https://Stackoverflow.com/users/984471", "pm_score": 3, "selected": false, "text": "var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n var CONST_WILD_TYPES = {\n REGULAR: 'RE',\n EXPANDING: 'EX',\n STICKY: 'ST',\n SHIFTING: 'SH'\n};\n var CONST_WILD_TYPES = {\n REGULAR: '1',\n EXPANDING: '2',\n STICKY: '3',\n SHIFTING: '4'\n};\n var wildType = CONST_WILD_TYPES.REGULAR;\n if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n" }, { "answer_id": 31636748, "author": "hvdd", "author_id": 2326407, "author_profile": "https://Stackoverflow.com/users/2326407", "pm_score": 4, "selected": false, "text": "const Modes = {\n DRAGGING: 'drag',\n SCALING: 'scale',\n CLICKED: 'click'\n};\n" }, { "answer_id": 32245965, "author": "Sherali Turdiyev", "author_id": 4365315, "author_profile": "https://Stackoverflow.com/users/4365315", "pm_score": 2, "selected": false, "text": "var A = {a:11, b:22}, \nenumA = new TypeHelper(A);\n\nif(enumA.Value === A.b || enumA.Key === \"a\"){ \n... \n}\n\nvar keys = enumA.getAsList();//[object, object]\n\n//set\nenumA.setType(22, false);//setType(val, isKey)\n\nenumA.setType(\"a\", true);\n\nenumA.setTypeByIndex(1);\n TypeHelper var Helper = {\n isEmpty: function (obj) {\n return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;\n },\n\n isObject: function (obj) {\n return (typeof obj === 'object');\n },\n\n sortObjectKeys: function (object) {\n return Object.keys(object)\n .sort(function (a, b) {\n c = a - b;\n return c\n });\n },\n containsItem: function (arr, item) {\n if (arr && Array.isArray(arr)) {\n return arr.indexOf(item) > -1;\n } else {\n return arr === item;\n }\n },\n\n pushArray: function (arr1, arr2) {\n if (arr1 && arr2 && Array.isArray(arr1)) {\n arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);\n }\n }\n};\nfunction TypeHelper() {\n var _types = arguments[0],\n _defTypeIndex = 0,\n _currentType,\n _value,\n _allKeys = Helper.sortObjectKeys(_types);\n\n if (arguments.length == 2) {\n _defTypeIndex = arguments[1];\n }\n\n Object.defineProperties(this, {\n Key: {\n get: function () {\n return _currentType;\n },\n set: function (val) {\n _currentType.setType(val, true);\n },\n enumerable: true\n },\n Value: {\n get: function () {\n return _types[_currentType];\n },\n set: function (val) {\n _value.setType(val, false);\n },\n enumerable: true\n }\n });\n this.getAsList = function (keys) {\n var list = [];\n _allKeys.forEach(function (key, idx, array) {\n if (key && _types[key]) {\n\n if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {\n var json = {};\n json.Key = key;\n json.Value = _types[key];\n Helper.pushArray(list, json);\n }\n }\n });\n return list;\n };\n\n this.setType = function (value, isKey) {\n if (!Helper.isEmpty(value)) {\n Object.keys(_types).forEach(function (key, idx, array) {\n if (Helper.isObject(value)) {\n if (value && value.Key == key) {\n _currentType = key;\n }\n } else if (isKey) {\n if (value && value.toString() == key.toString()) {\n _currentType = key;\n }\n } else if (value && value.toString() == _types[key]) {\n _currentType = key;\n }\n });\n } else {\n this.setDefaultType();\n }\n return isKey ? _types[_currentType] : _currentType;\n };\n\n this.setTypeByIndex = function (index) {\n for (var i = 0; i < _allKeys.length; i++) {\n if (index === i) {\n _currentType = _allKeys[index];\n break;\n }\n }\n };\n\n this.setDefaultType = function () {\n this.setTypeByIndex(_defTypeIndex);\n };\n\n this.setDefaultType();\n}\n\nvar TypeA = {\n \"-1\": \"Any\",\n \"2\": \"2L\",\n \"100\": \"100L\",\n \"200\": \"200L\",\n \"1000\": \"1000L\"\n};\n\nvar enumA = new TypeHelper(TypeA, 4);\n\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\n\nenumA.setType(\"200L\", false);\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\nenumA.setDefaultType();\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\n\nenumA.setTypeByIndex(1);\ndocument.writeln(\"Key = \", enumA.Key,\", Value = \", enumA.Value, \"<br>\");\n\ndocument.writeln(\"is equals = \", (enumA.Value == TypeA[\"2\"]));" }, { "answer_id": 32658453, "author": "Vivin Paliath", "author_id": 263004, "author_profile": "https://Stackoverflow.com/users/263004", "pm_score": 3, "selected": false, "text": "instanceof var Days = Enum.define(\"Days\", [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]);\n Days Days Days.Monday instanceof Days; // true\n\nDays.Friday.name(); // \"Friday\"\nDays.Friday.ordinal(); // 4\n\nDays.Sunday === Days.Sunday; // true\nDays.Sunday === Days.Friday; // false\n\nDays.Sunday.toString(); // \"Sunday\"\n\nDays.toString() // \"Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } \"\n\nDays.values().map(function(e) { return e.name(); }); //[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\nDays.values()[4].name(); //\"Friday\"\n\nDays.fromName(\"Thursday\") === Days.Thursday // true\nDays.fromName(\"Wednesday\").name() // \"Wednesday\"\nDays.Friday.fromName(\"Saturday\").name() // \"Saturday\"\n var Enum = (function () {\n /**\n * Function to define an enum\n * @param typeName - The name of the enum.\n * @param constants - The constants on the enum. Can be an array of strings, or an object where each key is an enum\n * constant, and the values are objects that describe attributes that can be attached to the associated constant.\n */\n function define(typeName, constants) {\n\n /** Check Arguments **/\n if (typeof typeName === \"undefined\") {\n throw new TypeError(\"A name is required.\");\n }\n\n if (!(constants instanceof Array) && (Object.getPrototypeOf(constants) !== Object.prototype)) {\n\n throw new TypeError(\"The constants parameter must either be an array or an object.\");\n\n } else if ((constants instanceof Array) && constants.length === 0) {\n\n throw new TypeError(\"Need to provide at least one constant.\");\n\n } else if ((constants instanceof Array) && !constants.reduce(function (isString, element) {\n return isString && (typeof element === \"string\");\n }, true)) {\n\n throw new TypeError(\"One or more elements in the constant array is not a string.\");\n\n } else if (Object.getPrototypeOf(constants) === Object.prototype && !Object.keys(constants).reduce(function (isObject, constant) {\n return Object.getPrototypeOf(constants[constant]) === Object.prototype;\n }, true)) {\n\n throw new TypeError(\"One or more constants do not have an associated object-value.\");\n\n }\n\n var isArray = (constants instanceof Array);\n var isObject = !isArray;\n\n /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/\n function __() { };\n\n /** Dynamically define a function with the same name as the enum we want to define. **/\n var __enum = new Function([\"__\"],\n \"return function \" + typeName + \"(sentinel, name, ordinal) {\" +\n \"if(!(sentinel instanceof __)) {\" +\n \"throw new TypeError(\\\"Cannot instantiate an instance of \" + typeName + \".\\\");\" +\n \"}\" +\n\n \"this.__name = name;\" +\n \"this.__ordinal = ordinal;\" +\n \"}\"\n )(__);\n\n /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/\n var __values = [];\n var __dict = {};\n\n /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/\n Object.defineProperty(__enum, \"values\", {\n value: function () {\n return __values;\n }\n });\n\n Object.defineProperty(__enum, \"fromName\", {\n value: function (name) {\n var __constant = __dict[name]\n if (__constant) {\n return __constant;\n } else {\n throw new TypeError(typeName + \" does not have a constant with name \" + name + \".\");\n }\n }\n });\n\n /**\n * The following methods are available to all instances of the enum. values() and fromName() need to be\n * available to each constant, and so we will attach them on the prototype. But really, they're just\n * aliases to their counterparts on the prototype.\n */\n Object.defineProperty(__enum.prototype, \"values\", {\n value: __enum.values\n });\n\n Object.defineProperty(__enum.prototype, \"fromName\", {\n value: __enum.fromName\n });\n\n Object.defineProperty(__enum.prototype, \"name\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"ordinal\", {\n value: function () {\n return this.__ordinal;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"valueOf\", {\n value: function () {\n return this.__name;\n }\n });\n\n Object.defineProperty(__enum.prototype, \"toString\", {\n value: function () {\n return this.__name;\n }\n });\n\n /**\n * If constants was an array, we can the element values directly. Otherwise, we will have to use the keys\n * from the constants object.\n */\n var _constants = constants;\n if (isObject) {\n _constants = Object.keys(constants);\n }\n\n /** Iterate over all constants, create an instance of our enum for each one, and attach it to the enum type **/\n _constants.forEach(function (name, ordinal) {\n // Create an instance of the enum\n var __constant = new __enum(new __(), name, ordinal);\n\n // If constants was an object, we want to attach the provided attributes to the instance.\n if (isObject) {\n Object.keys(constants[name]).forEach(function (attr) {\n Object.defineProperty(__constant, attr, {\n value: constants[name][attr]\n });\n });\n }\n\n // Freeze the instance so that it cannot be modified.\n Object.freeze(__constant);\n\n // Attach the instance using the provided name to the enum type itself.\n Object.defineProperty(__enum, name, {\n value: __constant\n });\n\n // Update our private objects\n __values.push(__constant);\n __dict[name] = __constant;\n });\n\n /** Define a friendly toString method for the enum **/\n var string = typeName + \" { \" + __enum.values().map(function (c) {\n return c.name();\n }).join(\", \") + \" } \";\n\n Object.defineProperty(__enum, \"toString\", {\n value: function () {\n return string;\n }\n });\n\n /** Freeze our private objects **/\n Object.freeze(__values);\n Object.freeze(__dict);\n\n /** Freeze the prototype on the enum and the enum itself **/\n Object.freeze(__enum.prototype);\n Object.freeze(__enum);\n\n /** Return the enum **/\n return __enum;\n }\n\n return {\n define: define\n }\n\n})();\n" }, { "answer_id": 33326060, "author": "Jules Sam. Randolph", "author_id": 2779871, "author_profile": "https://Stackoverflow.com/users/2779871", "pm_score": 2, "selected": false, "text": "var CloseEventCodes = new Enumeration(\"closeEventCodes\", {\n CLOSE_NORMAL: { _id: 1000, info: \"Connection closed normally\" },\n CLOSE_GOING_AWAY: { _id: 1001, info: \"Connection closed going away\" },\n CLOSE_PROTOCOL_ERROR: { _id: 1002, info: \"Connection closed due to protocol error\" },\n CLOSE_UNSUPPORTED: { _id: 1003, info: \"Connection closed due to unsupported operation\" },\n CLOSE_NO_STATUS: { _id: 1005, info: \"Connection closed with no status\" },\n CLOSE_ABNORMAL: { _id: 1006, info: \"Connection closed abnormally\" },\n CLOSE_TOO_LARGE: { _id: 1009, info: \"Connection closed due to too large packet\" }\n},{ talk: function(){\n console.log(this.info); \n }\n});\n\n\nCloseEventCodes.CLOSE_TOO_LARGE.talk(); //prints \"Connection closed due to too large packet\"\nCloseEventCodes.CLOSE_TOO_LARGE instanceof CloseEventCodes //evaluates to true\n Enumeration" }, { "answer_id": 34636629, "author": "Oooogi", "author_id": 4274373, "author_profile": "https://Stackoverflow.com/users/4274373", "pm_score": 2, "selected": false, "text": "function Enum(obj) {\n // Names must be unique, Values do not.\n // Putting same values for different Names is risky for this implementation\n\n this._reserved = {\n _namesObj: {},\n _objArr: [],\n _namesArr: [],\n _valuesArr: [],\n _selectOptionsHTML: \"\"\n };\n\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n this[k] = obj[k];\n this._reserved._namesObj[obj[k]] = k;\n }\n }\n}\n(function () {\n this.GetName = function (val) {\n if (typeof this._reserved._namesObj[val] === \"undefined\")\n return null;\n return this._reserved._namesObj[val];\n };\n\n this.GetValue = function (name) {\n if (typeof this[name] === \"undefined\")\n return null;\n return this[name];\n };\n\n this.GetObjArr = function () {\n if (this._reserved._objArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push({\n Name: k,\n Value: this[k]\n });\n }\n this._reserved._objArr = arr;\n }\n return this._reserved._objArr;\n };\n\n this.GetNamesArr = function () {\n if (this._reserved._namesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(k);\n }\n this._reserved._namesArr = arr;\n }\n return this._reserved._namesArr;\n };\n\n this.GetValuesArr = function () {\n if (this._reserved._valuesArr.length == 0) {\n var arr = [];\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n arr.push(this[k]);\n }\n this._reserved._valuesArr = arr;\n }\n return this._reserved._valuesArr;\n };\n\n this.GetSelectOptionsHTML = function () {\n if (this._reserved._selectOptionsHTML.length == 0) {\n var html = \"\";\n for (k in this) {\n if (this.hasOwnProperty(k))\n if (k != \"_reserved\")\n html += \"<option value='\" + this[k] + \"'>\" + k + \"</option>\";\n }\n this._reserved._selectOptionsHTML = html;\n }\n return this._reserved._selectOptionsHTML;\n };\n}).call(Enum.prototype);\n var enum1 = new Enum({\n item1: 0,\n item2: 1,\n item3: 2\n});\n var val2 = enum1.item2;\n var name1 = enum1.GetName(0); // \"item1\"\n var arr = enum1.GetObjArr();\n [{ Name: \"item1\", Value: 0}, { ... }, ... ]\n var html = enum1.GetSelectOptionsHTML();\n \"<option value='0'>item1</option>...\"\n" }, { "answer_id": 37159989, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 2, "selected": false, "text": " var Enum = Object.freeze({\n Role: Object.freeze({ Administrator: 1, Manager: 2, Supervisor: 3 }),\n Color:Object.freeze({RED : 0, GREEN : 1, BLUE : 2 })\n });\n\n alert(Enum.Role.Supervisor);\n alert(Enum.Color.GREEN);\n var currentColor=0;\n if(currentColor == Enum.Color.RED) {\n alert('Its Red');\n }\n" }, { "answer_id": 37429406, "author": "LNT", "author_id": 3335776, "author_profile": "https://Stackoverflow.com/users/3335776", "pm_score": 2, "selected": false, "text": " var Enum = (function(foo) {\n\n var EnumItem = function(item){\n if(typeof item == \"string\"){\n this.name = item;\n } else {\n this.name = item.name;\n }\n }\n EnumItem.prototype = new String(\"DEFAULT\");\n EnumItem.prototype.toString = function(){\n return this.name;\n }\n EnumItem.prototype.equals = function(item){\n if(typeof item == \"string\"){\n return this.name == item;\n } else {\n return this == item && this.name == item.name;\n }\n }\n\n function Enum() {\n this.add.apply(this, arguments);\n Object.freeze(this);\n }\n Enum.prototype.add = function() {\n for (var i in arguments) {\n var enumItem = new EnumItem(arguments[i]);\n this[enumItem.name] = enumItem;\n }\n };\n Enum.prototype.toList = function() {\n return Object.keys(this);\n };\n foo.Enum = Enum;\n return Enum;\n})(this);\nvar STATUS = new Enum(\"CLOSED\",\"PENDING\", { name : \"CONFIRMED\", ackd : true });\nvar STATE = new Enum(\"CLOSED\",\"PENDING\",\"CONFIRMED\",{ name : \"STARTED\"},{ name : \"PROCESSING\"});\n" }, { "answer_id": 38996905, "author": "Ilya Gazman", "author_id": 1129332, "author_profile": "https://Stackoverflow.com/users/1129332", "pm_score": 3, "selected": false, "text": "var Status = Object.freeze({\n \"Connecting\":0,\n \"Ready\":1,\n \"Loading\":2,\n \"Processing\": 3\n});\n console.log(Status.Ready) // 1\n console.log(Object.keys(Status)[Status.Ready]) // Ready\n" }, { "answer_id": 39222211, "author": "Marcus Junius Brutus", "author_id": 274677, "author_profile": "https://Stackoverflow.com/users/274677", "pm_score": 2, "selected": false, "text": "es2015 class CellState {\n v: string;\n constructor(v: string) {\n this.v = v;\n Object.freeze(this);\n }\n static EMPTY = new CellState('e');\n static OCCUPIED = new CellState('o');\n static HIGHLIGHTED = new CellState('h');\n static values = function(): Array<CellState> {\n const rv = [];\n rv.push(CellState.EMPTY);\n rv.push(CellState.OCCUPIED);\n rv.push(CellState.HIGHLIGHTED);\n return rv;\n }\n}\nObject.freeze(CellState);\n CellState CellState CellState CellState CellState values 'use strict';\n\nclass Status {\n\nconstructor(code, displayName = code) {\n if (Status.INSTANCES.has(code))\n throw new Error(`duplicate code value: [${code}]`);\n if (!Status.canCreateMoreInstances)\n throw new Error(`attempt to call constructor(${code}`+\n `, ${displayName}) after all static instances have been created`);\n this.code = code;\n this.displayName = displayName;\n Object.freeze(this);\n Status.INSTANCES.set(this.code, this);\n}\n\ntoString() {\n return `[code: ${this.code}, displayName: ${this.displayName}]`;\n}\nstatic INSTANCES = new Map();\nstatic canCreateMoreInstances = true;\n\n// the values:\nstatic ARCHIVED = new Status('Archived');\nstatic OBSERVED = new Status('Observed');\nstatic SCHEDULED = new Status('Scheduled');\nstatic UNOBSERVED = new Status('Unobserved');\nstatic UNTRIGGERED = new Status('Untriggered');\n\nstatic values = function() {\n return Array.from(Status.INSTANCES.values());\n}\n\nstatic fromCode(code) {\n if (!Status.INSTANCES.has(code))\n throw new Error(`unknown code: ${code}`);\n else\n return Status.INSTANCES.get(code);\n}\n}\n\nStatus.canCreateMoreInstances = false;\nObject.freeze(Status);\nexports.Status = Status;\n" }, { "answer_id": 40390784, "author": "Little Alien", "author_id": 6267925, "author_profile": "https://Stackoverflow.com/users/6267925", "pm_score": 1, "selected": false, "text": "const enumerate = spec => spec.split(/\\s*,\\s*/)\n .reduce((e, n) => Object.assign(e,{[n]:n}), {}) \n const kwords = enumerate(\"begin,end, procedure,if\")\nconsole.log(kwords, kwords.if, kwords.if == \"if\", kwords.undef)\n" }, { "answer_id": 41500700, "author": "Abdennour TOUMI", "author_id": 747579, "author_profile": "https://Stackoverflow.com/users/747579", "pm_score": 4, "selected": false, "text": "class ColorEnum {\n static RED = 0 ;\n static GREEN = 1;\n static BLUE = 2;\n}\n if (currentColor === ColorEnum.GREEN ) {/*-- coding --*/}\n Enum class ColorEnum extends Enum {/*....*/}\n" }, { "answer_id": 43363905, "author": "mika", "author_id": 4910883, "author_profile": "https://Stackoverflow.com/users/4910883", "pm_score": 0, "selected": false, "text": "my.namespace.ColorEnum = new Enum(\n \"RED = 0\",\n \"GREEN\",\n \"BLUE\"\n)\n" }, { "answer_id": 45325303, "author": "David Lemon", "author_id": 2739274, "author_profile": "https://Stackoverflow.com/users/2739274", "pm_score": 0, "selected": false, "text": "var objInvert = function (obj) {\n var invert = {}\n for (var i in obj) {\n if (i.match(/^\\d+$/)) i = parseInt(i,10)\n invert[obj[i]] = i\n }\n return invert\n}\n \nvar musicStyles = Object.freeze(objInvert(['ROCK', 'SURF', 'METAL',\n'BOSSA-NOVA','POP','INDIE']))\n\nconsole.log(musicStyles)" }, { "answer_id": 48798027, "author": "Joseph Merdrignac", "author_id": 4696005, "author_profile": "https://Stackoverflow.com/users/4696005", "pm_score": 3, "selected": false, "text": "const ThreeWiseMen = new Enum('Melchior', 'Caspar', 'Balthazar')\n\nfor (let name of ThreeWiseMen)\n console.log(name)\n\n\n// with a given key\nlet key = ThreeWiseMen.Melchior\n\nconsole.log(key in ThreeWiseMen) // true (string conversion, also true: 'Melchior' in ThreeWiseMen)\n\nfor (let entry from key.enum)\n console.log(entry)\n\n\n// prevent alteration (throws TypeError in strict mode)\nThreeWiseMen.Me = 'Me too!'\nThreeWiseMen.Melchior.name = 'Foo'\n class EnumKey {\n\n constructor(props) { Object.freeze(Object.assign(this, props)) }\n\n toString() { return this.name }\n\n}\n\nexport class Enum {\n\n constructor(...keys) {\n\n for (let [index, key] of keys.entries()) {\n\n Object.defineProperty(this, key, {\n\n value: new EnumKey({ name:key, index, enum:this }),\n enumerable: true,\n\n })\n\n }\n\n Object.freeze(this)\n\n }\n\n *[Symbol.iterator]() {\n\n for (let key of Object.keys(this))\n yield this[key]\n\n }\n\n toString() { return [...this].join(', ') }\n\n}\n" }, { "answer_id": 49309248, "author": "Govind Rai", "author_id": 2757916, "author_profile": "https://Stackoverflow.com/users/2757916", "pm_score": 5, "selected": false, "text": "Object.freeze() class Enum {\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name];\n }\n throw new Error(`No such enumerator: ${name}`);\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n };\n\n return new Proxy(enumObj, handler);\n }\n}\n const roles = new Enum({\n ADMIN: 'Admin',\n USER: 'User',\n});\n undefined undefined // Class for creating enums (13 lines)\n// Feel free to add this to your utility library in \n// your codebase and profit! Note: As Proxies are an ES6 \n// feature, some browsers/clients may not support it and \n// you may need to transpile using a service like babel\n\nclass Enum {\n // The Enum class instantiates a JavaScript Proxy object.\n // Instantiating a `Proxy` object requires two parameters, \n // a `target` object and a `handler`. We first define the handler,\n // then use the handler to instantiate a Proxy.\n\n // A proxy handler is simply an object whose properties\n // are functions which define the behavior of the proxy \n // when an operation is performed on it. \n \n // For enums, we need to define behavior that lets us check what enumerator\n // is being accessed and what enumerator is being set. This can be done by \n // defining \"get\" and \"set\" traps.\n constructor(enumObj) {\n const handler = {\n get(target, name) {\n if (typeof target[name] != 'undefined') {\n return target[name]\n }\n throw new Error(`No such enumerator: ${name}`)\n },\n set() {\n throw new Error('Cannot add/update properties on an Enum instance after it is defined')\n }\n }\n\n\n // Freeze the target object to prevent modifications\n return new Proxy(enumObj, handler)\n }\n}\n\n\n// Now that we have a generic way of creating Enums, lets create our first Enum!\nconst httpMethods = new Enum({\n DELETE: \"DELETE\",\n GET: \"GET\",\n OPTIONS: \"OPTIONS\",\n PATCH: \"PATCH\",\n POST: \"POST\",\n PUT: \"PUT\"\n})\n\n// Sanity checks\nconsole.log(httpMethods.DELETE)\n// logs \"DELETE\"\n\ntry {\n httpMethods.delete = \"delete\"\n} catch (e) {\nconsole.log(\"Error: \", e.message)\n}\n// throws \"Cannot add/update properties on an Enum instance after it is defined\"\n\ntry {\n console.log(httpMethods.delete)\n} catch (e) {\n console.log(\"Error: \", e.message)\n}\n// throws \"No such enumerator: delete\"" }, { "answer_id": 50115744, "author": "Julius Dzidzevičius", "author_id": 4554116, "author_profile": "https://Stackoverflow.com/users/4554116", "pm_score": 2, "selected": false, "text": "enum var makeEnum = function(obj) {\n obj[ obj['Active'] = 1 ] = 'Active';\n obj[ obj['Closed'] = 2 ] = 'Closed';\n obj[ obj['Deleted'] = 3 ] = 'Deleted';\n}\n makeEnum( NewObj = {} )\n// => {1: \"Active\", 2: \"Closed\", 3: \"Deleted\", Active: 1, Closed: 2, Deleted: 3}\n obj[1] 'Active' obj['foo'] = 1\n// => 1\n" }, { "answer_id": 50355530, "author": "Jack G", "author_id": 5601591, "author_profile": "https://Stackoverflow.com/users/5601591", "pm_score": 5, "selected": false, "text": "ENUM_ INDEX_ ENUM_ INDEX_ ENUMLENGTH_ ENUMLEN_ INDEXLENGTH_ INDEXLEN_ LEN_ LENGTH_ 0 0 == null 0 == false 0 == \"\" === == typeof typeof X == \"string\" === 1 ENUM_ INDEX_ const ENUM_COLORENUM_RED = 0;\nconst ENUM_COLORENUM_GREEN = 1;\nconst ENUM_COLORENUM_BLUE = 2;\nconst ENUMLEN_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n INDEX_ ENUM_ // Precondition: var arr = []; //\narr[INDEX_] = ENUM_;\n ENUM_ const ENUM_PET_CAT = 0,\n ENUM_PET_DOG = 1,\n ENUM_PET_RAT = 2,\n ENUMLEN_PET = 3;\n\nvar favoritePets = [ENUM_PET_CAT, ENUM_PET_DOG, ENUM_PET_RAT,\n ENUM_PET_DOG, ENUM_PET_DOG, ENUM_PET_CAT,\n ENUM_PET_RAT, ENUM_PET_CAT, ENUM_PET_DOG];\n\nvar petsFrequency = [];\n\nfor (var i=0; i<ENUMLEN_PET; i=i+1|0)\n petsFrequency[i] = 0;\n\nfor (var i=0, len=favoritePets.length|0, petId=0; i<len; i=i+1|0)\n petsFrequency[petId = favoritePets[i]|0] = (petsFrequency[petId]|0) + 1|0;\n\nconsole.log({\n \"cat\": petsFrequency[ENUM_PET_CAT],\n \"dog\": petsFrequency[ENUM_PET_DOG],\n \"rat\": petsFrequency[ENUM_PET_RAT]\n}); ENUM_PET_RAT ENUMLEN_PET LEN_ LEN_ (function(window){\n \"use strict\";\n var parseInt = window.parseInt;\n\n // use INDEX_ when representing the index in an array instance\n const INDEX_PIXELCOLOR_TYPE = 0, // is a ENUM_PIXELTYPE\n INDEXLEN_PIXELCOLOR = 1,\n INDEX_SOLIDCOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_SOLIDCOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_SOLIDCOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEXLEN_SOLIDCOLOR = INDEXLEN_PIXELCOLOR+3,\n INDEX_ALPHACOLOR_R = INDEXLEN_PIXELCOLOR+0,\n INDEX_ALPHACOLOR_G = INDEXLEN_PIXELCOLOR+1,\n INDEX_ALPHACOLOR_B = INDEXLEN_PIXELCOLOR+2,\n INDEX_ALPHACOLOR_A = INDEXLEN_PIXELCOLOR+3,\n INDEXLEN_ALPHACOLOR = INDEXLEN_PIXELCOLOR+4,\n // use ENUM_ when representing a mutually-exclusive species or type\n ENUM_PIXELTYPE_SOLID = 0,\n ENUM_PIXELTYPE_ALPHA = 1,\n ENUM_PIXELTYPE_UNKNOWN = 2,\n ENUMLEN_PIXELTYPE = 2;\n\n function parseHexColor(inputString) {\n var rawstr = inputString.trim().substring(1);\n var result = [];\n if (rawstr.length === 8) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 4) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_ALPHA;\n result[INDEX_ALPHACOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_ALPHACOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_ALPHACOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n result[INDEX_ALPHACOLOR_A] = parseInt(rawstr[3], 16) * 0x11;\n } else if (rawstr.length === 6) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr.substring(0,2), 16);\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr.substring(2,4), 16);\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr.substring(4,6), 16);\n } else if (rawstr.length === 3) {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_SOLID;\n result[INDEX_SOLIDCOLOR_R] = parseInt(rawstr[0], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_G] = parseInt(rawstr[1], 16) * 0x11;\n result[INDEX_SOLIDCOLOR_B] = parseInt(rawstr[2], 16) * 0x11;\n } else {\n result[INDEX_PIXELCOLOR_TYPE] = ENUM_PIXELTYPE_UNKNOWN;\n }\n return result;\n }\n\n // the red component of green\n console.log(parseHexColor(\"#0f0\")[INDEX_SOLIDCOLOR_R]);\n // the alpha of transparent purple\n console.log(parseHexColor(\"#f0f7\")[INDEX_ALPHACOLOR_A]); \n // the enumerated array for turquoise\n console.log(parseHexColor(\"#40E0D0\"));\n})(self); 'use strict';(function(e){function d(a){a=a.trim().substring(1);var b=[];8===a.length?(b[0]=1,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16),b[4]=c(a.substring(4,6),16)):4===a.length?(b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16),b[4]=17*c(a[3],16)):6===a.length?(b[0]=0,b[1]=c(a.substring(0,2),16),b[2]=c(a.substring(2,4),16),b[3]=c(a.substring(4,6),16)):3===a.length?(b[0]=0,b[1]=17*c(a[0],16),b[2]=17*c(a[1],16),b[3]=17*c(a[2],16)):b[0]=2;return b}var c=\ne.parseInt;console.log(d(\"#0f0\")[1]);console.log(d(\"#f0f7\")[4]);console.log(d(\"#40E0D0\"))})(self); // JG = Jack Giffin\nconst ENUM_JG_COLORENUM_RED = 0,\n ENUM_JG_COLORENUM_GREEN = 1,\n ENUM_JG_COLORENUM_BLUE = 2,\n ENUMLEN_JG_COLORENUM = 3;\n\n// later on\n\nif(currentColor === ENUM_JG_COLORENUM_RED) {\n // whatever\n}\n\n// PL = Pepper Loftus\n// BK = Bob Knight\nconst ENUM_PL_ARRAYTYPE_UNSORTED = 0,\n ENUM_PL_ARRAYTYPE_ISSORTED = 1,\n ENUM_BK_ARRAYTYPE_CHUNKED = 2, // added by Bob Knight\n ENUM_JG_ARRAYTYPE_INCOMPLETE = 3, // added by jack giffin\n ENUMLEN_PL_COLORENUM = 4;\n\n// later on\n\nif(\n randomArray === ENUM_PL_ARRAYTYPE_UNSORTED ||\n randomArray === ENUM_BK_ARRAYTYPE_CHUNKED\n) {\n // whatever\n}\n /// Hashmaps are slow, even with JIT juice\nvar ref = {};\nref.count = 10;\nref.value = \"foobar\";\n /// Arrays, however, are always lightning fast\nconst INDEX_REFERENCE_COUNT = 0;\nconst INDEX_REFERENCE_VALUE = 1;\nconst INDEXLENGTH_REFERENCE = 2;\n\nvar ref = [];\nref[INDEX_REFERENCE_COUNT] = 10;\nref[INDEX_REFERENCE_VALUE] = \"foobar\";\n /// Hashmaps are slow, even with JIT juice\nvar a={count:10,value:\"foobar\"};\n /// Arrays, however, are always lightning fast\nvar a=[10,\"foobar\"];\n var [variable name] is not defined const ENUM_COLORENUM_RED = 0,\n ENUM_COLORENUM_GREEN = 1,\n ENUM_COLORENUM_BLUE = 2,\n ENUMLEN_COLORENUM = 3;\nvar currentColor = ENUM_COLORENUM_GREEN;\n\nif(currentColor === ENUM_COLORENUM_RED) {\n // whatever\n}\n\nif(currentColor === ENUM_COLORENUM_DNE) {\n // whatever\n} ENUM_COLORENUM_DNE" }, { "answer_id": 52019639, "author": "jamess", "author_id": 4941356, "author_profile": "https://Stackoverflow.com/users/4941356", "pm_score": 0, "selected": false, "text": "if (value & Ez.G) {...}\n class Ez {\nconstructor() {\n let rgba = [\"R\", \"G\", \"B\", \"A\"];\n let rgbm = rgba.slice();\n rgbm.push(\"M\"); // for feColorMatrix values attribute\n this.createValues(rgba);\n this.createValues([\"H\", \"S\", \"L\"]);\n this.createValues([rgba, rgbm]);\n this.createValues([attX, attY, attW, attH]);\n}\ncreateValues(a) { // a for array\n let i, j;\n if (isA(a[0])) { // max 2 dimensions\n let k = 1;\n for (i of a[0]) {\n for (j of a[1]) {\n this[i + j] = k;\n k *= 2;\n }\n }\n }\n else { // 1D array is simple loop\n for (i = 0, j = 1; i < a.length; i++, j *= 2)\n this[a[i]] = j;\n }\n}\n" }, { "answer_id": 52409064, "author": "papiro", "author_id": 3878933, "author_profile": "https://Stackoverflow.com/users/3878933", "pm_score": 2, "selected": false, "text": "class Enum {\n constructor (...vals) {\n vals.forEach( val => {\n const CONSTANT = Symbol(val);\n Object.defineProperty(this, val.toUpperCase(), {\n get () {\n return CONSTANT;\n },\n set (val) {\n const enum_val = \"CONSTANT\";\n // generate TypeError associated with attempting to change the value of a constant\n enum_val = val;\n }\n });\n });\n }\n}\n const COLORS = new Enum(\"red\", \"blue\", \"green\");\n" }, { "answer_id": 55695903, "author": "oluckyman", "author_id": 823778, "author_profile": "https://Stackoverflow.com/users/823778", "pm_score": 1, "selected": false, "text": "const modes = ['DRAW', 'SCALE', 'DRAG'].reduce((o, v) => ({ ...o, [v]: v }), {});\n {\n DRAW: 'DRAW',\n SCALE: 'SCALE',\n DRAG: 'DRAG'\n}\n" }, { "answer_id": 60309416, "author": "Andrew", "author_id": 1599699, "author_profile": "https://Stackoverflow.com/users/1599699", "pm_score": 3, "selected": false, "text": "colors.RED colors[\"RED\"] colors[0] toString() valueOf() class Enums {\n static create({ name = undefined, items = [] }) {\n let newEnum = {};\n newEnum.length = items.length;\n newEnum.items = items;\n for (let itemIndex in items) {\n //Map by name.\n newEnum[items[itemIndex]] = parseInt(itemIndex, 10);\n //Map by index.\n newEnum[parseInt(itemIndex, 10)] = items[itemIndex];\n }\n newEnum.toString = Enums.enumToString.bind(newEnum);\n newEnum.valueOf = newEnum.toString;\n //Optional naming and global registration.\n if (name != undefined) {\n newEnum.name = name;\n Enums[name] = newEnum;\n }\n //Prevent modification of the enum object.\n Object.freeze(newEnum);\n return newEnum;\n }\n static enumToString() {\n return \"Enum \" +\n (this.name != undefined ? this.name + \" \" : \"\") +\n \"[\" + this.items.toString() + \"]\";\n }\n}\n let colors = Enums.create({\n name: \"COLORS\",\n items: [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\n});\n\n//Global access, if named.\nEnums.COLORS;\n\ncolors.items; //Array(4) [ \"RED\", \"GREEN\", \"BLUE\", \"PORPLE\" ]\ncolors.length; //4\n\ncolors.RED; //0\ncolors.GREEN; //1\ncolors.BLUE; //2\ncolors.PORPLE; //3\ncolors[0]; //\"RED\"\ncolors[1]; //\"GREEN\"\ncolors[2]; //\"BLUE\"\ncolors[3]; //\"PORPLE\"\n\ncolors.toString(); //\"Enum COLORS [RED,GREEN,BLUE,PORPLE]\"\n\n//Enum frozen, makes it a real enum.\ncolors.RED = 9001;\ncolors.RED; //0\n" }, { "answer_id": 62358238, "author": "Aral Roca", "author_id": 4467741, "author_profile": "https://Stackoverflow.com/users/4467741", "pm_score": 3, "selected": false, "text": "const [CATS, DOGS, BIRDS] = ENUM();\n function * ENUM(count=1) { while(true) yield count++ }\n 1" }, { "answer_id": 62929829, "author": "Idan", "author_id": 6591688, "author_profile": "https://Stackoverflow.com/users/6591688", "pm_score": 0, "selected": false, "text": "export const ButtonType = Object.freeze({ \n DEFAULT: 'default', \n BIG: 'big', \n SMALL: 'small'\n})\n" }, { "answer_id": 64416419, "author": "dsanchez", "author_id": 1514122, "author_profile": "https://Stackoverflow.com/users/1514122", "pm_score": 2, "selected": false, "text": "class Sizes {\n // Private Fields\n static #_SMALL = 0;\n static #_MEDIUM = 1;\n static #_LARGE = 2;\n\n // Accessors for \"get\" functions only (no \"set\" functions)\n static get SMALL() { return this.#_SMALL; }\n static get MEDIUM() { return this.#_MEDIUM; }\n static get LARGE() { return this.#_LARGE; }\n}\n Sizes.SMALL; // 0\nSizes.MEDIUM; // 1\nSizes.LARGE; // 2\n Sizes.SMALL = 10 // Sizes.SMALL is still 0\nSizes._SMALL = 10 // Sizes.SMALL is still 0\nSizes.#_SMALL = 10 // Sizes.SMALL is still 0\n" }, { "answer_id": 64631389, "author": "KooiInc", "author_id": 58186, "author_profile": "https://Stackoverflow.com/users/58186", "pm_score": 0, "selected": false, "text": "Enum /*\n * Notes: \n * The proxy handler enables case insensitive property queries\n * BigInt is used to enable bitflag strings /w length > 52\n*/\nfunction EnumFactory() {\n const proxyfy = {\n construct(target, args) { \n const caseInsensitiveHandler = { \n get(target, key) {\n return target[key.toUpperCase()] || target[key]; \n } \n };\n const proxified = new Proxy(new target(...args), caseInsensitiveHandler ); \n return Object.freeze(proxified);\n },\n }\n const ProxiedEnumCtor = new Proxy(EnumCtor, proxyfy);\n const throwIf = (\n assertion = false, \n message = `Unspecified error`, \n ErrorType = Error ) => \n assertion && (() => { throw new ErrorType(message); })();\n const hasFlag = (val, sub) => {\n throwIf(!val || !sub, \"valueIn: missing parameters\", RangeError);\n const andVal = (sub & val);\n return andVal !== BigInt(0) && andVal === val;\n };\n\n function EnumCtor(values) {\n throwIf(values.constructor !== Array || \n values.length < 2 || \n values.filter( v => v.constructor !== String ).length > 0,\n `EnumFactory: expected Array of at least 2 strings`, TypeError);\n const base = BigInt(1);\n this.NONE = BigInt(0);\n values.forEach( (v, i) => this[v.toUpperCase()] = base<<BigInt(i) );\n }\n\n EnumCtor.prototype = {\n get keys() { return Object.keys(this).slice(1); },\n subset(sub) {\n const arrayValues = this.keys;\n return new ProxiedEnumCtor(\n [...sub.toString(2)].reverse()\n .reduce( (acc, v, i) => ( +v < 1 ? acc : [...acc, arrayValues[i]] ), [] )\n );\n },\n getLabel(enumValue) {\n const tryLabel = Object.entries(this).find( value => value[1] === enumValue );\n return !enumValue || !tryLabel.length ? \n \"getLabel: no value parameter or value not in enum\" :\n tryLabel.shift();\n },\n hasFlag(val, sub = this) { return hasFlag(val, sub); },\n };\n \n return arr => new ProxiedEnumCtor(arr);\n}\n" }, { "answer_id": 71026153, "author": "Sebastian Norr", "author_id": 7880517, "author_profile": "https://Stackoverflow.com/users/7880517", "pm_score": 0, "selected": false, "text": "const Summer1 = Symbol(\"summer\")\nconst Summer2 = Symbol(\"summer\")\n\n// Even though they have the same apparent value\n// Summer1 and Summer2 don't equate\nconsole.log(Summer1 === Summer2)\n// false\n\nconsole.log(Summer1)\n const Summer = Symbol(\"summer\")\nconst Autumn = Symbol(\"autumn\")\nconst Winter = Symbol(\"winter\")\nconst Spring = Symbol(\"spring\")\n\nlet season = Spring\n\nswitch (season) {\n case Summer:\n console.log('the season is summer')\n break;\n case Winter:\n console.log('the season is winter')\n break;\n case Spring:\n console.log('the season is spring')\n break;\n case Autumn:\n console.log('the season is autumn')\n break;\n default:\n console.log('season not defined')\n}\n // Season enums can be grouped as static members of a class\nclass Season {\n // Create new instances of the same class as static attributes\n static Summer = new Season(\"summer\")\n static Autumn = new Season(\"autumn\")\n static Winter = new Season(\"winter\")\n static Spring = new Season(\"spring\")\n\n constructor(name) {\n this.name = name\n }\n}\n\n// Now we can access enums using namespaced assignments\n// this makes it semantically clear that \"Summer\" is a \"Season\"\nlet season = Season.Summer\n\n// We can verify whether a particular variable is a Season enum\nconsole.log(season instanceof Season)\n// true\nconsole.log(Symbol('something') instanceof Season)\n//false\n\n// We can explicitly check the type based on each enums class\nconsole.log(season.constructor.name)\n// 'Season'\n this.name .description Seasons.summer.name Seasons.summer constructor(name) {\n this.name = Symbol(name).description\n }\n Object.keys(Season).forEach(season => console.log(\"season:\", season))\n// season: Summer\n// season: Autumn\n// season: Winter\n// season: Spring\n" }, { "answer_id": 71432477, "author": "LEMUEL ADANE", "author_id": 1347816, "author_profile": "https://Stackoverflow.com/users/1347816", "pm_score": 2, "selected": false, "text": "export const ColorEnum = Object.freeze({\n // you can only change the property values here\n // in the object declaration like in the Java enumaration\n RED: 0,\n GREEN: 1,\n BLUE: 2,\n});\n\nColorEnum.RED = 22 // assigning here will throw an error\nColorEnum.VIOLET = 45 // even adding a new property will throw an error\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16071/" ]
287,928
<p>DataGridView, for example, lets you do this:</p> <pre><code>DataGridView dgv = ...; DataGridViewCell cell = dgv[1,5]; </code></pre> <p>but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?</p> <p>ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like <code>public object this[int x, int y]{ get{...}; set{...} }</code>; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.</p> <p>ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.</p>
[ { "answer_id": 287938, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 5, "selected": false, "text": "Operators Overloadability\n\n+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.\n\n+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.\n\n==, !=, <, >, <= , >= All relational operators can be overloaded, \n but only as pairs.\n\n&&, || They can't be overloaded\n\n() (Conversion operator) They can't be overloaded\n\n+=, -=, *=, /=, %= These compound assignment operators can be \n overloaded. But in C#, these operators are\n automatically overloaded when the respective\n binary operator is overloaded.\n\n=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded\n\n [ ] Can be overloaded but not always!\n public Object this[int index]\n{\n \n}\n" }, { "answer_id": 287945, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 3, "selected": false, "text": "public class CustomCollection : List<Object>\n{\n public Object this[int index]\n {\n // ...\n }\n}\n" }, { "answer_id": 287946, "author": "Ruben", "author_id": 21733, "author_profile": "https://Stackoverflow.com/users/21733", "pm_score": 10, "selected": true, "text": "public object this[int i]\n{\n get { return InnerList[i]; }\n set { InnerList[i] = value; }\n}\n" }, { "answer_id": 287948, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 5, "selected": false, "text": "public T Item[int index, int y]\n{ \n //Then do whatever you need to return/set here.\n get; set; \n}\n" }, { "answer_id": 287952, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 2, "selected": false, "text": " public object this[int index]\n {\n get { return ( List[index] ); }\n set { List[index] = value; }\n }\n" }, { "answer_id": 287959, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "public class EmployeeCollection: List<Employee>\n{\n public Employee this[int employeeId]\n { \n get \n { \n foreach(var emp in this)\n {\n if (emp.EmployeeId == employeeId)\n return emp;\n }\n\n return null;\n }\n }\n\n public Employee this[string employeeName]\n { \n get \n { \n foreach(var emp in this)\n {\n if (emp.Name == employeeName)\n return emp;\n }\n\n return null;\n }\n }\n}\n" }, { "answer_id": 310114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "ref class Class\n{\n public:\n property System::String^ default[int i]\n {\n System::String^ get(int i) { return \"hello world\"; }\n }\n};\n" }, { "answer_id": 34098286, "author": "amoss", "author_id": 208068, "author_profile": "https://Stackoverflow.com/users/208068", "pm_score": 4, "selected": false, "text": "public object this[int i] => this.InnerList[i];" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
287,954
<p>To add a NOT NULL Column to a table with many records, a DEFAULT constraint needs to be applied. This constraint causes the entire ALTER TABLE command to take a long time to run if the table is very large. This is because:</p> <p>Assumptions:</p> <ol> <li>The DEFAULT constraint modifies existing records. This means that the db needs to increase the size of each record, which causes it to shift records on full data-pages to other data-pages and that takes time.</li> <li>The DEFAULT update executes as an atomic transaction. This means that the transaction log will need to be grown so that a roll-back can be executed if necessary.</li> <li>The transaction log keeps track of the entire record. Therefore, even though only a single field is modified, the space needed by the log will be based on the size of the entire record multiplied by the # of existing records. This means that adding a column to a table with small records will be faster than adding a column to a table with large records even if the total # of records are the same for both tables.</li> </ol> <p>Possible solutions:</p> <ol> <li>Suck it up and wait for the process to complete. Just make sure to set the timeout period to be very long. The problem with this is that it may take hours or days to do depending on the # of records.</li> <li>Add the column but allow NULL. Afterward, run an UPDATE query to set the DEFAULT value for existing rows. Do not do UPDATE *. Update batches of records at a time or you'll end up with the same problem as solution #1. The problem with this approach is that you end up with a column that allows NULL when you know that this is an unnecessary option. I believe that there are some best practice documents out there that says that you should not have columns that allow NULL unless it's necessary.</li> <li>Create a new table with the same schema. Add the column to that schema. Transfer the data over from the original table. Drop the original table and rename the new table. I'm not certain how this is any better than #1.</li> </ol> <p>Questions:</p> <ol> <li>Are my assumptions correct? </li> <li>Are these my only solutions? If so, which one is the best? I f not, what else could I do?</li> </ol>
[ { "answer_id": 288717, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": -1, "selected": false, "text": "-- without NOT NULL constrain -- we will add it in the end\nALTER TABLE table ADD new_column INT DEFAULT 0\n\nDECLARE fillNullColumn CURSOR LOCAL FAST_FORWARD\n SELECT \n key\n FROM\n table WITH (NOLOCK)\n WHERE\n new_column IS NULL\n\nOPEN fillNullColumn\n\nDECLARE \n @key INT\n\nFETCH NEXT FROM fillNullColumn INTO @key\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n UPDATE\n table WITH (ROWLOCK)\n SET\n new_column = 0 -- default value\n WHERE\n key = @key\n\n WAIT 00:00:05 --wait 5 seconds, keep in mind it causes updating only 12 rows per minute\n\n FETCH NEXT FROM fillNullColumn INTO @key\nEND\n\nCLOSE fillNullColumn\nDEALLOCATE fillNullColumn\n\nALTER TABLE table ALTER COLUMN new_column ADD CONSTRAIN xxx\n" }, { "answer_id": 649136, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 0, "selected": false, "text": "Alter table MyTable\nAdd MyNewColumn char(10) null default '?';\ngo\n\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 0 and 1000000\ngo\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 1000000 and 2000000\ngo\nupdate MyTable set MyNewColumn='?' where MyPrimaryKey between 2000000 and 3000000\ngo\n..etc..\n\nAlter table MyTable\nAlter column MyNewColumn char(10) not null;\n" }, { "answer_id": 1151157, "author": "DHornpout", "author_id": 21268, "author_profile": "https://Stackoverflow.com/users/21268", "pm_score": 7, "selected": true, "text": "ALTER TABLE MyTable ADD MyColumn varchar(40) DEFAULT('')\n NOT NULL NOCHECK NOCHECK ALTER TABLE MyTable WITH NOCHECK\nADD CONSTRAINT MyColumn_NOTNULL CHECK (MyColumn IS NOT NULL)\n GO\nUPDATE TOP(3000) MyTable SET MyColumn = '' WHERE MyColumn IS NULL\nGO 1000\n GO 1000" }, { "answer_id": 14194691, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 2, "selected": false, "text": "GETDATE() NEWID() sys.system_internals_partition_columns" }, { "answer_id": 19141346, "author": "Tanya Kogan", "author_id": 2576551, "author_profile": "https://Stackoverflow.com/users/2576551", "pm_score": 0, "selected": false, "text": " SELECT table.*, cast (‘default’ as nvarchar(256)) new_column\n INTO table_copy \n FROM table\n DROP TABLE table\n EXEC sp_rename 'table_copy', ‘table’\n" }, { "answer_id": 30443744, "author": "Kenneth Xu", "author_id": 111877, "author_profile": "https://Stackoverflow.com/users/111877", "pm_score": 1, "selected": false, "text": "Alter table mytable add mycolumn char(1) not null default('N');\n" }, { "answer_id": 40552829, "author": "hobbsenigma", "author_id": 861894, "author_profile": "https://Stackoverflow.com/users/861894", "pm_score": 0, "selected": false, "text": "ALTER TABLE MyTable ADD MyColumn int default 0\n declare @rowcount int = 1\n\nwhile (@rowcount > 0)\nbegin \n\n UPDATE TOP(10000) MyTable SET MyColumn = 0 WHERE MyColumn IS NULL \n set @rowcount = @@ROWCOUNT\n\nend\n ALTER TABLE MyTable ALTER COLUMN MyColumn int NOT NULL\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13484/" ]
287,960
<p>I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?</p>
[ { "answer_id": 288083, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "for(var i=0; i<ary.length; i++)\n // assuming that ary[] contains objects with a DoSometing() method\n ary[i].doSomething(); \n" }, { "answer_id": 288831, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 3, "selected": false, "text": "function setDisplay(el, display) {\n el.style.display = display;\n}\n\nYAHOO.util.Dom.batch(document.getElementsByTagName('div'), setDisplay, 'none');\n" }, { "answer_id": 4388875, "author": "Witek", "author_id": 176336, "author_profile": "https://Stackoverflow.com/users/176336", "pm_score": 2, "selected": false, "text": "Y.Array.each(myArray, function(element) {\n Y.log(element);\n});\n Y.Array.each(myArray, function(element, index, array) {\n ...\n});\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
287,965
<p>I have two tables: Client(id,name,...)<br> Purchase(id,item,date,client_id,...)</p> <p>They have their respective Model, with their validations. What I need is to create a new client with a new purchase, all into the create method of Client controller. Something like this:</p> <pre><code>def create @client = Client.new(params[:client]) respond_to do |format| if @client.save # Add purchase @sell = Purchase.new @sell.client_id = @client.id @sell.date = params[:date] # Fill another fields if @sell.save # Do another stuff... else format.html { render :action =&gt; "new" } format.xml { render :xml =&gt; @client.errors, :status =&gt; :unprocessable_entity } end flash[:notice] = 'You have a new client!' format.html { redirect_to(:action =&gt; :show, :id =&gt; @evento.id) } format.xml { render :xml =&gt; @client, :status =&gt; :created, :location =&gt; @client } else format.html { render :action =&gt; "new" } format.xml { render :xml =&gt; @evento.client, :status =&gt; :unprocessable_entity } end end end </code></pre> <p>In Purchase's model I have:</p> <pre><code>belongs_to :client validates_format_of :date, :with =&gt; /^20[0-9]{2}[-][0-9]{2}[-][0-9]{2}$/, :message =&gt; 'not valid' validates_presence_of :date </code></pre> <p>And there is my problem: how can I validate the date input, through validations into the model, from Client controller? And, how can I rollback the new client created when errors?</p> <p>Yes, I can do the check as the very first instruction in the method, with a regular expression, but I think it's ugly. I feel like might exist a conventional method for doing this validation or even doing all the stuff in another way (i.e. calling create method for Purchase from Client controller).</p> <p>Can you put me back in the right way?</p> <p>Thank you in advance.</p>
[ { "answer_id": 288026, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": true, "text": "Client.purchases.empty?\nClient.purchases.size,\nClient.purchases\nClient.purchases<<(purchase)\nClient.purchases.delete(purchase)\nClient.purchases.find(purchases_id)\nClient.purchases.find_all(conditions)\nClient.purchases.build\nClient.purchases.create\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36599/" ]
287,976
<p>I'd like to make an (MS)SQL query that returns something like this:</p> <pre><code>Col1 Col2 Col3 ---- --------------------- ------ AAA 18.92 18.92 BBB 20.00 40.00 AAA 30.84 30.84 BBB 06.00 12.00 AAA 30.84 30.84 AAA 46.79 46.79 AAA 86.40 86.40 </code></pre> <p>where Col3 is equal to Col2 when Col1 = AAA and Col3 is twice Col2 when Col1 = BBB. Can someone point me in the rigth direction please?</p>
[ { "answer_id": 287982, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": true, "text": "SELECT Col1, Col2, \n CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3\nFROM ...\n" }, { "answer_id": 287985, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "select *\nfrom yourtable\nwhere (Col3 = col2 AND Col1 = 'AAA') OR\n (Col3 = (2*Col2) AND Col1='BBB')\n" }, { "answer_id": 287989, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 2, "selected": false, "text": "Select Col1, Col2, \n Case When Col1 = 'AAA' Then Col2 Else Col2 * 2 End As Col3\nFrom YourTable\n" }, { "answer_id": 6329839, "author": "Pankaj Awasthi", "author_id": 522781, "author_profile": "https://Stackoverflow.com/users/522781", "pm_score": 0, "selected": false, "text": "null select Address1 + (case when Address2='' then '' else ', '+Address2 end) + \n (case when Address3='' then '' else ', '+ Address3 end) as FullAddress from users\n" }, { "answer_id": 9335321, "author": "Draugnar", "author_id": 1217143, "author_profile": "https://Stackoverflow.com/users/1217143", "pm_score": 3, "selected": false, "text": "ISNULL COALESCE SELECT ISNULL(Col1, 'AAA') AS Col1, \n ISNULL(Col2, 0) AS Col2,\n CASE WHEN ISNULL(Col1, 'AAA') = 'BBB' THEN ISNULL(Col2, 0) * 2 \n ELSE ISNULL(Col2) \n END AS Col3\nFROM Tablename\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34632/" ]
287,986
<p>Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:</p> <pre><code>http://foo.com?x[]=1&amp;x[]=5&amp;x[]=bar </code></pre> <p>This would get converted into the following array:</p> <pre><code>['1','5','bar'] </code></pre> <p>Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter? For example, It would be nice to do something like the following:</p> <pre><code>var s:HTTPService = new HTTPService(); s.request['x[]'] = 1; s.request['x[]'] = 5; s.request['x[]'] = 'bar'; </code></pre> <p>However, that will simply overwrite each value, resulting in only the last value being sent. Anyone have a better idea? I know I could just append stuff to the query string, but I'd like to do it in the POST body.</p>
[ { "answer_id": 288004, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "\nvar s:HTTPService = new HTTPService();\ns.url = \"http://foo.com\";\ns.method = \"post\";\n// add listeners...\ns.addEventListenser(ResultEvent.RESULT,function(event:ResultEvent){\n\n mx.controls.Alert.show(event.result.toString());\n});\n\n// send the data...\ns.send({\n a: 1,\n b: 5,\n c: \"bar\"\n});\n\n \n\nvar postdata:Object = {};\n\npostdata[\"a\"] = 1;\npostdata[\"b\"] = 5;\npostdata[\"c\"] = \"bar\";\n\n// s is the HTTPService from above...\ns.send(postdata);\n\n" }, { "answer_id": 410945, "author": "bartv", "author_id": 51371, "author_profile": "https://Stackoverflow.com/users/51371", "pm_score": 3, "selected": true, "text": "var service:HTTPService = new HTTPService();\nservice.useProxy = true;\nservice.destination = \"myservicet\";\nservice.resultFormat = HTTPService.RESULT_FORMAT_XML;\n\nvar fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = new Object();\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field\"] = fields;\nservice.send(params);\n" }, { "answer_id": 1392977, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var params:Object = new Object;\nfor (var i:uint=0; i<31; i++){\n params[\"Date\"+(jj.toString())] = date[i];\n}\n\nHTTPService....etc.\nHTTPService.send(params);\n Date0...Date31" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19964/" ]
287,991
<p>How can I match (PCRE) everything inbetween two tags?</p> <p>I tried something like this:</p> <blockquote> <p>&lt;!--\s&#42;LoginStart\s&#42;--&gt;(.*)&lt;!--\s&#42;LoginEnd\s&#42;--&gt;</p> </blockquote> <p>But it didn't work out too well for me..</p> <p>I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.</p> <p>Thanks</p>
[ { "answer_id": 288006, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 1, "selected": false, "text": "'/<!--\\s*LoginStart\\s*-->(.*)<!--\\s*LoginEnd\\s*-->/Us'\n U <!-- s . i" }, { "answer_id": 288015, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "$string = '<!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds -->';\n$regex = '#<!--\\s*LoginStart\\s*-->(.*?)<!--\\s*LoginEnds\\s*-->#s';\n\npreg_match($regex, $string, $matches);\n\nprint_r($matches); // $matches[1] = <div id=\"stuff\">text</div>\n (.*?) = non greedy match (match the first <!-- LoginEnds --> it finds\n s = modifier in $regex (end of the variable) allows multiline matches\n such as '<!-- LoginStart -->stuff\n more stuff\n <!-- LoginEnds -->'\n" }, { "answer_id": 4214104, "author": "Gnanz", "author_id": 512008, "author_profile": "https://Stackoverflow.com/users/512008", "pm_score": 0, "selected": false, "text": "<!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds -->\"DONT MIND THIS\"<!-- LoginStart --><div id=\"stuff\">text</div><!-- LoginEnds -->" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37439/" ]
288,007
<pre><code>SELECT DISTINCT 'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || rpad(licensing_no,30) || rpad(' ',300) AS RECORD FROM APPS WHERE L_code = '1000' AND licensing_no IS NOT NULL </code></pre> <p>This seems to be the primary culprit in why I cannot export these records to a textfile in my development environment. Is there any way I can get this query to run quicker. It returns roughly 2000+ lines of text. </p>
[ { "answer_id": 289075, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "explain plan for SELECT DISTINCT \n'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE L_code = '1000' AND licensing_no IS NOT NULL\n/\n\nselect * from table(dbms_xplan.display)\n/\n explain plan for SELECT /*+ dynamic_sampling(4) */ DISTINCT \n'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE L_code = '1000' AND licensing_no IS NOT NULL\n/\n\nselect * from table(dbms_xplan.display)\n/\n" }, { "answer_id": 289240, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT \n 'LRS-TECH 1' || rpad(code,7) || rpad('APPTYPE',30) || \n rpad(licensing_no,30) || rpad(' ',300) AS RECORD \nFROM APPS\nWHERE DECODE(L_code,'1000',licensing_no,NULL) IS NOT NULL;\n" }, { "answer_id": 296871, "author": "user34850", "author_id": 34850, "author_profile": "https://Stackoverflow.com/users/34850", "pm_score": 2, "selected": false, "text": "SELECT 'LRS-TECH 1'\n || RPAD (code, 7)\n || RPAD ('APPTYPE', 30)\n || RPAD (licensing_no, 30)\n || RPAD (' ', 300) AS RECORD\n FROM (SELECT DISTINCT code, licensing_no\n FROM apps\n WHERE l_code = '1000' AND licensing_no IS NOT NULL)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,009
<p>So, I've been tasked with making a kiosk for the office for showing statistics about our SCRUM progress, build server status, rentability and so forth. It should ideally run a slideshow with bunch of different pages, some of them showing text, some showing graphs and so on. </p> <p>What is the best approach for this? I first thought of powerpoint, but It should be able to take the images from a webserver so I can automate the graph generation procedure. I would also like to take text from an external source when showing "Who broke the build" or some page like that.</p> <p>I have no doubt that ready-made systems exist, but I don't really know where to look for them.</p> <p>Is this easy/hard in powerpoint? Or are there an ubiquous app that everybody but me knows about?</p>
[ { "answer_id": 289219, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": true, "text": "<img> slide001.htm slide002.htm slide003.htm <img src=\"http://hudson.abc/job/proj042/buildTimeGraph\"> .php <?PHP echo(who_broke_build()); ?>" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24610/" ]
288,020
<p>I found one source which successfully overrode <code>Time.strftime</code> like this:</p> <pre><code>class Time alias :old_strftime :strftime def strftime #do something old_strftime end end </code></pre> <p>The trouble is, <code>strftime</code> is an instance method. I need to override <code>Time.now</code> - a class method - in such away that any caller gets my new method, while the new method still calls the original <code>.now</code> method. I've looked at <code>alias_method</code> and have met with no success.</p>
[ { "answer_id": 288077, "author": "Austin Ziegler", "author_id": 36378, "author_profile": "https://Stackoverflow.com/users/36378", "pm_score": 2, "selected": false, "text": "class Time\n class << self\n alias_method :old_time_now, :now\n\n def now\n my_now = old_time_now\n # new code\n my_now\n end\n end\nend\n\nclass << Time\n alias_method :old_time_now, :now\n\n def now\n my_now = old_time_now\n # new code\n my_now\n end\nend\n" }, { "answer_id": 288088, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 5, "selected": true, "text": "class Time\n alias :old_strftime :strftime\n\n def strftime\n puts \"got here\"\n old_strftime\n end\nend\n\nclass Time\n class << self\n alias :old_now :now\n def now\n puts \"got here too\"\n old_now\n end\n end\nend\n\nt = Time.now\nputs t.strftime\n" }, { "answer_id": 288103, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 1, "selected": false, "text": "Time.stub!(:now).and_return(Time.mktime(1970,1,1))\n class Foo\n def initialize(clock=Time)\n @clock = clock\n end\n\n def do_something\n time = @clock.now\n # ...\n end\nend\n" }, { "answer_id": 3393550, "author": "Federico Ramallo", "author_id": 237975, "author_profile": "https://Stackoverflow.com/users/237975", "pm_score": 0, "selected": false, "text": "module Mo\n def self.included(base)\n base.instance_eval do\n alias :old_time_now :now\n def now\n my_now = old_time_now\n puts 'overrided now'\n # new code\n my_now\n end\n end\n end\nend\nTime.send(:include, Mo) unless Time.include?(Mo)\n\n> Time.now\noverrided now\n=> Mon Aug 02 23:12:31 -0500 2010\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30997/" ]
288,027
<p>In Object Oriented Paradigm, I would create an object/conceptual model before I start implementing it using OO language.</p> <p>Is there anything parallel to object model in functional programming. Is it called functional model? or we create the same conceptual model in both the paradigm before implementing it in one of the language.. </p> <p>Are there articles/books where I can read about functional model in case it exist? </p> <p>or to put it in different way... even if we are using functional programming language, would we start with object model?</p>
[ { "answer_id": 333145, "author": "Daishiman", "author_id": 42345, "author_profile": "https://Stackoverflow.com/users/42345", "pm_score": 3, "selected": false, "text": "-nil\n-bin(left:bt, root: a, right:bt)\n numberOfNodes(nil) == 0\nnumberOfNodes(bin(left,x,right))== 1 + numberOfNodes(left) + numberOfNodes(right)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30917/" ]
288,034
<p>I need some help regarding algorithm for randomness. So Problem is.</p> <p>There are 50 events going to happen in 8 hours duration. Events can happen at random times. Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736. How can I do this with random generation algorithm?</p> <p>I can get random number </p> <pre><code>int r = rand(); double chance = r/RAND_MAX; if(chance &lt; 0.001736) then event happens else no event </code></pre> <p>But most of times rand() returns 0 and 0&lt;0.001736 and I am getting more events than required.</p> <p>Any suggestions?</p> <hr> <p>sorry I forget to mention I calculated chance as double chance = (static_cast )(r) / (static_cast)(RAND_MAX);</p> <hr> <p>It removed double from static_cast</p> <p>double chance = (double)r/(double)(RAND_MAX);</p>
[ { "answer_id": 288046, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "r RAND_MAX double chance = r / RAND_MAX;\n double chance = 1.0 * r / RAND_MAX;\n" }, { "answer_id": 288133, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 2, "selected": false, "text": " double u;\n do\n {\n // Get a uniformally-distributed random double between\n // zero (inclusive) and 1 (exclusive)\n u = rng.nextDouble();\n } while (u == 0d); // Reject zero, u must be +ve for this to work.\n return (-Math.log(u)) / rate;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
288,038
<p>I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes. Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.</p> <p>Is there a function available in the CRT or somewhere in the linux headers to safely escape a string to pass to the command line ?</p>
[ { "answer_id": 288067, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "'...' ' '\"'\"' system(\"mplayer 'foo'\\\"'\\\"' bar'\"); foo bar \" \\n \" \\\"" }, { "answer_id": 288071, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "'\"'\"' \"'\"" }, { "answer_id": 288203, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 3, "selected": false, "text": "void play(const char *path)\n{\n /* Fork, then exec */\n pid = fork();\n\n if( pid < 0 ) { \n /* This is an error! */\n return;\n } \n\n if( pid == 0 ) { \n /* This is the child */\n freopen( \"/dev/null\", \"r\", stdin );\n freopen( \"/dev/null\", \"w\", stdout );\n freopen( \"/dev/null\", \"w\", stderr );\n\n execlp( \"mplayer\", \"mplayer\", path, (char *)0 );\n /* This is also an error! */\n return;\n }\n}\n" }, { "answer_id": 38546462, "author": "over_optimistic", "author_id": 884893, "author_profile": "https://Stackoverflow.com/users/884893", "pm_score": 0, "selected": false, "text": "#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <sys/stat.h>\n#include <vector>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <string.h>\n\nstd::vector<std::string> split(std::string delimiter, std::string str){\n std::size_t nextPos = 0;\n std::size_t delimiterSize = delimiter.size();\n std::vector<std::string> list;\n while(true){\n std::size_t pos = str.find(delimiter, nextPos);\n std::string subStr;\n\n if(pos == std::string::npos){\n list.push_back(str.substr(nextPos));\n break;\n }\n subStr = str.substr(nextPos, pos - nextPos);\n list.push_back(subStr);\n\n nextPos = pos + delimiterSize;\n }\n return list;\n}\n\n\nbool isFileExecutable(const std::string &file)\n{\n struct stat st;\n\n if (stat(file.c_str(), &st) < 0)\n return false;\n if ((st.st_mode & S_IEXEC) != 0)\n return true;\n return false;\n}\n\nstd::string ensureEndsWithSlash(std::string path){\n if(path[path.length()-1] != '/'){\n path += \"/\";\n }\n return path;\n}\nstd::string findProgram(std::string name){\n // check if it's relative\n if(name.size() > 2){\n if(name[0] == '.' && name[1] == '/'){\n if(isFileExecutable(name)){\n return name;\n }\n return std::string();\n }\n }\n std::vector<std::string> pathEnv = split(\":\", getenv(\"PATH\"));\n for(std::string path : pathEnv){\n path = ensureEndsWithSlash(path);\n path += name;\n if(isFileExecutable(path)){\n return path;\n }\n }\n return std::string();\n}\n\n// terminal condition\nvoid toVector(std::vector<std::string> &vector, const std::string &str){\n vector.push_back(str);\n}\ntemplate<typename ...Args>\nvoid toVector(std::vector<std::string> &vector, const std::string &str, Args ...args){\n vector.push_back(str);\n toVector(vector, args...);\n}\n\nint waitForProcess(pid_t processId){\n if(processId == 0){\n return 0;\n }\n int status = 0;\n int exitCode = -1;\n while(waitpid(processId, &status, 0) != processId){\n // wait for it\n }\n if (WIFEXITED(status)) {\n exitCode = WEXITSTATUS(status);\n }\n return exitCode;\n}\n\n/**\n Runs the process and returns the exit code.\n\n You should change it so you can detect process failure\n vs this function actually failing as a process can return -1 too\n\n @return -1 on failure, or exit code of process.\n*/\ntemplate<typename ...Args>\nint mySystem(Args ...args){\n std::vector<std::string> command;\n toVector(command, args...);\n command[0] = findProgram(command[0]);\n if(command[0].empty()){\n // handle this case by returning error or something\n // maybe std::abort() with error message\n return -1;\n }\n pid_t pid = fork();\n if(pid) {\n // parent wait for child\n return waitForProcess(pid);\n }\n\n // we are child make a C friendly array\n // this process will be replaced so we don't care about memory\n // leaks at this point.\n std::vector<char*> c_command;\n for(int i = 0; i < command.size(); ++i){\n c_command.push_back(strdup(command[i].c_str()));\n }\n // null terminate the sequence\n c_command.push_back(nullptr);\n execvp(c_command[0], &c_command[0]);\n // just incase\n std::abort();\n return 0;\n}\n\n\n\nint main(int argc, char**argv){\n\n // example usage\n mySystem(\"echo\", \"hello\", \"world\");\n\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34014/" ]
288,044
<p>I am using a <code>ListView</code> to display the main screen of my application.<br> The main screen is essentially a <code>menu</code> to get into the different sections of application. Currently, I have the <code>ListView</code> whose contents are added programmatically in the <code>onCreate</code> method. </p> <p>Here is the code snippet that does this:</p> <pre><code>String[] mainItems = { "Inbox", "Projects", "Contexts", "Next Actions" } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new ArrayAdapter&lt;String&gt;( this, android.R.layout.simple_list_item_1, mainItems)); registerForContextMenu(getListView()); } </code></pre> <p>So the menu is essentially just a bunch of nodes with the text contained in the mainItems array. I know that I can create an XML layout (i.e. <code>R.layout.mainMenu_item</code>) that has an ImageView and TextView in it, but I am unsure how to set the ImageView's icon. I have seen that there is a setImageResouce(int resId) method, but the way to use this when generating with an ArrayAdapter is eluding me. Is there a better way to do this?</p>
[ { "answer_id": 339021, "author": "jasonhudgins", "author_id": 24590, "author_profile": "https://Stackoverflow.com/users/24590", "pm_score": 5, "selected": true, "text": "public View getView(int position, View convertView, ViewGroup parent) {\n\n View row = inflater.inflate(R.layout.menu_row, null);\n\n ImageView icon = (ImageView) row.findViewById(R.id.icon);\n icon.setImageResource(..your drawable's id...);\n\n return view;\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37436/" ]
288,045
<p>I am accessing a .NET COM object from C++. I want to know the version information about this COM object. When I open the TLB in OLEVIEW.exe I can see the version information associated with the coclass. How can I access this information from C++? This is the information I get:</p> <pre><code>[ uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX), version(1.0), custom(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, XXXX) ] coclass XXXXXXXX{ [default] interface XXXXXXXX; interface _Object; interface XXXXXXXX; }; </code></pre>
[ { "answer_id": 339021, "author": "jasonhudgins", "author_id": 24590, "author_profile": "https://Stackoverflow.com/users/24590", "pm_score": 5, "selected": true, "text": "public View getView(int position, View convertView, ViewGroup parent) {\n\n View row = inflater.inflate(R.layout.menu_row, null);\n\n ImageView icon = (ImageView) row.findViewById(R.id.icon);\n icon.setImageResource(..your drawable's id...);\n\n return view;\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8661/" ]
288,047
<p>I have some UserControls that I created in ProjectA. I have ProjectB that has a windows form that I want to put the controls on. Both of these projects are in a single solution. There's a reference to ProjectA from ProjectB so it can "see" the UserControls.</p> <p>However, the UserControls do not show up in the toolbox for me to drag to the windows form.</p> <p>I've tried rebuilding. I've also deleted the 'bin' directory to force a rebuild-all.</p> <p>How do I get VS2008 to populate the toolbox with my UserControls?</p>
[ { "answer_id": 1672504, "author": "DavidMB", "author_id": 202441, "author_profile": "https://Stackoverflow.com/users/202441", "pm_score": 1, "selected": false, "text": "MyCustomControls MyCustomControls AutoToolboxPopulate" }, { "answer_id": 8235736, "author": "Dan7", "author_id": 232288, "author_profile": "https://Stackoverflow.com/users/232288", "pm_score": 2, "selected": false, "text": "ToolStripItems ToolStripStatusLabel StatusStrip public using System.Windows.Forms.Design;\n\n[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.StatusStrip)]\npublic class MyStatusLabel : ToolStripStatusLabel\n{\n}\n" }, { "answer_id": 14574122, "author": "Martin", "author_id": 419427, "author_profile": "https://Stackoverflow.com/users/419427", "pm_score": 0, "selected": false, "text": "public UserControl() {\n...\n}\n" }, { "answer_id": 14974559, "author": "Alexa Adrian", "author_id": 999079, "author_profile": "https://Stackoverflow.com/users/999079", "pm_score": 2, "selected": false, "text": "public class yourClass:control {}\n" }, { "answer_id": 18152061, "author": "Forest Kunecke", "author_id": 1822214, "author_profile": "https://Stackoverflow.com/users/1822214", "pm_score": 1, "selected": false, "text": "Properties Build Register for COM interop" }, { "answer_id": 23515942, "author": "user3611840", "author_id": 3611840, "author_profile": "https://Stackoverflow.com/users/3611840", "pm_score": 0, "selected": false, "text": "drive:\\work\\c#\\folder\\ drive:\\work\\folder" }, { "answer_id": 38382479, "author": "Thomas Weller", "author_id": 480982, "author_profile": "https://Stackoverflow.com/users/480982", "pm_score": 1, "selected": false, "text": "x64 devenv.exe *32 Any CPU" }, { "answer_id": 41206423, "author": "Hamed", "author_id": 359170, "author_profile": "https://Stackoverflow.com/users/359170", "pm_score": 1, "selected": false, "text": "[ToolboxItem(true)]\npublic class PanelTitle : LabelControl {\n// Whatever code to override LabelControl here...\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9516/" ]
288,061
<p>I have often wondered why it is that non-English speaking programmers are forced to use a different language when programming when it would seem to be so easy to offer an IDE that could replace keywords with localized versions. Why can't the Germans use a "während..macht" loop?</p> <p>Do programmers in Japan, Germany, France, Spain, Botswana just make extensive use of macros/define statements to make life more tolerable or do they just get used to the functional significance of print, if, then, while, do, begin, end, var, double, function, etc?</p> <p>Perhaps the increased use of frameworks (J2EE/.NET) makes this more complicated, but it still seems worthwhile. On the other hand, if Klingon became the de-facto programming language in the US I'd probably regret suggesting this.</p>
[ { "answer_id": 289056, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "if for" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30018/" ]
288,062
<p>It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?</p> <pre><code>close(fileno(stdin)); fclose(stdin); </code></pre>
[ { "answer_id": 5925575, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 5, "selected": false, "text": "fclose(stdin) stdin close(fileno(stdin)) stdin EBADF int fd = open(\"/dev/null\", O_WRONLY);\ndup2(fd, 0);\nclose(fd);\n O_RDONLY O_WRONLY" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
288,068
<p>I need to add localization to the exceptions thrown by my application as a lot are ApplicationExceptions and handled and logged to an error report. Ideally I want to create a new Exception, imheriting from ApplicationException that I can pass the resource key as well as arguments to, so that the exception messsage can be built up from the resource information. Unfortunately (I think) the only way to set the message in an exception is in the New()...</p> <p>I would like something like:</p> <pre><code>public class LocalizedException Inherits ApplicationException public Sub New(ResourceKey as string, arg0 as Object) MyBase.New() ' get the localized text' Dim ResMan as New Global.System.Resources.ResourceManager("AppName.ExceptionResources", _ System.Reflection.Assembly.GetExecutingAssembly) Dim LocalText as string = ResMan.GetString(ResourceKey) Dim ErrorText as String = "" Try Dim ErrorText = String.Format(LocalText, arg0) Catch ErrorText = LocalText + arg0.ToString() ' in case String.Format fails' End Try ' cannot now set the exception message!' End Sub End Class </code></pre> <p>However I can only have MyBase.New() as the first line Message is ReadOnly</p> <p>Does anyone have any recommendations as to how to get localised strings into the Exception handler? I will need this in a few different exceptions, though could go the way of a exceptioncreation function that gets the localised string and creates teh exception, though the stack info would then be wrong. I also don't want too much in the main body before teh Throw as it obviously starts to impinge on readability of the flow. </p>
[ { "answer_id": 288129, "author": "labilbe", "author_id": 1195872, "author_profile": "https://Stackoverflow.com/users/1195872", "pm_score": 3, "selected": true, "text": "\nnamespace eMill.Model.Exceptions\n{\n public sealed class AccountNotFoundException : EmillException\n {\n private readonly string _accountName;\n\n public AccountNotFoundException(string accountName)\n {\n _accountName = accountName;\n }\n\n public override string Message\n {\n get { return string.Format(Resource.GetString(\"ErrAccountNotFoundFmt\"), _accountName); }\n }\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6684/" ]
288,070
<p>I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.</p> <p>Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method. </p> <pre><code> [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] [OperationBehavior(Impersonation = ImpersonationOption.Required)] public string method1() </code></pre> <p>I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?</p> <p>Thanks</p>
[ { "answer_id": 288758, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "public string method1()\n{\n PrincipalPermission p = new PrincipalPermission(null, \"Administrators\");\n p.Demand();\n ...\n" }, { "answer_id": 289696, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 3, "selected": false, "text": "<system.Web>\n <authentication mode=\"Windows\"/>\n <authorization>\n <allow roles=\".\\Administrators\"/>\n <deny users=\"*\"/>\n </authorization>\n</system.Web>\n <system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WindowsSecurity\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" />\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <client>\n <endpoint address=\"https://localhost/myservice\"\n binding=\"wsHttpBinding\"\n bindingConfiguration=\"WindowsSecurity\"\n contract=\"IMyService\" />\n </client>\n</system.serviceModel>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37444/" ]
288,084
<p>Is there any other way to get a list of file names via <code>T-SQL</code> other than </p> <pre><code>INSERT INTO @backups(filename) EXEC master.sys.xp_cmdshell 'DIR /b c:\some folder with sql backups in it </code></pre> <p>I am attempting to get a list of SQL backup files from a folder to restore and I do NOT want to use the <code>xp_cmdshell</code> for obvious security reasons.</p>
[ { "answer_id": 288759, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": false, "text": "RESTORE FILELISTONLY disk='FULL_PATH_TO_YOUR_FILE'" }, { "answer_id": 16380244, "author": "Jeff Moden", "author_id": 313265, "author_profile": "https://Stackoverflow.com/users/313265", "pm_score": 1, "selected": false, "text": "--===== Define the path and populate it.\n -- This could be a parameter in a proc\nDECLARE @pPath VARCHAR(512);\n SELECT @pPath = 'C:\\Temp';\n\n--===== Create a table to store the directory information in\n CREATE TABLE #DIR\n (\n RowNum INT IDENTITY(1,1),\n ObjectName VARCHAR(512),\n Depth TINYINT,\n IsFile BIT,\n Extension AS RIGHT(ObjectName,CHARINDEX('.',REVERSE(ObjectName))) PERSISTED\n )\n;\n--===== Get the directory information and remember it\n INSERT INTO #DIR\n (ObjectName,Depth,IsFile)\n EXEC xp_DirTree 'C:\\Temp',1,1\n;\n--===== Now do whatever it is you need to do with it\n SELECT * FROM #DIR;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
288,111
<p>I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them. However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc. How can I strip out the BOM characters? Is there an easy way to do this without manually going through the byte array looking for ""?</p>
[ { "answer_id": 289114, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "var name = GetFileName();\nvar bytes = System.IO.File.ReadAllBytes(name);\nSystem.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray());\n" }, { "answer_id": 289505, "author": "Tim Bailey", "author_id": 1077232, "author_profile": "https://Stackoverflow.com/users/1077232", "pm_score": 1, "selected": false, "text": "File.WriteAllText(filename, File.ReadAllText(filename, Encoding.UTF8), Encoding.ASCII);\n" }, { "answer_id": 1136541, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var text = File.ReadAllText(args.SourceFileName);\nvar streamWriter = new StreamWriter(args.DestFileName, args.Append, new UTF8Encoding(false));\nstreamWriter.Write(text);\nstreamWriter.Close();\n" }, { "answer_id": 2863890, "author": "Olivier de Rivoyre", "author_id": 26071, "author_profile": "https://Stackoverflow.com/users/26071", "pm_score": 3, "selected": false, "text": "using System.Linq;\nusing System.IO;\nnamespace BomRemover\n{\n /// <summary>\n /// Remove UTF-8 BOM (EF BB BF) of all *.php files in current & sub-directories.\n /// </summary>\n class Program\n {\n private static void removeBoms(string filePattern, string directory)\n {\n foreach (string filename in Directory.GetFiles(directory, file Pattern))\n {\n var bytes = System.IO.File.ReadAllBytes(filename);\n if(bytes.Length > 2 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)\n {\n System.IO.File.WriteAllBytes(filename, bytes.Skip(3).ToArray()); \n }\n }\n foreach (string subDirectory in Directory.GetDirectories(directory))\n {\n removeBoms(filePattern, subDirectory);\n }\n }\n static void Main(string[] args)\n {\n string filePattern = \"*.php\";\n string startDirectory = Directory.GetCurrentDirectory();\n removeBoms(filePattern, startDirectory); \n } \n }\n}\n" }, { "answer_id": 49279224, "author": "Ashokan Sivapragasam", "author_id": 6928056, "author_profile": "https://Stackoverflow.com/users/6928056", "pm_score": 0, "selected": false, "text": "StreamReader sr = new StreamReader(path: @\"<Input_file_full_path_with_byte_order_mark>\", \n detectEncodingFromByteOrderMarks: true);\n\nStreamWriter sw = new StreamWriter(path: @\"<Output_file_without_byte_order_mark>\", \n append: false, \n encoding: new UnicodeEncoding(bigEndian: false, byteOrderMark: false));\n\nvar lineNumber = 0;\nwhile (!sr.EndOfStream)\n{\n sw.WriteLine(sr.ReadLine());\n lineNumber += 1;\n if (lineNumber % 100000 == 0)\n Console.Write(\"\\rLine# \" + lineNumber.ToString(\"000000000000\"));\n}\n\nsw.Flush();\nsw.Close();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
288,121
<p>I want to commit a large amount of XML files which have been modified. However, within the directory that I want to recursively search through, there are many folders/files which have been added locally, these I do not want to commit.</p> <p>Is there a way to do this on the command line?</p> <p>Update: I should have included the SVN version info: svn, version 1.4.6 (r28521), compiled Mar 11 2008, 08:26:35</p> <p>P.S. I'd be interested in answers which include how to force the commit, e.g. even if files have been locked.</p>
[ { "answer_id": 288170, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "svnadmin lslocks /path/to/repository\n svnadmin rmlocks /path/to/repository /project/path/to/locked/file\n svn --force unlock svn://url.to.repository/project/path/to/locked/file\n svn --force unlock svn;//url.to.repository/project/janes_subdir/jane.xml\nsvn ci -m \"Whatever Log\" foo.xml junk.xml my_subdir/*.xml janes_subdir/jane.xml\n" }, { "answer_id": 289600, "author": "tommym", "author_id": 37607, "author_profile": "https://Stackoverflow.com/users/37607", "pm_score": 2, "selected": false, "text": "find . -name '*.xml' -print0 | xargs -0 svn ci svn status | egrep '^M.*\\.xml$' | sed -e 's/^. *//' > tmp.txt && svn ci --targets tmp.txt svn status > tmp.txt && $EDITOR tmp.txt && sed -e 's/^. *//' < tmp.txt > tmp2.txt && svn ci --targets tmp2.txt" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
288,127
<p>I would like to include some code coverage into our nightly build process. We're using CruiseControl, Ant, and Buckminster. Buckminster drives checkout from multiple repositories, and the PDE building and packaging of the product.</p> <p><strong>Has any one any experience integrating code coverage into an RCP headless build?</strong></p> <p>I have been looking at Cobertura, EMMA/EclEMMA, DbUnit though am very interested to hear of any experiences with these or any other tools. </p>
[ { "answer_id": 296506, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 3, "selected": true, "text": "osgi.parentClassloader=app ext boot fwk app" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
288,138
<p>this is not a primary key, but merely used as a marker in existing system that marks these items with a 1 letter code ie 'N' for new, 'R' for return, etc. I was going to go with a varchar(50) as the data type but wondering if there's anything wrong with say varchar(2) instead aiming for efficiency. thx!</p>
[ { "answer_id": 289072, "author": "Ian Varley", "author_id": 37539, "author_profile": "https://Stackoverflow.com/users/37539", "pm_score": 1, "selected": false, "text": "CREATE TABLE Product_Status (\n status_id INT NOT NULL PRIMARY KEY, \n description VARCHAR(50) NOT NULL\n)\nINSERT INTO Product_Status (status_id, description) \n VALUES (1, 'New')\nINSERT INTO Product_Status (status_id, description) \n VALUES (2, 'Return')\n--etc.\n ALTER TABLE OriginalTable \n ADD status_id INT NOT NULL REFERENCES Product_Status(status_id)\n ALTER TABLE OriginalTable ALTER status \n ADD CONSTRAINT [Check_Valid_Values] \n CHECK status in ('N', 'R' /* etc ... */)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35286/" ]
288,142
<p>I'm trying to watch the execution of a VB6 app and I'm running into an issue because once I enter the debugger and then hit <code>Continue</code>, it no longer lets me step through the code until I hit another break point. I want to be able to execute a program without stepping through something until I hit a point where I want to watch it execute. Ideally this would be something to the effect of holding a key down while I pressed a button to 'step into' that function.</p> <p>Thanks in advance!</p> <p><strong>[EDIT]</strong>: I'm aware that I can use break points to stop the execution. To be more clear, the problem is that I don't know where the execution is going to, so I can't set the break point there (because I don't know where there is). That's why I essentially want to be able to say, 'after this next thing that I do, break, no matter what'. It sounds like this functionality does not exist, but I'm still keeping my fingers crossed.</p>
[ { "answer_id": 288159, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 1, "selected": false, "text": "Debug.Assert False\n" }, { "answer_id": 290720, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 2, "selected": false, "text": "<save the current state>\n<Do your original code>\n<save the modified state>\n<push the command onto a stack>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
288,153
<p>I would like to know How to create a fps-game with SDL lib? </p> <p>Are there any books that explain with examples? </p>
[ { "answer_id": 288376, "author": "David Frenkel", "author_id": 28747, "author_profile": "https://Stackoverflow.com/users/28747", "pm_score": 5, "selected": true, "text": " xxxxxxxxxxxxxxxxxxxxxxxx\n xx..........P..........x\n xxxxxxx...........I....x\n xR....xxx...........E..x\n xx.................0xxxx\n xxxxxxxxxxxxxxxxxxxxxxxx\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24639/" ]
288,157
<p>Say we are traversing a graph and want to quickly determine if a node has been seen before or not. We have a few set preconditions.</p> <ol> <li>Nodes have been marked with integers values 1..N</li> <li>Graph is implemented with nodes having an adjacency list</li> <li>Every integer value from 1..N occurs in the graph, which is of size N</li> </ol> <p>Any ideas for doing this in a purely functional way?(No Hash tables or arrays allowed).</p> <p>I want a data structure with two functions working on it; add(adds an encountered integer) and lookup(checks if integer has been added). Both should preferably take O(n) time amortized for N repetitions.</p> <p>Is this possible?</p>
[ { "answer_id": 288254, "author": "namin", "author_id": 34596, "author_profile": "https://Stackoverflow.com/users/34596", "pm_score": 3, "selected": false, "text": "insert member" }, { "answer_id": 874172, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 1, "selected": false, "text": "Data.Set" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,178
<p>I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...</p> <p>is there a way to simplify a c++ integration function like this:</p> <pre><code>// Integral Function double integrate(double a, double b, double (*f)(double)) { double sum = 0.0; // Evaluate integral{a,b} f(x) dx for(int n = 0 ; n &lt;= 100; ++n) { double x = a + n*(b-a)/100.0; sum += (*f)(x) * (b-a)/101.0; } return sum; } </code></pre> <p>by using c# and lambda expressions?</p>
[ { "answer_id": 288311, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "public double Integrate(double a,double b, Func<double, double> f)\n{\n double sum = 0.0;\n\n for (int n = 0; n <= 100; ++n)\n {\n double x = a + n * (b - a) / 100.0;\n sum += f(x) * (b - a) / 101.0;\n }\n return sum;\n}\n Func<double, double> fun = x => Math.Pow(x,2); \n double result = Integrate(0, 10, fun);\n" }, { "answer_id": 288315, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": " static double Integrate(double a, double b, Func<double, double> func)\n {\n double sum = 0.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0 ; n <= 100; ++n)\n {\n double x = a + n*(b-a)/100.0;\n sum += func(x) * (b - a) / 101.0;\n }\n return sum;\n }\n double value = Integrate(1,2,x=>x*x); // yields 2.335\n // expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...\n" }, { "answer_id": 288344, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "(a, b, c) => {\n double sum = 0.0;\n Func<double, double> dox = (x) => a + x*(b-a)/100.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0 ; n <= 100; ++n)\n sum += c(dox(n)) * (b-a)/101.0;\n\n return sum;\n}\n static double Integrate(double a, double b, function<double(double)> f)\n{\n double sum = 0.0;\n\n // Evaluate integral{a,b} f(x) dx\n for(int n = 0; n < 100; ++n) {\n double x = a + n * (b - a) / 100.0;\n sum += f(x) * (b - a) / 101.0;\n }\n return sum;\n} \n\nint main() {\n Integrate(0, 1, [](double a) { return a * a; });\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,182
<p>Where should I be logging exceptions? At the data service tier(ExecuteDataSet, etc.) and/or at the data access layer and/or at the business layer?</p>
[ { "answer_id": 288215, "author": "James McMahon", "author_id": 20774, "author_profile": "https://Stackoverflow.com/users/20774", "pm_score": 1, "selected": false, "text": "main {\n try {\n application code\n } catch {\n preform logging\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34214/" ]
288,190
<p>How do I ignore all files within a folder under source control?</p> <p><code>/project/published/</code> is a folder I want to keep</p> <p><code>/project/published/some_file(s)</code> are files/folders I don't want</p> <p>More Details: Currently when I go to commit changes for my project I see a lot of files that I don't want to. They are files that get published to a folder and I don't need them under source control. I won't ever know the names of these files as they are chosen by users.</p> <p>I tried to use the property <code>svn:ignore</code> with value <code>published/*</code> but that did not work. Any ideas?</p>
[ { "answer_id": 288213, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 2, "selected": false, "text": "svn propset svn:ignore published/*\n svn propset svn propset svn:ignore [value] [target]\n svn propset svn:ignore \"*\" published\n" }, { "answer_id": 3673549, "author": "Shiro", "author_id": 129209, "author_profile": "https://Stackoverflow.com/users/129209", "pm_score": 6, "selected": false, "text": "published/ svn:ignore *" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,192
<p>I'm writing Application A and DLL B, both in C#.NET. How do I do the following: </p> <ol> <li>A calls function in B </li> <li>Want B to use delegate/callback to update status in UI of A </li> </ol> <p>This is <em>not</em> about BackgroundWorker...that part works fine in A. What I can't see is how to let B know what function to call in A.</p>
[ { "answer_id": 288234, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 4, "selected": false, "text": "public delegate void CallbackDelegate(string status);\n\npublic void DoWork(string param, CallbackDelegate callback)\n{\n callback(\"status\");\n}\n public void MyCallback(string status)\n{\n // Update your UI.\n}\n B.DoWork(\"my params\", MyCallback);\n" }, { "answer_id": 288247, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "public class A\n{\n delegate void BDelegate();\n\n public void BegineBMethod()\n {\n BDelegate b_method = new BDelegate(B.b);\n b_method.BeginInvoke(BCallback, null);\n }\n\n void BCallback(IAsyncResult ar)\n {\n // cleanup/get return value/check exceptions here\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,200
<p>We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us the time it takes to calculate the first n Prime numbers.</p> <p>Optimised version below - now takes ~6.6secs</p> <pre><code>public class Primes { public static void main(String[] args) { int topPrime = 150000; int current = 2; int count = 0; int lastPrime = 2; long start = System.currentTimeMillis(); while (count &lt; topPrime) { boolean prime = true; int top = (int)Math.sqrt(current) + 1; for (int i = 2; i &lt; top; i++) { if (current % i == 0) { prime = false; break; } } if (prime) { count++; lastPrime = current; } if (current == 2) { current++; } else { current = current + 2; } } System.out.println("Last prime = " + lastPrime); System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000); } } </code></pre> <p>We've pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins.</p> <p>If you want to have a go and post your results, then stick em up.</p> <p>Specs for the PC I'm running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04.</p> <p><strong>Best Optimisation so far has been the square root of current, first mentioned by Jason Z.</strong></p>
[ { "answer_id": 288252, "author": "BP.", "author_id": 36984, "author_profile": "https://Stackoverflow.com/users/36984", "pm_score": 1, "selected": false, "text": "for (int i = 2; i < top; i++)" }, { "answer_id": 288263, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 4, "selected": true, "text": "int count = 0;\n...\nfor (int i = 2; i < top; i++)\n...\nif (current == 2)\n current++;\nelse\n current += 2;\n int count = 1;\n...\nfor (int i = 3; i < top; i += 2)\n...\ncurrent += 2;\n int count = 1;\n...\nfor (int i = 3; i*i <= current; i += 2)\n...\ncurrent += 2;\n" }, { "answer_id": 288339, "author": "Aistina", "author_id": 37472, "author_profile": "https://Stackoverflow.com/users/37472", "pm_score": 2, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n int count = 0;\n int max = 150000;\n int i = 2;\n\n DateTime start = DateTime.Now;\n while (count < max)\n {\n if (IsPrime(i))\n {\n count++;\n }\n\n i++;\n\n }\n DateTime end = DateTime.Now;\n\n Console.WriteLine(\"Total time taken: \" + (end - start).TotalSeconds.ToString() + \" seconds\");\n Console.ReadLine();\n }\n\n static bool IsPrime(int n)\n {\n if (n < 4)\n return true;\n if (n % 2 == 0)\n return false;\n\n int s = (int)Math.Sqrt(n);\n for (int i = 2; i <= s; i++)\n if (n % i == 0)\n return false;\n\n return true;\n }\n}\n" }, { "answer_id": 288437, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 0, "selected": false, "text": "class Program\n{ \n static void Main(string[] args)\n {\n DateTime start = DateTime.Now;\n\n int count = 2; //once 2 and 3\n\n int i = 5;\n while (count < 150000)\n {\n if (IsPrime(i))\n {\n count++;\n }\n\n i += 2;\n\n if (IsPrime(i))\n {\n count++;\n }\n\n i += 4;\n }\n\n DateTime end = DateTime.Now;\n\n Console.WriteLine(\"Total time taken: \" + (end - start).TotalSeconds.ToString() + \" seconds\");\n Console.ReadLine();\n }\n\n static bool IsPrime(int n)\n {\n //if (n < 4)\n //return true;\n //if (n % 2 == 0)\n //return false;\n\n int s = (int)Math.Sqrt(n);\n for (int i = 2; i <= s; i++)\n if (n % i == 0)\n return false;\n\n return true;\n }\n}\n" }, { "answer_id": 288495, "author": "avgbody", "author_id": 8737, "author_profile": "https://Stackoverflow.com/users/8737", "pm_score": 1, "selected": false, "text": " while (count < topPrime) {\n\n boolean prime = true;\n boolean prime; \nwhile (count < topPrime) {\n\n prime = true;\n" }, { "answer_id": 288669, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "public class Primes\n{\n // Original code\n public static void first()\n {\n int topPrime = 150003;\n int current = 2;\n int count = 0;\n int lastPrime = 2;\n\n long start = System.currentTimeMillis();\n\n while (count < topPrime) {\n\n boolean prime = true;\n\n int top = (int)Math.sqrt(current) + 1;\n\n for (int i = 2; i < top; i++) {\n if (current % i == 0) {\n prime = false;\n break;\n }\n }\n\n if (prime) {\n count++;\n lastPrime = current;\n// System.out.print(lastPrime + \" \"); // Checking algo is correct...\n }\n if (current == 2) {\n current++;\n } else {\n current = current + 2;\n }\n }\n\n System.out.println(\"\\n-- First\");\n System.out.println(\"Last prime = \" + lastPrime);\n System.out.println(\"Total time = \" + (double)(System.currentTimeMillis() - start) / 1000);\n }\n\n // My attempt\n public static void second()\n {\n final int wantedPrimeNb = 150000;\n int count = 0;\n\n int currentNumber = 1;\n int increment = 4;\n int lastPrime = 0;\n\n long start = System.currentTimeMillis();\n\nNEXT_TESTING_NUMBER:\n while (count < wantedPrimeNb)\n {\n currentNumber += increment;\n increment = 6 - increment;\n if (currentNumber % 2 == 0) // Even number\n continue;\n if (currentNumber % 3 == 0) // Multiple of three\n continue;\n\n int top = (int) Math.sqrt(currentNumber) + 1;\n int testingNumber = 5;\n int testIncrement = 2;\n do\n {\n if (currentNumber % testingNumber == 0)\n {\n continue NEXT_TESTING_NUMBER;\n }\n testingNumber += testIncrement;\n testIncrement = 6 - testIncrement;\n } while (testingNumber < top);\n // If we got there, we have a prime\n count++;\n lastPrime = currentNumber;\n// System.out.print(lastPrime + \" \"); // Checking algo is correct...\n }\n\n System.out.println(\"\\n-- Second\");\n System.out.println(\"Last prime = \" + lastPrime);\n System.out.println(\"Total time = \" + (double) (System.currentTimeMillis() - start) / 1000);\n }\n\n public static void main(String[] args)\n {\n first();\n second();\n }\n}\n" }, { "answer_id": 288709, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": " if (current != 2 && current % 2 == 0)\n prime = false;\n else {\n for (int i = 3; i < top; i+=2) {\n if (current % i == 0) {\n prime = false;\n break;\n }\n }\n }\n" }, { "answer_id": 296214, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "let max = 150000\nlet numbers = [2..max]\nlet rec getPrimes sieve max =\n match sieve with\n | [] -> sieve\n | _ when sqrt(float(max)) < float sieve.[0] -> sieve\n | _ -> let prime = sieve.[0]\n let filtered = List.filter(fun x -> x % prime <> 0) sieve // Removes the prime as well so the recursion works correctly.\n let result = getPrimes filtered max\n prime::result // The filter removes the prime so add it back to the primes result.\n\nlet timer = System.Diagnostics.Stopwatch()\ntimer.Start()\nlet r = getPrimes numbers max\ntimer.Stop()\nprintfn \"Primes: %A\" r\nprintfn \"Elapsed: %d.%d\" timer.Elapsed.Seconds timer.Elapsed.Milliseconds\n" }, { "answer_id": 392265, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\ndef iprimes_upto(limit):\n \"\"\"Generate all prime numbers less then limit.\n\n http://stackoverflow.com/questions/188425/project-euler-problem#193605\n \"\"\"\n is_prime = [True] * limit\n for n in range(2, limit):\n if is_prime[n]:\n yield n\n for i in range(n*n, limit, n): # start at ``n`` squared\n is_prime[i] = False\n\ndef sup_prime(n):\n \"\"\"Return an integer upper bound for p(n).\n\n p(n) < n (log n + log log n - 1 + 1.8 log log n / log n)\n\n where p(n) is the n-th prime. \n http://primes.utm.edu/howmany.shtml#2\n \"\"\"\n from math import ceil, log\n assert n >= 13\n pn = n * (log(n) + log(log(n)) - 1 + 1.8 * log(log(n)) / log(n))\n return int(ceil(pn))\n\nif __name__ == '__main__':\n import sys\n max_number_of_primes = int(sys.argv[1]) if len(sys.argv) == 2 else 150000\n primes = list(iprimes_upto(sup_prime(max_number_of_primes)))\n print(\"Generated %d primes\" % len(primes))\n n = 100\n print(\"The first %d primes are %s\" % (n, primes[:n]))\n $ python primes.py\n\nGenerated 153465 primes\nThe first 100 primes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, \n43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,\n283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,\n467, 479, 487, 491, 499, 503, 509, 521, 523, 541]\n" }, { "answer_id": 423344, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 0, "selected": false, "text": "#include<stdio.h>\n#include<math.h>\n#include<stdlib.h>\n#include<time.h>\n\n//5MB... allocate a lot of memory at once each time we need it\n#define ARRAYMULT 5242880 \n\n\n//list of calculated primes\n__int64* primes; \n//number of primes calculated\n__int64 primeCount;\n//the current size of the array\n__int64 arraySize;\n\n//Prints all of the calculated primes\nvoid PrintPrimes()\n{\n __int64 i;\n for(i=0; i<primeCount; i++)\n {\n printf(\"%d \", primes[i]);\n }\n\n}\n\n//Calculates all prime numbers to max\nvoid CalcPrime(__int64 max)\n{\n register __int64 i;\n double square;\n primes = (__int64*)malloc(sizeof(__int64) * ARRAYMULT);\n primeCount = 0;\n arraySize = ARRAYMULT;\n\n //we provide the first prime because its even, and it would be convenient to start\n //at an odd number so we can skip evens.\n primes[0] = 2;\n primeCount++;\n\n\n\n for(i=3; i<max; i+=2)\n {\n int j;\n square = sqrt((double)i);\n\n //only test the current candidate against other primes.\n for(j=0; j<primeCount; j++)\n {\n //prime divides evenly into candidate, so we have a non-prime\n if(i%primes[j]==0)\n break;\n else\n {\n //if we've reached the point where the next prime is > than the square of the\n //candidate, the candidate is a prime... so we can add it to the list\n if(primes[j] > square)\n {\n //our array has run out of room, so we need to expand it\n if(primeCount >= arraySize)\n {\n int k;\n __int64* newArray = (__int64*)malloc(sizeof(__int64) * (ARRAYMULT + arraySize));\n\n for(k=0; k<primeCount; k++)\n {\n newArray[k] = primes[k];\n }\n\n arraySize += ARRAYMULT;\n free(primes);\n primes = newArray;\n }\n //add the prime to the list\n primes[primeCount] = i;\n primeCount++;\n break;\n\n }\n }\n\n }\n\n }\n\n\n}\nint main()\n{\n int max;\n time_t t1,t2;\n double elapsedTime;\n\n printf(\"Enter the max number to calculate primes for:\\n\");\n scanf_s(\"%d\",&max);\n t1 = time(0);\n CalcPrime(max);\n t2 = time(0);\n elapsedTime = difftime(t2, t1);\n printf(\"%d Primes found.\\n\", primeCount);\n printf(\"%f seconds elapsed.\\n\\n\",elapsedTime);\n //PrintPrimes();\n scanf(\"%d\");\n return 1;\n}\n" }, { "answer_id": 1484967, "author": "Nicholas Jordan", "author_id": 177505, "author_profile": "https://Stackoverflow.com/users/177505", "pm_score": 0, "selected": false, "text": "package demo;\n\nimport java.util.List;\nimport java.util.HashSet;\n\nclass Primality\n{\n int current = 0;\n int minValue;\n private static final HashSet<Integer> resultSet = new HashSet<Integer>();\n final int increment = 2;\n // An obvious optimization is to use some already known work as an internal\n // constant table of some kind, reducing approaches to boundary conditions.\n int[] alreadyKown = \n {\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, \n 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, \n 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,\n 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,\n 467, 479, 487, 491, 499, 503, 509, 521, 523, 541\n };\n // Trivial constructor.\n\n public Primality(int minValue)\n {\n this.minValue = minValue;\n }\n List calcPrimes( int startValue )\n {\n // eliminate several hundred already known primes \n // by hardcoding the first few dozen - implemented \n // from prior work by J.F. Sebastian\n if( startValue > this.minValue )\n {\n // Duh.\n current = Math.abs( start );\n do\n {\n boolean prime = true;\n int index = current;\n do\n {\n if(current % index == 0)\n {\n // here, current cannot be prime so break.\n prime = false;\n break;\n }\n while( --index > 0x00000000 );\n\n // Unreachable if not prime\n // Here for clarity\n\n if ( prime )\n { \n resultSet dot add ( or put or whatever it is )\n new Integer ( current ) ;\n }\n }\n while( ( current - increment ) > this.minValue );\n // Sanity check\n if resultSet dot size is greater that zero\n {\n for ( int anInt : alreadyKown ) { resultSet.add( new Integer ( anInt ) );}\n return resultSet;\n }\n else throw an exception ....\n }\n if(current % 5 == 0 )\n if(current % 7 == 0 )\n if( ( ( ( current % 12 ) +1 ) == 0) || ( ( ( current % 12 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 18 ) +1 ) == 0) || ( ( ( current % 18 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 24 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 36 ) +1 ) == 0) || ( ( ( current % 36 ) -1 ) == 0) ){break;}\n if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 42 ) -1 ) == 0) ){break;}\n\n\n// and - new work this morning:\n\n\npackage demo;\n\n/**\n *\n * Buncha stuff deleted for posting .... duh.\n *\n * @author Author\n * @version 0.2.1\n *\n * Note strings are base36\n */\npublic final class Alice extends java.util.HashSet<java.lang.String>\n{\n // prints 14551 so it's 14 ½ seconds to get 40,000 likely primes\n // using Java built-in on amd sempron 1.8 ghz / 1600 mhz front side bus 256 k L-2\n public static void main(java.lang.String[] args)\n {\n try\n {\n final long start=System.currentTimeMillis();\n // VM exhibits spurious 16-bit pointer behaviour somewhere after 40,000\n final java.lang.Integer upperBound=new java.lang.Integer(40000);\n int index = upperBound.intValue();\n\n final java.util.HashSet<java.lang.String>hashSet\n = new java.util.HashSet<java.lang.String>(upperBound.intValue());//\n // Arbitraily chosen value, based on no idea where to start.\n java.math.BigInteger probablePrime\n = new java.math.BigInteger(16,java.security.SecureRandom.getInstance(\"SHA1PRNG\"));\n do\n {\n java.math.BigInteger nextProbablePrime = probablePrime.nextProbablePrime();\n if(hashSet.add(new java.lang.String(nextProbablePrime.toString(Character.MAX_RADIX))))\n {\n probablePrime = nextProbablePrime;\n if( ( index % 100 ) == 0x00000000 )\n {\n // System.out.println(nextProbablePrime.toString(Character.MAX_RADIX));//\n continue;\n }\n else\n {\n continue;\n }\n }\n else\n {\n throw new StackOverflowError(new String(\"hashSet.add(string) failed on iteration: \"+\n Integer.toString(upperBound.intValue() - index)));\n }\n }\n while(--index > 0x00000000);\n System.err.println(Long.toString( System.currentTimeMillis() - start));\n }\n catch(java.security.NoSuchAlgorithmException nsae)\n {\n // Never happen\n return;\n }\n catch(java.lang.StackOverflowError soe)\n {\n // Might happen\n System.out.println(soe.getMessage());//\n return;\n }\n }\n}// end class Alice\n" }, { "answer_id": 1485311, "author": "Naveen", "author_id": 43594, "author_profile": "https://Stackoverflow.com/users/43594", "pm_score": 0, "selected": false, "text": "/*Calculate the primes till TOTALPRIMES*/\n#include <stdio.h>\n#define TOTALPRIMES 15000\n\nmain(){\nint primes[TOTALPRIMES];\nint count;\nint i, j, cpr;\nchar isPrime;\n\nprimes[0] = 2;\ncount = 1;\n\nfor(i = 3; count < TOTALPRIMES; i+= 2){\n isPrime = 1;\n\n //check divisiblity only with previous primes\n for(j = 0; j < count; j++){\n cpr = primes[j];\n if(i % cpr == 0){\n isPrime = 0;\n break;\n }\n if(cpr*cpr > i){\n break;\n }\n }\n if(isPrime == 1){\n //printf(\"Prime: %d\\n\", i);\n primes[count] = i;\n count++;\n }\n\n\n}\n\nprintf(\"Last prime = %d\\n\", primes[TOTALPRIMES - 1]);\n}\n" }, { "answer_id": 2298622, "author": "Steph L", "author_id": 277225, "author_profile": "https://Stackoverflow.com/users/277225", "pm_score": 0, "selected": false, "text": "\n//\n// Finds the n first prime numbers.\n//\n//count: Number of prime numbers to find.\n//listPrimes: A reference to a list that will contain all n first prime if getLast is set to false.\n//getLast: If true, the list will only contain the nth prime number.\n//\nstatic ulong GetPrimes(ulong count, ref IList listPrimes, bool getLast)\n{\n if (count == 0)\n return 0;\n if (count == 1)\n {\n if (listPrimes != null)\n {\n if (!getLast || (count == 1))\n listPrimes.Add(2);\n }\n\n return count;\n }\n\n ulong currentSquare = 1;\n ulong nextSquare = 9;\n ulong nextSquareIndex = 3;\n ulong primesCount = 1;\n\n List dividers = new List();\n\n //Only check for odd numbers starting with 3.\n for (ulong curNumber = 3; (curNumber (nextSquareIndex % div) == 0) == false)\n dividers.Add(nextSquareIndex);\n\n //Move to next square number\n currentSquare = nextSquare;\n\n //Skip the even dividers so take the next odd square number.\n nextSquare += (4 * (nextSquareIndex + 1));\n nextSquareIndex += 2;\n\n //We may continue as a square number is never a prime number for obvious reasons :).\n continue;\n }\n\n //Check if there is at least one divider for the current number.\n //If so, this is not a prime number.\n if (dividers.Exists(div => (curNumber % div) == 0) == false)\n {\n if (listPrimes != null)\n {\n //Unless we requested only the last prime, add it to the list of found prime numbers.\n if (!getLast || (primesCount + 1 == count))\n listPrimes.Add(curNumber);\n }\n primesCount++;\n }\n }\n\n return primesCount;\n}\n" }, { "answer_id": 7895077, "author": "voidlogic", "author_id": 1013460, "author_profile": "https://Stackoverflow.com/users/1013460", "pm_score": 3, "selected": false, "text": "//returns number of primes less than n\nprivate static int getNumberOfPrimes(final int n)\n{\n if(n < 2) \n return 0;\n BitSet candidates = new BitSet(n - 1);\n candidates.set(0, false);\n candidates.set(1, false);\n candidates.set(2, n);\n for(int i = 2; i < n; i++)\n if(candidates.get(i))\n for(int j = i + i; j < n; j += i)\n if(candidates.get(j) && j % i == 0)\n candidates.set(j, false); \n return candidates.cardinality();\n} \n" }, { "answer_id": 28639828, "author": "thephpdev", "author_id": 2529423, "author_profile": "https://Stackoverflow.com/users/2529423", "pm_score": 0, "selected": false, "text": "clang++ main.cpp -O3 Caelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100\n\nCalculated 25 prime numbers up to 100 in 2 clocks (0.000002 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000\n\nCalculated 168 prime numbers up to 1000 in 4 clocks (0.000004 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000\n\nCalculated 1229 prime numbers up to 10000 in 18 clocks (0.000018 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000\n\nCalculated 9592 prime numbers up to 100000 in 237 clocks (0.000237 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000\n\nCalculated 78498 prime numbers up to 1000000 in 3232 clocks (0.003232 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 10000000\n\nCalculated 664579 prime numbers up to 10000000 in 51620 clocks (0.051620 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 100000000\n\nCalculated 5761455 prime numbers up to 100000000 in 918373 clocks (0.918373 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 1000000000\n\nCalculated 50847534 prime numbers up to 1000000000 in 10978897 clocks (10.978897 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ ./a.out 4000000000\n\nCalculated 189961812 prime numbers up to 4000000000 in 53709395 clocks (53.709396 seconds).\nCaelans-MacBook-Pro:Primer3 Caelan$ \n #include <iostream> // cout\n#include <cmath> // sqrt\n#include <ctime> // clock/CLOCKS_PER_SEC\n#include <cstdlib> // malloc/free\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n if(argc == 1) {\n cout << \"Please enter a number.\" << \"\\n\";\n return 1;\n }\n long n = atol(argv[1]);\n long i;\n long j;\n long k;\n long c;\n long sr;\n bool * a = (bool*)malloc((size_t)n * sizeof(bool));\n\n for(i = 2; i < n; i++) {\n a[i] = true;\n }\n\n clock_t t = clock();\n\n sr = sqrt(n);\n for(i = 2; i <= sr; i++) {\n if(a[i]) {\n for(k = 0, j = 0; j <= n; j = (i * i) + (k * i), k++) {\n a[j] = false;\n }\n }\n }\n\n t = clock() - t;\n\n c = 0;\n for(i = 2; i < n; i++) {\n if(a[i]) {\n //cout << i << \" \";\n c++;\n }\n }\n\n cout << fixed << \"\\nCalculated \" << c << \" prime numbers up to \" << n << \" in \" << t << \" clocks (\" << ((float)t) / CLOCKS_PER_SEC << \" seconds).\\n\";\n\n free(a);\n\n return 0;\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18340/" ]
288,210
<p>I used to do this:</p> <pre><code>SELECT layerID FROM layers WHERE ownerID = ? AND collectionID = ? </code></pre> <p>Which would give me an array of layerID's, and then I'd loop and do this for each one:</p> <pre><code>SELECT DATA FROM drawings WHERE layerID = ? </code></pre> <p>And it all worked fine. So now I'm trying to do it in one step, so I try this:</p> <pre><code>SELECT DATA , layerID FROM drawings WHERE layerID = ANY ( SELECT layerID FROM layers WHERE ownerID = ? AND collectionID = ? ) </code></pre> <p>But for some reason, it doesn't use the index, for the main query, <code>SELECT DATA etc</code>! So this one combined query takes much much longer to complete, versus the separate queries I was doing before. (By theway, the subquery, <code>SELECT layerID etc</code> still uses the index).</p> <p>I've determined if it's using a query or not by using the 'EXPLAIN' statement.</p> <p>I have individual indexes on the <code>ownerID</code> and <code>collectionID</code> columns in the <code>layers</code> table, and on the <code>layerID</code> column in the <code>drawings</code> table.</p> <p>What am I doing wrong with my query?</p>
[ { "answer_id": 288237, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 4, "selected": true, "text": "SELECT d.DATA, d.layerID \nFROM drawings AS d \nINNER JOIN layers AS l ON d.layerID = l.layerID \nWHERE l.ownerID = ? AND l.collectionID = ?\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
288,217
<p>I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed.</p> <p>The problem I am now facing is happening when I quit the application: as order of destruction is not deterministic, it so happens that the single controllerSupervisor instance is destructed prior to (some) of the controllers themselves, and when they call the unregister method in their destructor, they do so upon an already destructed object. </p> <p>The only idea I came up with so far (having a big cold, so this may not mean much) is not having the controllerSupervisor as a global variable on the stack, but rather on the heap (i.e. using new). However in that case I do not have a place to delete it (this is all in a 3rd party kind of library). </p> <p>Any hints/suggestions on what possible options are would be appreciated.</p>
[ { "answer_id": 288223, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "!= 0" }, { "answer_id": 288272, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 0, "selected": false, "text": "class Supervisor {\npublic:\n Supervisor() : inDeleteMode_(false) {}\n\n void deleteWhenDone() {\n inDeleteMode_ = true;\n if( controllers_.empty()){\n delete this;\n }\n }\n\n void deregister(Controller* controller) {\n controllers_.erase(\n remove(controllers_.begin(), \n controllers_.end(), \n controller));\n if( inDeleteMode_ && controllers_.empty()){\n delete this;\n }\n }\n\n\nprivate:\n\n ~Supervisor() {}\n bool inDeleteMode_;\n vector<Controllers*> controllers_;\n};\n\nSupervisor* supervisor = Supervisor();\n...\nsupervisor->deleteWhenDone();\n" }, { "answer_id": 288283, "author": "Nathan Kitchen", "author_id": 31000, "author_profile": "https://Stackoverflow.com/users/31000", "pm_score": 0, "selected": false, "text": "struct ControllerCoordinator {\n Supervisor supervisor;\n set<Controller *> controllers;\n\n ~ControllerDeallocator() {\n set<Controller *>::iterator i;\n for (i = controllers.begin(); i != controllers.end(); ++i) {\n delete *i;\n }\n }\n}\n ControllerCoordinator control;\n control.supervisor.insert(controller) control.erase(controller) control." }, { "answer_id": 288299, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "boost::shared_ptr<> shared_ptr<>" }, { "answer_id": 288362, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "class CS\n{\n public:\n static CS& getInstance()\n {\n static CS instance;\n return instance;\n }\n void doregister(C const&);\n void unregister(C const&);\n private:\n CS()\n { // initialised\n }\n CS(CS const&); // DO NOT IMPLEMENT\n void operator=(CS const&); // DO NOT IMPLEMENT\n };\n\n class C\n {\n public:\n C()\n {\n CS::getInstance().doregister(*this);\n }\n ~C()\n {\n CS::getInstance().unregister(*this);\n }\n };\n" }, { "answer_id": 288517, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 0, "selected": false, "text": "// -- client code --\nclass ControllerClient {\npublic:\n ControllerClient() : \n controller_(NULL)\n {\n controller_ = Controller::create();\n }\n\n ~ControllerClient() {\n delete controller_;\n }\n Controller* controller_;\n};\n\n// -- library code --\nclass Supervisor {\npublic: \n static Supervisor& getIt() { \n if (!theSupervisor ) {\n theSupervisor = Supervisor();\n }\n return *theSupervisor;\n } \n\n void deregister(Controller& controller) {\n remove( controller );\n if( controllers_.empty() ) {\n theSupervisor = NULL;\n delete this;\n } \n }\n\nprivate: \n Supervisor() {} \n\n vector<Controller*> controllers_;\n\n static Supervisor* theSupervisor;\n};\n\nclass Controller {\npublic: \n static Controller* create() {\n return new Controller(Supervisor::getIt()); \n } \n\n ~Controller() {\n supervisor_->deregister(*this);\n supervisor_ = NULL;\n }\nprivate: \n Controller(Supervisor& supervisor) : \n supervisor_(&supervisor)\n {}\n}\n" }, { "answer_id": 288562, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 1, "selected": false, "text": " In Standard C++, objects defined at namespace scope are guaranteed\n to be initialized in an order in strict accordance with that of\n their definitions _in a given translation unit_. No guarantee is\n made for initializations across translation units. However, GNU\n C++ allows users to control the order of initialization of objects\n defined at namespace scope with the init_priority attribute by\n specifying a relative PRIORITY, a constant integral expression\n currently bounded between 101 and 65535 inclusive. Lower numbers\n indicate a higher priority.\n\n In the following example, `A' would normally be created before\n `B', but the `init_priority' attribute has reversed that order:\n\n Some_Class A __attribute__ ((init_priority (2000)));\n Some_Class B __attribute__ ((init_priority (543)));\n\n Note that the particular values of PRIORITY do not matter; only\n their relative ordering.\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27101/" ]
288,222
<p>In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?</p> <p>Something like:</p> <pre><code>alter table tblFoo alter column bar identity(1,1) </code></pre>
[ { "answer_id": 590913, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "alter table tablename \nalter column columnname \nadd Identity(100,1)\n" }, { "answer_id": 912795, "author": "NateJ", "author_id": 112764, "author_profile": "https://Stackoverflow.com/users/112764", "pm_score": 4, "selected": false, "text": "CREATE TABLE tname2 (etc.)\nINSERT INTO tname2 FROM tname1\n\nDROP TABLE tname1\nCREATE TABLE tname1 (with IDENTITY specified)\n\nSET IDENTITY_INSERT tname1 ON\nINSERT INTO tname1 FROM tname2\nSET IDENTITY_INSERT tname1 OFF\n\nDROP tname2\n" }, { "answer_id": 41860419, "author": "Milan", "author_id": 1438675, "author_profile": "https://Stackoverflow.com/users/1438675", "pm_score": 2, "selected": false, "text": "-- make sure you have the correct CREATE TABLE script ready with IDENTITY\n\nSELECT * INTO abcTable_copy FROM abcTable\n\nDROP TABLE abcTable\n\nCREATE TABLE abcTable -- this time with the IDENTITY column\n\nSET IDENTITY_INSERT abcTable ON\n\nINSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy\n\nSET INDENTITY_INSERT abcTable OFF\n\nDROP TABLE abcTable_copy \n\n-- I would suggest to verify the contents of both tables \n-- before dropping the copy table\n" }, { "answer_id": 56885743, "author": "Anuj Kumar", "author_id": 11739011, "author_profile": "https://Stackoverflow.com/users/11739011", "pm_score": 2, "selected": false, "text": "SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;\n Alter table Table_New drop column id;\n Alter table Table_New add id int primary key identity; \n SET IDENTITY_INSERT Table_New ON;\nINSERT INTO Table_New (id, Name,CreatedDate,Modified) \nSELECT id, Name,CreatedDate,Modified FROM Table_Current;\nSET IDENTITY_INSERT Table_New OFF;\n drop table Table_Current;\n EXEC sp_rename 'Table_New', 'Table_Current';\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
288,255
<p>While testing a console app, I set the properties of the console window to be only 3 lines high. </p> <p>This change has somehow stuck, meaning that new console windows default to 3 lines high. If I create a new shortcut on the desktop, and point it to cmd.exe, the window that opens is 3 lines high. </p> <p>Of course, I can alter this value using the properties panel, which ultimately results in "current window only"/"future windows with same title"/"shortcut that started this window" dialog to alter the stickiness of the setting. None of these choices results in the default being changed. If, subsequently, I make a new shortcut to cmd.exe, it's still 3 lines high.</p> <p>The principal problem is that for any new console app that I write, the first time I debug it, I must change the size setting, and when I run the release build, it's the same story.</p> <p>Does anyone know where the default settings for new (i.e. new title or from new shortcut) console app are stored/how to change them?</p> <p>[and, yes, I feel like a muppet for asking, but I can't find this info anywhere!]</p>
[ { "answer_id": 288286, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 4, "selected": false, "text": "HKEY_CURRENT_USER\\Console\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
288,277
<p>I have a JavaScript variable which holds an HTML page and due to the setup I need to extract everything between <code>&lt;div id="LiveArea"&gt;</code> and <code>&lt;/div&gt;</code> from that variable using JavaScript.</p> <p>Any help is greatly appreciated.</p>
[ { "answer_id": 288297, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "\nvar e = document.getElementById('LiveArea');\nif(e) alert(e.innerHTML);\n\n" }, { "answer_id": 288326, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "pattern = /<div id=\"LiveArea\">(.*?)<\\/div>/;\nmatches = your_html_var.match(pattern);\nthe_string = matches[0];\n\ndocument.write(the_string);\n" }, { "answer_id": 288354, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "</div>" }, { "answer_id": 288373, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "var temp = document.createElement('DIV');\ntemp.innerHTML = YourVariable;\nvar liveArea;\nfor (var i = 0; i < temp.childNodes.length; i++)\n{\n if (temp.childNodes[i].id == 'LiveArea')\n {\n liveArea = temp.childNodes[i];\n break;\n }\n}\n" }, { "answer_id": 288534, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 0, "selected": false, "text": "function getPrint(print_area)\n{\n//Creating new page\nvar pp = window.open();\n//Adding HTML opening tag with <HEAD> … </HEAD> portion \npp.document.writeln('<HTML><HEAD><title>Print Preview</title>')\npp.document.writeln('<LINK href=Styles.css type=\"text/css\" rel=\"stylesheet\">')\npp.document.writeln('<LINK href=PrintStyle.css ' + \n 'type=\"text/css\" rel=\"stylesheet\" media=\"print\">')\npp.document.writeln('<base target=\"_self\"></HEAD>')\n\n//Adding Body Tag\npp.document.writeln('<body MS_POSITIONING=\"GridLayout\" bottomMargin=\"0\"');\npp.document.writeln(' leftMargin=\"0\" topMargin=\"0\" rightMargin=\"0\">');\n//Adding form Tag\npp.document.writeln('<form method=\"post\">');\n\n//Creating two buttons Print and Close within a HTML table\npp.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right>');\npp.document.writeln('<INPUT ID=\"PRINT\" type=\"button\" value=\"Print\" ');\npp.document.writeln('onclick=\"javascript:location.reload(true);window.print();\">');\npp.document.writeln('<INPUT ID=\"CLOSE\" type=\"button\" ' + \n 'value=\"Close\" onclick=\"window.close();\">');\npp.document.writeln('</TD></TR><TR><TD></TD></TR></TABLE>');\n\n//Writing print area of the calling page\npp.document.writeln(document.getElementById(print_area).innerHTML);\n//Ending Tag of </form>, </body> and </HTML>\npp.document.writeln('</form></body></HTML>'); \n btnGet.Attributes.Add(\"Onclick\", \"getPrint('YOURDIV');\")\n" }, { "answer_id": 1106399, "author": "Victor", "author_id": 125946, "author_profile": "https://Stackoverflow.com/users/125946", "pm_score": 0, "selected": false, "text": "(?<=<div id=\"LiveArea\">).*(?=<\\/div>)" }, { "answer_id": 2482300, "author": "Jonas", "author_id": 297913, "author_profile": "https://Stackoverflow.com/users/297913", "pm_score": -1, "selected": false, "text": "<div id=\"LiveArea\">\n<!--LiveArea-->\nContent here\n<!--EndLiveArea-->\n</div>\n htmlVal.match(/<\\!\\-\\-LiveArea\"\\-\\->(.*?)<\\!\\-\\-EndLiveArea\"\\-\\->/);\n" }, { "answer_id": 2482315, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": -1, "selected": false, "text": "$(page_html).find(\"#LiveArea\").html();\n" }, { "answer_id": 5360895, "author": "SoSo", "author_id": 667105, "author_profile": "https://Stackoverflow.com/users/667105", "pm_score": 4, "selected": false, "text": "var html = \"<stuff><div id=\\\"LiveArea\\\">hello stackoverflow!</div></stuff>\";\n\nvar matches = html.match(/<div\\s+id=\"LiveArea\">[\\S\\s]*?<\\/div>/gi);\nvar matches = matches[0].replace(/(<\\/?[^>]+>)/gi, ''); // Strip HTML tags?\n\nalert(matches);\n" }, { "answer_id": 27249563, "author": "Supriya Gopalakrishnan", "author_id": 4302960, "author_profile": "https://Stackoverflow.com/users/4302960", "pm_score": 0, "selected": false, "text": "<div id=\"[^\"]*\">(.*?)</div>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,282
<p>Here's some code I have:</p> <pre><code>MyClass* MyClass::getInstance() { static MyClass instance; return &amp;instance; } </code></pre> <p>I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.</p> <p>My question then is how to refer to this <code>instance</code> variable from a global scope. I've tried referring to it as <code>MyClass::getInstance::instance</code> but that doesn't work. I'm guessing <code>getInstance</code> has to be decorated somehow. Anyone know how?</p> <p>This is in Visual Studio 2008.</p>
[ { "answer_id": 288329, "author": "Nathan Kitchen", "author_id": 31000, "author_profile": "https://Stackoverflow.com/users/31000", "pm_score": 1, "selected": false, "text": "int f() {\n static int xyz = 0;\n ++xyz;\n\n return xyz;\n}\n" }, { "answer_id": 292962, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": true, "text": "instance .map cl.exe /Fm x programname!*MyClass* MyClass MyClass::getInstance $S1 MyClass x s dt dt programname!MyClass 0042b360 MyClass::getInstance" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
288,294
<p>This may be too generic a question as is but... I am stumped by trying to move through the directories from within a shell script. I'm not a *nix power user, but I am comfortable working through the command line for most tasks. I'd like to call a script that can move 'me' to a directory instead of just the script process similar to the following:</p> <pre><code>prompt:&gt; goto lit </code></pre> <p>where <code>goto</code> is an alias -> <code>goto='./goscript'</code><br> and<br> <code>goscript</code> has some simple code in such as:</p> <pre><code>cd /path to work dirs/lit/user dir </code></pre> <p>(assuming each user has a directory inside /lit)</p> <p>I've avoided this issue myself by setting my personal alias' to move to the desired directory, run a script, then return to the original directory. This question was brought to me by a co-worker who uses a similar method, but wanted to make the process more generic so we don't need to create every single alias we need. I thought this would be an easy problem to solve, but I'm stumped as I don't really have a great deal of shell scripting experience ...as of yet. </p>
[ { "answer_id": 288308, "author": "Magus", "author_id": 2188, "author_profile": "https://Stackoverflow.com/users/2188", "pm_score": 0, "selected": false, "text": "alias goto='cd /path_to_work/usr/dir'\n source ~/.bashrc\n" }, { "answer_id": 288314, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 0, "selected": false, "text": "alias main1='cd ~/code/main1 && export TOP=`pwd` && export DEBUG=1'\n" }, { "answer_id": 288316, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 0, "selected": false, "text": "alias goto 'cd /path_to_work/\\!*/user_dir'\n" }, { "answer_id": 288323, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "function goto {\n # the \"$USER\" part will expand to the current username\n # the \"$1\" will expand to the first argument to the function (\"goto xyz\" => $1 is \"xyz\")\n cd /some-path/lit/$USER/$1\n}\n prompt> goto folder\n cd /some-path/lit/your-user/folder\n" }, { "answer_id": 288324, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 2, "selected": false, "text": "cd .. \n $> pwd\n$> /home/users/rd/proj\n$> . up\n$> pwd\n$> /home/users/rd\n" }, { "answer_id": 288337, "author": "Sniggerfardimungus", "author_id": 30997, "author_profile": "https://Stackoverflow.com/users/30997", "pm_score": 0, "selected": false, "text": "alias work='cd /home/foo/work'\nalias rails='cd /home/foo/rails'\nalias assets='cd /home/foo/rails/assets'\n" }, { "answer_id": 288363, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 3, "selected": false, "text": "CDPATH PATH CDPATH $CDPATH:${HOME}/subdir ~/subdir subsubdir cd subsubdir\n CDPATH .bashrc export CDPATH=$CDPATH:${HOME}/subdir\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,298
<p>How much code documentation in your .NET source is too much?</p> <p>Some background: I inherited a large codebase that I've talked about in some of the other questions I've posted here on SO. One of the "features" of this codebase is a God Class, a single static class with >3000 lines of code encompassing several dozen static methods. It's everything from <code>Utilities.CalculateFYBasedOnMonth()</code> to <code>Utilities.GetSharePointUserInfo()</code> to <code>Utilities.IsUserIE6()</code>. It's all good code that <a href="http://www.joelonsoftware.com/printerFriendly/articles/fog0000000069.html" rel="noreferrer">doesn't need to be rewritten</a>, just refactored into an appropriate set of libraries. I have that planned out.</p> <p>Since these methods are moving into a new business layer, and my role on this project is to prepare the system for maintenance by other developers, I'm thinking about solid code documentation. While these methods all have good inline comments, they don't all have good (or any) code doco in the form of XML comments. Using a combo of GhostDoc and Sandcastle (or Document X), I can create some pretty nice HTML documentation and post it to SharePoint, which would let developers understand more about what the code does without navigating through the code itself.</p> <p>As the amount of documentation in the code increases, the more difficult it becomes to navigate the code. I'm beginning to wonder if the XML comments will make the code more difficult to maintain than, say, a simpler <code>//comment</code> would on each method. </p> <p>These examples are <a href="http://www.innovasys.com/products/dx2008/overview.aspx" rel="noreferrer">from the Document X sample</a>:</p> <pre><code> /// &lt;summary&gt; /// Adds a new %Customer:CustomersLibrary.Customer% to the collection. /// &lt;/summary&gt; /// &lt;returns&gt;A new Customer instance that represents the new customer.&lt;/returns&gt; /// &lt;example&gt; /// The following example demonstrates adding a new customer to the customers /// collection. /// &lt;code lang="CS" title="Example"&gt; /// CustomersLibrary.Customer newCustomer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith"); /// &lt;/code&gt; /// &lt;code lang="VB" title="Example"&gt; /// Dim newCustomer As CustomersLibrary.Customer = myCustomers.Add(CustomersLibrary.Title.Mr, "John", "J", "Smith") /// &lt;/code&gt; /// &lt;/example&gt; /// &lt;seealso cref="Remove"&gt;Remove Method&lt;/seealso&gt; /// &lt;param name="Title"&gt;The customers title.&lt;/param&gt; /// &lt;param name="FirstName"&gt;The customers first name.&lt;/param&gt; /// &lt;param name="MiddleInitial"&gt;The customers middle initial.&lt;/param&gt; /// &lt;param name="LastName"&gt;The customers last name.&lt;/param&gt; public Customer Add(Title Title, string FirstName, string MiddleInitial, string LastName) { // create new customer instance Customer newCust = new Customer(Title, FirstName, MiddleInitial, LastName); // add to internal collection mItems.Add(newCust); // return ref to new customer instance return newCust; } </code></pre> <p>And:</p> <pre><code> /// &lt;summary&gt; /// Returns the number of %Customer:CustomersLibrary.Customer% instances in the collection. /// &lt;/summary&gt; /// &lt;value&gt; /// An Int value that specifies the number of Customer instances within the /// collection. /// &lt;/value&gt; public int Count { get { return mItems.Count; } } </code></pre> <p>So I was wondering from you: do you document <strong>all</strong> of your code with XML comments with the goal of using something like NDoc (RIP) or Sandcastle? If not, how do you decide what gets documentation and what doesn't? Something like an API would obviously have doco, but what about a codebase that you're going to hand off to another team to maintain?</p> <p>What do you think I should do?</p>
[ { "answer_id": 560540, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "/// <include file=\"Documentation/XML/YourClass.xml\" path=\"//documentation/members[@name='YourClass']/*\"/>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ]
288,304
<p>I have some .NET remoting code where a factory method, implemented in some server side class, returns interfaces to concrete objects, also executing on the very same server. .NET remoting automagically creates proxies and allows me to pass the interfaces across to the client, which can then call them directly.</p> <p>Example interfaces:</p> <pre><code>public interface IFactory { IFoo GetFoo(); } public interface IFoo { void DoSomething(); } </code></pre> <p>Example client code:</p> <pre><code>... IFactory factory = (IFactory) System.Activator.GetObject (typeof (IFactory), url); ... IFoo foo = factory.GetFoo (); // the server returns an interface; we get a proxy to it foo.DoSomething (); ... </code></pre> <p>This all works great. However, now I am trying to migrate my code to WCF. I wonder if there is a means to pass around interfaces and having WCF generate the proxies on the fly on the client, as does the original .NET remoting.</p> <p>And I don't want to return class instances, since I don't want to expose real classes. And serializing the full instance and sending it back and forth between the server and the client is not an option either. I really just want the client to talk to the server object through an interface pointer/proxy.</p> <p>Any ideas?</p>
[ { "answer_id": 288425, "author": "Pierre Arnaud", "author_id": 4597, "author_profile": "https://Stackoverflow.com/users/4597", "pm_score": 1, "selected": false, "text": "ChannelFactory IFactory ServiceHost IFoo ServiceHost IFactory IFactory IFoo factory.GetFoo (); EndPointAddress10 ChannelFactory" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
288,319
<p>I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future</p>
[ { "answer_id": 288328, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n<style>\n #upperDiv {width:200px; height:20px; text-align:center; cursor:pointer; }\n #lowerDiv {width:200px; height:20px; background-color:red; border:#206ba4 1px solid;}\n</style>\n\n<script language=\"Javascript\" src=\"javascript/jquery-1.2.6.min.js\"></script>\n<script type=\"text/JavaScript\">\n\n$(function(){\n$('#upperDiv').toggle (\n function(){ \n $(\"#lowerDiv\").hide() ; \n },\n function(){ \n $(\"#lowerDiv\").show() ; \n }\n); // End toggle\n }); // End eventlistener\n\n</script>\n</head>\n<body>\n<div id=\"upperDiv\" >Upper div</div>\n<div id=\"lowerDiv\" >Lover Div</div>\n</body>\n</html>\n" }, { "answer_id": 288345, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "toggle() #lowerDiv $('#upperDiv').click(function() {\n $('#lowerDiv').animate({\n 'opacity' : 'toggle',\n });\n});\n" }, { "answer_id": 47716274, "author": "thvs86", "author_id": 6094194, "author_profile": "https://Stackoverflow.com/users/6094194", "pm_score": 0, "selected": false, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"#pClick\").click(function(){ \n $(\"#pText\").toggle();\n $(\"#pText\").text(\"...\");\n });\n });\n </script>\n #pText {display: none;}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
288,349
<p>Does anyone know of a good alternative to cron? I would like something that can be run with different time zones.</p>
[ { "answer_id": 288399, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "Date" }, { "answer_id": 5895518, "author": "mecano", "author_id": 731772, "author_profile": "https://Stackoverflow.com/users/731772", "pm_score": 1, "selected": false, "text": "cron at xinet watchdog launchd" }, { "answer_id": 8079055, "author": "hroptatyr", "author_id": 107375, "author_profile": "https://Stackoverflow.com/users/107375", "pm_score": 2, "selected": false, "text": "CRON_TZ" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
288,350
<p>Can anybody tell me when Application_End is triggered in a lifecycle of an application? When all sessions are ended, will Application_End be triggered automatically? + Are there any other reasons why Application_End could be triggered?</p>
[ { "answer_id": 288411, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 6, "selected": true, "text": "application_end" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26521/" ]
288,357
<p>So if I have:</p> <pre><code>public class ChildClass : BaseClass { public new virtual string TempProperty { get; set; } } public class BaseClass { public virtual string TempProperty { get; set; } } </code></pre> <p>How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?</p> <p>I'd like the answer to be agnostic between c# and vb.net</p>
[ { "answer_id": 288372, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": -1, "selected": false, "text": "Module Module1\n\n Class Foo\n Public Function SomeFunc() As Integer\n Return 42\n End Function\n End Class\n\n Class Bar\n Inherits Foo\n Public Shadows Function SomeFunc() As Integer\n Return 36\n End Function\n End Class\n\n Sub Main()\n Dim type = GetType(Bar)\n Dim func = type.GetMethod(\"SomeFunc\")\n Stop\n End Sub\n\nEnd Module\n" }, { "answer_id": 288714, "author": "Tinister", "author_id": 34715, "author_profile": "https://Stackoverflow.com/users/34715", "pm_score": 3, "selected": false, "text": "public static bool IsHidingMember( this PropertyInfo self )\n{\n Type baseType = self.DeclaringType.BaseType;\n PropertyInfo baseProperty = baseType.GetProperty( self.Name, self.PropertyType );\n\n if ( baseProperty == null )\n {\n return false;\n }\n\n if ( baseProperty.DeclaringType == self.DeclaringType )\n {\n return false;\n }\n\n var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();\n var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();\n\n return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;\n}\n" }, { "answer_id": 288928, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 6, "selected": true, "text": "hidebysig non-virtual : .method public hidebysig specialname instance\nvirtual : .method public hidebysig specialname newslot virtual instance \n override : .method public hidebysig specialname virtual instance \nnew : .method public hidebysig specialname instance\nnew virtual : .method public hidebysig specialname newslot virtual instance \n new new new virtual virtual newslot var prop = typeof(ChildClass).GetProperty(\"TempProperty\");\nvar getMethod = prop.GetGetMethod();\nif ((getMethod.Attributes & MethodAttributes.Virtual) != 0 &&\n (getMethod.Attributes & MethodAttributes.NewSlot) == 0)\n{\n // the property's 'get' method is an override\n}\n hidebysig else \n{\n if (getMethod.IsHideBySig)\n {\n var flags = getMethod.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;\n flags |= getMethod.IsStatic ? BindingFlags.Static : BindingFlags.Instance;\n var paramTypes = getMethod.GetParameters().Select(p => p.ParameterType).ToArray();\n if (getMethod.DeclaringType.BaseType.GetMethod(getMethod.Name, flags, null, paramTypes, null) != null)\n {\n // the property's 'get' method shadows by signature\n }\n }\n else\n {\n var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;\n if (getMethod.DeclaringType.BaseType.GetMethods(flags).Any(m => m.Name == getMethod.Name))\n {\n // the property's 'get' method shadows by name\n }\n }\n}\n Foo foo hidebysig" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
288,364
<p>I have two system calls GetSystemTime() and GetThreadTimes() that I need to calculate the CPU utilization by a given Win32 thread.</p> <p>For the sake of accuracy, I need to ensure that both GetSystemTime() and GetThreadTimes() are executed atomically; i.e. there should be no context switch in between a call to GetSystemTime() &amp; GetThreadTimes().</p> <p>The reason is that occasionally I end up with a percentage of over 100% (~ 1 in 500).</p> <p>How can I ensure an atomic execution of the 2 function calls?</p> <p>Thanks, Sachin</p>
[ { "answer_id": 288403, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 2, "selected": false, "text": "perc = ( perc > 100.0f ) ? 100.0f : perc;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33870/" ]
288,368
<p>Do any of the existing JavaScript frameworks have a non-regex <code>replace()</code> function, or has this already been posted on the web somewhere as a one-off function?</p> <p>For example I want to replace <code>"@!#$123=%"</code> and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.</p>
[ { "answer_id": 288384, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 6, "selected": true, "text": "replace() var string = '@!#$123=%';\nvar newstring = string.replace('@!#$123=%', 'hi');\n" }, { "answer_id": 6724957, "author": "Nick Ager", "author_id": 848808, "author_profile": "https://Stackoverflow.com/users/848808", "pm_score": 5, "selected": false, "text": "\"some text containing regex interpreted characters: $1.00\".split(\"$\").join(\"£\");\n \"some text containing regex interpreted characters: $1.00\".replace(new RegExp(\"$\"),\"£\")\n" }, { "answer_id": 18675737, "author": "Steven Lizarazo", "author_id": 589132, "author_profile": "https://Stackoverflow.com/users/589132", "pm_score": 2, "selected": false, "text": "function replaceAllTemp(str,find, replace) { \nvar ignoreCase=true;\nvar _token;\nvar token=find;\nvar newToken=replace;\nvar i = -1;\n\nif ( typeof token === \"string\" ) {\n\n if ( ignoreCase ) {\n\n _token = token.toLowerCase();\n\n while( (\n i = str.toLowerCase().indexOf(\n token, i >= 0 ? i + newToken.length : 0\n ) ) !== -1\n ) {\n str = str.substring( 0, i ) +\n newToken +\n str.substring( i + token.length );\n }\n\n } else {\n return this.split( token ).join( newToken );\n }\n\n}\nreturn str;\n};\n" }, { "answer_id": 56989647, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 1, "selected": false, "text": "toLowerCase toLocaleLowerCase function replaceAll(str, find, newToken, ignoreCase)\n{\n var i = -1;\n\n if (!str)\n {\n // Instead of throwing, act as COALESCE if find == null/empty and str == null\n if ((str == null) && (find == null))\n return newToken;\n\n return str;\n }\n\n if (!find) // sanity check \n return str;\n\n ignoreCase = ignoreCase || false;\n find = ignoreCase ? find.toLowerCase() : find;\n\n while ((\n i = (ignoreCase ? str.toLowerCase() : str).indexOf(\n find, i >= 0 ? i + newToken.length : 0\n )) !== -1\n )\n {\n str = str.substring(0, i) +\n newToken +\n str.substring(i + find.length);\n } // Whend \n\n return str;\n}\n if (!String.prototype.replaceAll ) { \nString.prototype.replaceAll = function (find, replace) {\n var str = this, i = -1;\n\n if (!str)\n {\n // Instead of throwing, act as COALESCE if find == null/empty and str == null\n if ((str == null) && (find == null))\n return newToken;\n\n return str;\n }\n\n if (!find) // sanity check \n return str;\n\n ignoreCase = ignoreCase || false;\n find = ignoreCase ? find.toLowerCase() : find;\n\n while ((\n i = (ignoreCase ? str.toLowerCase() : str).indexOf(\n find, i >= 0 ? i + newToken.length : 0\n )) !== -1\n )\n {\n str = str.substring(0, i) +\n newToken +\n str.substring(i + find.length);\n } // Whend \n\n return str;\n};\n}\n" }, { "answer_id": 71562813, "author": "Mordechai", "author_id": 1751640, "author_profile": "https://Stackoverflow.com/users/1751640", "pm_score": 2, "selected": false, "text": "$bc $$bc 'abc'.replace('a', '$$')\n 'abc'.replace('a', () => '$$')\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
288,374
<p>A method I work with that is called tens of thousands of times started throwing exceptions recently. In most debugging circumstances I would set a breakpoint at the top of this method and run through until I reach the call I'm interested in with a parameter value that triggers the exception. In this case that would be impractical, so I tried setting a breakpoint with a condition that will only break when that parameter value appears. I created a breakpoint at the position indicated below and gave it a condition <code>str == "OffendingValue"</code>. </p> <pre><code>class Foo { // Bar() is called many, many times void Bar(string str) { try { // Breakpoint inserted here ... } catch (Exception ex) { ... } } } </code></pre> <p>To my surprise, doing this caused Visual Studio and my application to stop functioning in Debug mode. My application started and output some simple logging messages but then stopped responding entirely. Thinking Visual Studio might just be performing a little slower due to the extra work it has to do to monitor the breakpoint condition, I stepped away from my desk for 15 mintues to give it some time to run. When I returned there was no change. I can reproduce the condition by deleting the breakpoint and recreating it with the same condition. Strangest of all, the Break All debugging command, which will usually break program execution on the statement that's currently execting whether it's a breakpoint or not, does nothing at all when I have this problematic breakpoint enabled. </p> <p>Has anyone encountered similar behavior with Visual Studio breakpoint conditions? I am able to use Hit Count conditions without problem. </p>
[ { "answer_id": 288521, "author": "asponge", "author_id": 19449, "author_profile": "https://Stackoverflow.com/users/19449", "pm_score": 4, "selected": true, "text": "class Foo\n{\n // Bar() is called many, many times\n void Bar(string str)\n {\n try\n {\n\n if(str == \"condition\")\n {\n int i = 0; // Breakpoint inserted here\n }\n ...\n }\n catch (Exception ex)\n {\n ...\n }\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28350/" ]
288,392
<p>My ASP.NET application needs a number of supporting services to run periodically in the background. For example:</p> <ul> <li>I need to query the database (or cache) every 1-5 minutes, identify overdue work items and notify users by email</li> <li>I need to generate nightly reports that are then emailed to subscribers</li> <li>Plus other system/non-user admin tasks</li> </ul> <p>What is the best way to implement these services? Should I include them as part of the web application, starting an instance of each 'service' in Application_Start()? Or create them as actual standalone services? If they were part of the web application I can potentially utilize my cached data store, but are there any downsides to this approach?</p> <p>Thanks for any advice.</p>
[ { "answer_id": 288539, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 1, "selected": false, "text": "Timer timer = new Timer(intervalSeconds * 1000)\ntimer.Elapsed += delegate\n{\n // do the meat\n};\ntimer.Start();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
288,409
<p>If I create a UserControl and add some objects to it, how can I grab the HTML it would render?</p> <p>ex.</p> <pre><code>UserControl myControl = new UserControl(); myControl.Controls.Add(new TextBox()); // ...something happens return strHTMLofControl; </code></pre> <p>I'd like to just convert a newly built UserControl to a string of HTML.</p>
[ { "answer_id": 288414, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": ".RenderControl()" }, { "answer_id": 288419, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 7, "selected": true, "text": "Control.RenderControl(HtmlTextWriter) StringWriter HtmlTextWriter StringBuilder StringWriter StringBuilder string html = String.Empty;\nusing (TextWriter myTextWriter = new StringWriter(new StringBuilder()))\n{\n using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))\n {\n myControl.RenderControl(myWriter);\n html = myTextWriter.ToString();\n }\n}\n" }, { "answer_id": 288427, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "protected override void Render(HtmlTextWriter output)\n{ \n output.Write(\"<br>Message from Control : \" + Message); \n output.Write(\"Showing Custom controls created in reverse\" +\n \"order\"); \n // Render Controls.\n RenderChildren(output);\n}\n" }, { "answer_id": 832696, "author": "Ben Aston", "author_id": 38522, "author_profile": "https://Stackoverflow.com/users/38522", "pm_score": 5, "selected": false, "text": "//render control to string\nStringBuilder b = new StringBuilder();\nHtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));\nthis.LoadControl(\"~/path_to_control.ascx\").RenderControl(h);\nstring controlAsString = b.ToString();\n" }, { "answer_id": 4777200, "author": "theJerm", "author_id": 118191, "author_profile": "https://Stackoverflow.com/users/118191", "pm_score": 4, "selected": false, "text": "UserControl uc = new UserControl();\nMyCustomUserControl mu = (MyCustomUserControl)uc.LoadControl(\"~/Controls/MyCustomUserControl.ascx\");\n\nTextWriter tw = new StringWriter();\nHtmlTextWriter hw = new HtmlTextWriter(tw);\n\nmu.RenderControl(hw);\n\nreturn tw.ToString();\n" }, { "answer_id": 31619749, "author": "Reikim", "author_id": 4271595, "author_profile": "https://Stackoverflow.com/users/4271595", "pm_score": 3, "selected": false, "text": "StringBuilder StringWriter HtmlWriter RenderControl Page <form> runat=\"server\" Page page = new Page();\npage.EnableEventValidation = false;\n\nHtmlForm form = new HtmlForm();\nform.Name = \"form1\";\npage.Controls.Add(form1);\n\nMyControl mc = new MyControl();\nform.Controls.Add(mc);\n\nStringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nHtmlTextWriter writer = new HtmlTextWriter(sw);\n\npage.RenderControl(writer);\n\nreturn sb.ToString();\n" }, { "answer_id": 41982072, "author": "Carl in 't Veld", "author_id": 1585847, "author_profile": "https://Stackoverflow.com/users/1585847", "pm_score": 1, "selected": false, "text": "HttpServerUtility.Execute HttpContext.Current.Server.Execute var page = new Page();\nvar myControl = (MyControl)page.LoadControl(\"mycontrol.ascx\");\nmyControl.SetSomeProperty = true;\npage.Controls.Add(myControl);\nvar sw = new StringWriter();\nHttpContext.Current.Server.Execute(page, sw, preserveForm: false);\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
288,412
<p>I did a few tests with TouchJSON last night and it worked pretty well in general for simple cases. I'm using the following code to read some JSON content from a file, and deserialize it:</p> <pre><code>NSString *jsonString = [[NSString alloc] initWithContentsOfFile:@"data.json"]; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding]; NSError *error = nil; NSDictionary *items = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&amp;error]; NSLog(@"total items: %d", [items count]); NSLog(@"error: %@", [error localizedDescription]); </code></pre> <p>That works fine if I have a very simple JSON object in the file (i.e. a dictionary):</p> <pre><code>{"id": "54354", "name": "boohoo"} </code></pre> <p>This way I was able to get access to the array of values, as I wanted to get the item based on its index within the list:</p> <pre><code>NSArray *items_list = [items allValues]; NSString *name = [items_list objectAtIndex:1]; </code></pre> <p><em>(I understand that I could have fetched the name with the dictionary API)</em></p> <p>Now I would like to deserialize a semi-complex JSON string, which represents an array of dictionaries. An example of such a JSON string is below:</p> <pre><code>[{"id": "123456", "name": "touchjson"}, {"id": "3456", "name": "bleh"}] </code></pre> <p>When I try to run the same code above against this new content in the data.json file, I don't get any results back. My NSLog() call says "total items: 0", and no error is coming back in the NSError object.</p> <p>Any clues on what is going on? I'm completely lost on what to do, as there isn't much documentation available for TouchJSON, and much less usage examples.</p>
[ { "answer_id": 289175, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 0, "selected": false, "text": "{\n \"objects\": [{\n \"id\": \"123456\",\n \"name\": \"touchjson\"\n }, {\n \"id\": \"3456\",\n \"name\": \"bleh\"\n }]\n}\n" }, { "answer_id": 289193, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 4, "selected": false, "text": "- (id)deserialize:(NSData *)inData error:(NSError **)outError;\n" }, { "answer_id": 954728, "author": "gene tsai", "author_id": 82174, "author_profile": "https://Stackoverflow.com/users/82174", "pm_score": 0, "selected": false, "text": "NSArray *tweetsArray = [resultsDictionary objectForKey:@\"results\"]; \nfor (NSDictionary *tweetDictionary in tweetsArray) { \n NSString *tweetText = [tweetDictionary objectForKey:@\"text\"]; \n [tweets addObject:tweetText]; \n} \n {\"results\": \n [ \n {\"text\":\"tweet1\"}, \n {\"text\":\"tweet2\"}, \n {\"text\":\"tweet3\"} \n ] \n} \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35478/" ]
288,413
<p>I am using this code to verify a behavior of a method I am testing:</p> <pre><code> _repository.Expect(f =&gt; f.FindAll(t =&gt; t.STATUS_CD == "A")) .Returns(new List&lt;JSOFile&gt;()) .AtMostOnce() .Verifiable(); </code></pre> <p>_repository is defined as:</p> <pre><code>private Mock&lt;IRepository&lt;JSOFile&gt;&gt; _repository; </code></pre> <p>When my test is run, I get this exception:</p> <p><strong>Expression t => (t.STATUS_CD = "A") is not supported.</strong></p> <p>Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?</p> <p>Thanks!!</p>
[ { "answer_id": 288509, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Func<JSOFile, bool> _myDelegate;\n\n_repository.Stub(f => FindAll(null)).IgnoreArguments()\n .Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});\n Assert.IsTrue(_myDelegate.Invoke(fakeJSO));\n" }, { "answer_id": 288649, "author": "flukus", "author_id": 407256, "author_profile": "https://Stackoverflow.com/users/407256", "pm_score": 0, "selected": false, "text": " _repository.Expect(f => f.FindAll(It.Is<SomeType>(t => t.STATUS_CD == \"A\")))\n" }, { "answer_id": 1120836, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 2, "selected": false, "text": " [Test]\n public void MoqTests()\n {\n var mockedRepo = new Mock<IRepository<Meeting>>();\n mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());\n Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));\n Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);\n }\n\n //I broke this out into a helper as its a bit ugly\n Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)\n {\n return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]