qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
108,104
<p>Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"</p> <p>So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?</p> <p>So I have</p> <pre><code>typeof(int) typeof(DateTime) System.Type t = something; </code></pre> <p>and I want</p> <pre><code>int? DateTime? </code></pre> <p>or</p> <pre><code>Nullable&lt;int&gt; (which is the same) if (t is primitive) then Nullable&lt;T&gt; else just T </code></pre> <p>Is there a built-in method?</p>
[ { "answer_id": 108122, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 8, "selected": true, "text": "Type GetNullableType(Type type) {\n // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.\n type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null\n if (type.IsValueType)\n return typeof(Nullable<>).MakeGenericType(type);\n else\n return type;\n}\n" }, { "answer_id": 108129, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 2, "selected": false, "text": "int? Nullable<T> Nullable Nullable<>" }, { "answer_id": 2473675, "author": "Thracx", "author_id": 296924, "author_profile": "https://Stackoverflow.com/users/296924", "pm_score": 4, "selected": false, "text": "Nullable.GetUnderlyingType(type) Nullable System.RuntimeType typeof(System.Int32) Nullable.GetUnderlyingType(type) Nullable ExtensionMethod ValueType Nullable Type NullableVersion(this Type sourceType)\n{\n if(sourceType == null)\n {\n // Throw System.ArgumentNullException or return null, your preference\n }\n else if(sourceType == typeof(void))\n { // Special Handling - known cases where Exceptions would be thrown\n return null; // There is no Nullable version of void\n }\n\n return !sourceType.IsValueType\n || (sourceType.IsGenericType\n && sourceType.GetGenericTypeDefinition() == typeof(Nullable<>) )\n ? sourceType\n : typeof(Nullable<>).MakeGenericType(sourceType);\n}\n" }, { "answer_id": 7759487, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 4, "selected": false, "text": " /// <summary>\n /// [ <c>public static Type GetNullableType(Type TypeToConvert)</c> ]\n /// <para></para>\n /// Convert any Type to its Nullable&lt;T&gt; form, if possible\n /// </summary>\n /// <param name=\"TypeToConvert\">The Type to convert</param>\n /// <returns>\n /// The Nullable&lt;T&gt; converted from the original type, the original type if it was already nullable, or null \n /// if either <paramref name=\"TypeToConvert\"/> could not be converted or if it was null.\n /// </returns>\n /// <remarks>\n /// To qualify to be converted to a nullable form, <paramref name=\"TypeToConvert\"/> must contain a non-nullable value \n /// type other than System.Void. Otherwise, this method will return a null.\n /// </remarks>\n /// <seealso cref=\"Nullable&lt;T&gt;\"/>\n public static Type GetNullableType(Type TypeToConvert)\n {\n // Abort if no type supplied\n if (TypeToConvert == null)\n return null;\n\n // If the given type is already nullable, just return it\n if (IsTypeNullable(TypeToConvert))\n return TypeToConvert;\n\n // If the type is a ValueType and is not System.Void, convert it to a Nullable<Type>\n if (TypeToConvert.IsValueType && TypeToConvert != typeof(void))\n return typeof(Nullable<>).MakeGenericType(TypeToConvert);\n\n // Done - no conversion\n return null;\n }\n /// <summary>\n /// [ <c>public static bool IsTypeNullable(Type TypeToTest)</c> ]\n /// <para></para>\n /// Reports whether a given Type is nullable (Nullable&lt; Type &gt;)\n /// </summary>\n /// <param name=\"TypeToTest\">The Type to test</param>\n /// <returns>\n /// true = The given Type is a Nullable&lt; Type &gt;; false = The type is not nullable, or <paramref name=\"TypeToTest\"/> \n /// is null.\n /// </returns>\n /// <remarks>\n /// This method tests <paramref name=\"TypeToTest\"/> and reports whether it is nullable (i.e. whether it is either a \n /// reference type or a form of the generic Nullable&lt; T &gt; type).\n /// </remarks>\n /// <seealso cref=\"GetNullableType\"/>\n public static bool IsTypeNullable(Type TypeToTest)\n {\n // Abort if no type supplied\n if (TypeToTest == null)\n return false;\n\n // If this is not a value type, it is a reference type, so it is automatically nullable\n // (NOTE: All forms of Nullable<T> are value types)\n if (!TypeToTest.IsValueType)\n return true;\n\n // Report whether TypeToTest is a form of the Nullable<> type\n return TypeToTest.IsGenericType && TypeToTest.GetGenericTypeDefinition() == typeof(Nullable<>);\n }\n // Abort if no type supplied\n if (TypeToTest == null)\n return false;\n\n // If this is not a value type, it is a reference type, so it is automatically nullable\n // (NOTE: All forms of Nullable<T> are value types)\n if (!TypeToTest.IsValueType)\n return true;\n\n // Report whether an underlying Type exists (if it does, TypeToTest is a nullable Type)\n return Nullable.GetUnderlyingType(TypeToTest) != null;\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
108,134
<p>I am using <code>pyexcelerator</code> Python module to generate Excel files. I want to apply bold style to part of cell text, but not to the whole cell. How to do it?</p>
[ { "answer_id": 108204, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "With Worksheets(\"Sheet1\").Range(\"B1\")\n .Value = \"New Title\"\n .Characters(5, 5).Font.Bold = True\nEnd With\n" }, { "answer_id": 109724, "author": "Greg", "author_id": 13009, "author_profile": "https://Stackoverflow.com/users/13009", "pm_score": 2, "selected": false, "text": "import pyExcelerator as xl\n\ndef save_in_excel(headers,values):\n #Open new workbook\n mydoc=xl.Workbook()\n #Add a worksheet\n mysheet=mydoc.add_sheet(\"test\")\n #write headers\n header_font=xl.Font() #make a font object\n header_font.bold=True\n header_font.underline=True\n #font needs to be style actually\n header_style = xl.XFStyle(); header_style.font = header_font\n for col,value in enumerate(headers):\n mysheet.write(0,col,value,header_style)\n #write values and highlight those that match my criteria\n highlighted_row_font=xl.Font() #no real highlighting available?\n highlighted_row_font.bold=True\n highlighted_row_font.colour_index=2 #2 is red,\n highlighted_row_style = xl.XFStyle(); highlighted_row_style.font = highlighted_row_font\n for row_num,row_values in enumerate(values):\n row_num+=1 #start at row 1\n if row_values[1]=='Manatee':\n for col,value in enumerate(row_values):\n #make Manatee's (sp) red\n mysheet.write(row_num,col,value,highlighted_row_style)\n else:\n for col,value in enumerate(row_values):\n #normal row\n mysheet.write(row_num,col,value)\n #save file\n mydoc.save(r'C:testpyexel.xlt')\n\nheaders=['Date','Name','Localatity']\ndata=[\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Manatee','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Manatee','San Jose'],\n]\n\nsave_in_excel(headers,data)\n" }, { "answer_id": 66246157, "author": "ItsPrinceAk", "author_id": 10730446, "author_profile": "https://Stackoverflow.com/users/10730446", "pm_score": 1, "selected": false, "text": " import xlsxwriter\n workbook = xlsxwriter.Workbook(r'C:\\workspace\\NMSAutomation_001\\FMGGUIAutomation\\Libraries\\Frontend\\new_STICKERS_Final.xlsx')\n####### two different formats\n bold = workbook.add_format({'font_name':'Tahoma', 'bold': True, 'font_size':14})\n normal = workbook.add_format({'font_name':'Tahoma', 'font_size':11})\n\n######## value is my string, bold and normal are my two different formats\n segments = [bold, value[:9], normal, value[9:]]\n worksheet.write_rich_string('A1', *segments) # 'A1' is cell position\n workbook.close()\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19607/" ]
108,149
<p>I know that it's possible to replace the browse button, which is generated in html, when you use <code>input</code> tag with <code>type="file</code>.</p> <p>I'm not sure what is the best way, so if someone has experience with this please contribute. </p>
[ { "answer_id": 108176, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<input type=\"file\" id=\"fileInput\">\n<img src=\"...\">\n #fileInput{\n position: absolute;\n opacity: 0;\n -moz-opacity: 0;\n filter: alpha(opacity=0);\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16039/" ]
108,169
<p>Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?</p> <h3>EDIT:</h3> <p>Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.</p>
[ { "answer_id": 108248, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 4, "selected": true, "text": "(define get-n-items\n (lambda (lst num)\n (if (> num 0)\n (cons (car lst) (get-n-items (cdr lst) (- num 1)))\n '()))) ;'\n\n(define slice\n (lambda (lst start count)\n (if (> start 1)\n (slice (cdr lst) (- start 1) count)\n (get-n-items lst count))))\n > (define l '(2 3 4 5 6 7 8 9)) ;'\n()\n> l\n(2 3 4 5 6 7 8 9)\n> (slice l 2 4)\n(3 4 5 6)\n> \n" }, { "answer_id": 108265, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "(define (sublist list start number)\n (cond ((> start 0) (sublist (cdr list) (- start 1) number))\n ((> number 0) (cons (car list)\n (sublist (cdr list) 0 (- number 1))))\n (else '())))\n" }, { "answer_id": 108266, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 1, "selected": false, "text": " (define (slice l offset length)\n (if (null? l)\n l\n (if (> offset 0)\n (slice (cdr l) (- offset 1) length)\n (if (> length 0)\n (cons (car l) (slice (cdr l) 0 (- length 1)))\n '()))))\n" }, { "answer_id": 121976, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": false, "text": "slice take drop (define (slice l offset n)\n (take (drop l offset) n))\n" }, { "answer_id": 35534477, "author": "Mulan", "author_id": 633183, "author_profile": "https://Stackoverflow.com/users/633183", "pm_score": 1, "selected": false, "text": "slice (define (slice a b xs (ys null))\n (cond ((> a 0) (slice (- a 1) b (cdr xs) ys))\n ((> b 0) (slice a (- b 1) (cdr xs) (cons (car xs) ys)))\n (else (reverse ys))))\n\n(slice 0 3 '(A B C D E F G)) ;=> '(A B C)\n(slice 2 4 '(A B C D E F G)) ;=> '(C D E F)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
108,183
<p>I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.</p> <p>The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a <code>SIGPIPE</code> and make my server crash.</p> <p>What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (<code>select()</code> doesn't seem to work here as it always says the socket is writable). Or should I just catch the <code>SIGPIPE</code> with a handler and ignore it?</p>
[ { "answer_id": 108192, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 9, "selected": true, "text": "SIGPIPE SIGPIPE SIG_IGN SIGPIPE SIGPIPE signal(SIGPIPE, SIG_IGN);\n send() MSG_NOSIGNAL SIGPIPE MSG_NOSIGNAL SO_SIGNOPIPE setsockopt() SIGPIPE" }, { "answer_id": 450130, "author": "user55807", "author_id": 55807, "author_profile": "https://Stackoverflow.com/users/55807", "pm_score": 7, "selected": false, "text": "int set = 1;\nsetsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));\n" }, { "answer_id": 1705705, "author": "sklnd", "author_id": 204462, "author_profile": "https://Stackoverflow.com/users/204462", "pm_score": 7, "selected": false, "text": "SO_NOSIGPIPE SO_NOSIGPIPE MSG_NOSIGNAL write(...) send(...,MSG_NOSIGNAL) char buf[888];\n//write( sockfd, buf, sizeof(buf) );\nsend( sockfd, buf, sizeof(buf), MSG_NOSIGNAL );\n" }, { "answer_id": 9036323, "author": "Sam", "author_id": 590956, "author_profile": "https://Stackoverflow.com/users/590956", "pm_score": 5, "selected": false, "text": "// We expect write failures to occur but we want to handle them where \n// the error occurs rather than in a SIGPIPE handler.\nsignal(SIGPIPE, SIG_IGN);\n" }, { "answer_id": 35354069, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "sigprocmask() #include <signal.h>\n\nvoid block_signal(int signal_to_block /* i.e. SIGPIPE */ )\n{\n sigset_t set;\n sigset_t old_state;\n\n // get the current state\n //\n sigprocmask(SIG_BLOCK, NULL, &old_state);\n\n // add signal_to_block to that existing state\n //\n set = old_state;\n sigaddset(&set, signal_to_block);\n\n // block that signal also\n //\n sigprocmask(SIG_BLOCK, &set, NULL);\n\n // ... deal with old_state if required ...\n}\n old_state old_state" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12523/" ]
108,193
<pre><code>class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) </code></pre> <p>Simple models just to ask my question.</p> <p>I wonder how can i query blogs using tags in two different ways.</p> <ul> <li>Blog entries that are tagged with "tag1" or "tag2": <code>Blog.objects.filter(tags_in=[1,2]).distinct()</code></li> <li>Blog objects that are tagged with "tag1" and "tag2" : <strong>?</strong></li> <li>Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : <strong>??</strong></li> </ul> <hr> <p>Tag and Blog is just used for an example.</p>
[ { "answer_id": 108404, "author": "Clint Ecker", "author_id": 13668, "author_profile": "https://Stackoverflow.com/users/13668", "pm_score": 6, "selected": true, "text": "# Blogs who have either hockey or django tags.\nfrom django.db.models import Q\nBlog.objects.filter(\n Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')\n)\n def get_union_by_model(self, queryset_or_model, tags):\n \"\"\"\n Create a ``QuerySet`` containing instances of the specified\n model associated with *any* of the given list of tags.\n \"\"\"\n tags = get_tag_list(tags)\n tag_count = len(tags)\n queryset, model = get_queryset_and_model(queryset_or_model)\n\n if not tag_count:\n return model._default_manager.none()\n\n model_table = qn(model._meta.db_table)\n # This query selects the ids of all objects which have any of\n # the given tags.\n query = \"\"\"\n SELECT %(model_pk)s\n FROM %(model)s, %(tagged_item)s\n WHERE %(tagged_item)s.content_type_id = %(content_type_id)s\n AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)\n AND %(model_pk)s = %(tagged_item)s.object_id\n GROUP BY %(model_pk)s\"\"\" % {\n 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),\n 'model': model_table,\n 'tagged_item': qn(self.model._meta.db_table),\n 'content_type_id': ContentType.objects.get_for_model(model).pk,\n 'tag_id_placeholders': ','.join(['%s'] * tag_count),\n }\n\n cursor = connection.cursor()\n cursor.execute(query, [tag.pk for tag in tags])\n object_ids = [row[0] for row in cursor.fetchall()]\n if len(object_ids) > 0:\n return queryset.filter(pk__in=object_ids)\n else:\n return model._default_manager.none()\n def get_intersection_by_model(self, queryset_or_model, tags):\n \"\"\"\n Create a ``QuerySet`` containing instances of the specified\n model associated with *all* of the given list of tags.\n \"\"\"\n tags = get_tag_list(tags)\n tag_count = len(tags)\n queryset, model = get_queryset_and_model(queryset_or_model)\n\n if not tag_count:\n return model._default_manager.none()\n\n model_table = qn(model._meta.db_table)\n # This query selects the ids of all objects which have all the\n # given tags.\n query = \"\"\"\n SELECT %(model_pk)s\n FROM %(model)s, %(tagged_item)s\n WHERE %(tagged_item)s.content_type_id = %(content_type_id)s\n AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)\n AND %(model_pk)s = %(tagged_item)s.object_id\n GROUP BY %(model_pk)s\n HAVING COUNT(%(model_pk)s) = %(tag_count)s\"\"\" % {\n 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),\n 'model': model_table,\n 'tagged_item': qn(self.model._meta.db_table),\n 'content_type_id': ContentType.objects.get_for_model(model).pk,\n 'tag_id_placeholders': ','.join(['%s'] * tag_count),\n 'tag_count': tag_count,\n }\n\n cursor = connection.cursor()\n cursor.execute(query, [tag.pk for tag in tags])\n object_ids = [row[0] for row in cursor.fetchall()]\n if len(object_ids) > 0:\n return queryset.filter(pk__in=object_ids)\n else:\n return model._default_manager.none()\n" }, { "answer_id": 108500, "author": "Ycros", "author_id": 10495, "author_profile": "https://Stackoverflow.com/users/10495", "pm_score": 4, "selected": false, "text": "Blog.objects.filter(tags__name__in=['tag1', 'tag2']).distinct()\n Blog.objects.filter(Q(tags__name='tag1') | Q(tags__name='tag2')).distinct()\n Blog.objects.filter(tags__name='tag1').filter(tags__name='tag2')\n" }, { "answer_id": 4604096, "author": "amit", "author_id": 563925, "author_profile": "https://Stackoverflow.com/users/563925", "pm_score": 3, "selected": false, "text": "Blog.objects.filter(tags__name__in=['tag1', 'tag2']).annotate(tag_matches=models.Count(tags)).filter(tag_matches=2)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785/" ]
108,200
<p>I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?</p>
[ { "answer_id": 108239, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": "DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();\nSystem.out.println(parser2.parseDateTime(your_date_string));\n" }, { "answer_id": 108431, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 0, "selected": false, "text": "javax.mail.internet.MailDateFormat javax.mail.internet.MailDateParser int" }, { "answer_id": 11689182, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 1, "selected": false, "text": "int zone = new DateTimeParser(new StringReader(\"Fri, 27 Jul 2012 09:13:15 -0400\")).zone();\n // Stupid hack in case the zone is not in [-+]zzzz format\nfinal int hours;\nfinal int minutes;\nif (zone > 24 || zone < -24 ) {\n hours = zone / 100;\n minutes = minutes = Math.abs(zone % 100);\n}\nelse {\n hours = zone;\n minutes = 0;\n}\nDateTimeZone.forOffsetHoursMinutes(hours, minutes);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15231/" ]
108,207
<p>I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.</p> <p>BTW, this is an on-page <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> search, so it has no button.</p>
[ { "answer_id": 108218, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 4, "selected": false, "text": "onfocus onblur <input type=\"text\" class=\"hint\" value=\"Search...\"\n onfocus=\"if (this.className=='hint') { this.className = ''; this.value = ''; }\"\n onblur=\"if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }\">\n input.hint {\n color: grey;\n}\n" }, { "answer_id": 108222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<input onfocus=\"this.value=''\" type=\"text\" value=\"Search\" /> <input name=\"keyword_\" type=\"text\" size=\"25\" style=\"color:#999;\" maxlength=\"128\" id=\"keyword_\"\nonblur=\"this.value = this.value || this.defaultValue; this.style.color = '#999';\"\nonfocus=\"this.value=''; this.style.color = '#000';\"\nvalue=\"Search Term\">\n" }, { "answer_id": 108223, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 3, "selected": false, "text": "<input type=\"text\" id=\"textbox\" value=\"Search\"\n onclick=\"if(this.value=='Search'){this.value=''; this.style.color='#000'}\" \n onblur=\"if(this.value==''){this.value='Search'; this.style.color='#555'}\" />\n" }, { "answer_id": 108224, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": " input.foo { }\n input.fooempty { background-image: url(\"blah.png\"); }\n value == 0 <input class=\"foo fooempty\" value=\"\" type=\"text\" name=\"bar\" />\n jQuery(function($)\n{\n var target = $(\"input.foo\");\n target.bind(\"change\", function()\n {\n if( target.val().length > 1 )\n {\n target.addClass(\"fooempty\");\n }\n else\n {\n target.removeClass(\"fooempty\");\n }\n });\n});\n" }, { "answer_id": 108230, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "if (this.value == this.defaultValue)\n this.value = ''\nthis.className = ''\n if (this.value == '')\n this.value = this.defaultValue\nthis.className = 'placeholder'\n input.placeholder{\n color: gray;\n font-style: italic;\n}\n" }, { "answer_id": 108262, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<input type=\"text\" value=\"Search\" onfocus=\"this.select();\" />\n" }, { "answer_id": 108437, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": false, "text": "<style type=\"text/stylesheet\" media=\"screen\">\n .inputblank { color:gray; } /* Class to use for blank input */\n</style>\n <script language=\"javascript\"\n type=\"text/javascript\"\n src=\"http://www.google.com/jsapi\">\n</script>\n<script>\n // Load jQuery\n google.load(\"jquery\", \"1\");\n\n google.setOnLoadCallback(function() {\n $(\"#search_form\")\n .submit(function() {\n alert(\"Submitted. Value= \" + $(\"input:first\").val());\n return false;\n });\n\n $(\"#keywords\")\n .focus(function() {\n if ($(this).val() == 'Search') {\n $(this)\n .removeClass('inputblank')\n .val('');\n }\n })\n .blur(function() {\n if ($(this).val() == '') {\n $(this)\n .addClass('inputblank')\n .val('Search');\n }\n });\n });\n</script>\n <form id=\"search_form\">\n <fieldset>\n <legend>Search the site</legend>\n <label for=\"keywords\">Keywords:</label>\n <input id=\"keywords\" type=\"text\" class=\"inputblank\" value=\"Search\"/>\n </fieldset>\n</form>\n" }, { "answer_id": 949345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "$('input[value=\"text\"]').focus(function(){ \nif ($(this).attr('class')=='hint') \n{ \n $(this).removeClass('hint'); \n $(this).val(''); \n}\n});\n\n$('input[value=\"text\"]').blur(function(){\n if($(this).val() == '')\n {\n $(this).addClass('hint');\n $(this).val($(this).attr('title'));\n } \n});\n\n<input type=\"text\" value=\"\" title=\"Default Watermark Text\">\n" }, { "answer_id": 2658328, "author": "Dustin", "author_id": 292709, "author_profile": "https://Stackoverflow.com/users/292709", "pm_score": 2, "selected": false, "text": ".watermark" }, { "answer_id": 2994702, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": ".js <script type=\"text/javascript\" src=\"/hint-textbox.js\"></script>\n hintTextbox <input type=\"text\" name=\"email\" value=\"enter email\" class=\"hintTextbox\" />\n" }, { "answer_id": 3302835, "author": "0b10011", "author_id": 526741, "author_profile": "https://Stackoverflow.com/users/526741", "pm_score": 5, "selected": false, "text": "placeholder font-style color input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */\n color:gray;\n font-style:italic;\n}\ninput[type=search]:-moz-placeholder { /* Firefox 18- */\n color:gray;\n font-style:italic;\n}\ninput[type=search]::-moz-placeholder { /* Firefox 19+ */\n color:gray;\n font-style:italic;\n}\ninput[type=search]:-ms-input-placeholder { /* IE (10+?) */\n color:gray;\n font-style:italic;\n} <input placeholder=\"Search\" type=\"search\" name=\"q\">" }, { "answer_id": 3612949, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 10, "selected": true, "text": "<input name=\"email\" placeholder=\"Email Address\">\n $('input[placeholder], textarea[placeholder]').placeholder();\n" }, { "answer_id": 8813551, "author": "Isaac Liu", "author_id": 927512, "author_profile": "https://Stackoverflow.com/users/927512", "pm_score": 0, "selected": false, "text": "$('input[value=\"text\"]').blur();\n" }, { "answer_id": 37670822, "author": "Pradeep", "author_id": 2159249, "author_profile": "https://Stackoverflow.com/users/2159249", "pm_score": -1, "selected": false, "text": "<form>\n<input type=\"text\" name=\"test\" id=\"test\" required>\n<input type=\"submit\" value=\"enter\">\n</form>\n" }, { "answer_id": 38664150, "author": "apm", "author_id": 2982121, "author_profile": "https://Stackoverflow.com/users/2982121", "pm_score": 2, "selected": false, "text": "<input type=\"text\" name=\"fst_name\" placeholder=\"First Name\"/>\n" }, { "answer_id": 61569608, "author": "Kosem", "author_id": 6159404, "author_profile": "https://Stackoverflow.com/users/6159404", "pm_score": 0, "selected": false, "text": " <textarea onfocus=\"if (this.value == 'Text') { this.value = ''; }\" onblur=\"if (this.value == '') { this.value = 'Text'; }\">Text</textarea>\n\n <input type=\"text\" value=\"Text\" onfocus=\"if (this.value == 'Text') { this.value = ''; }\" onblur=\"if (this.value == '') { this.value = 'Text'; }\">\n" }, { "answer_id": 64685537, "author": "Green", "author_id": 13262204, "author_profile": "https://Stackoverflow.com/users/13262204", "pm_score": 0, "selected": false, "text": "placeholder=\"\" <html>\n<body>\n// try this out!\n<input placeholder=\"This is my placeholder\"/>\n</body>\n</html>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7668/" ]
108,211
<p>I want to add a <em>column</em> to an existing legacy <em>database</em> and write a <em>procedure</em> by which I can assign each record a different value. Something like adding a <em>column</em> and autogenerate the data for it.</p> <p>Like, if I add a new <em>column</em> called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID <em>column</em> will have records from say <code>1 to 1000</code>.<br> How do I do that?</p>
[ { "answer_id": 108227, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 9, "selected": true, "text": "alter table Example\nadd NewColumn int identity(1,1)\n" }, { "answer_id": 108237, "author": "Roy Tang", "author_id": 18494, "author_profile": "https://Stackoverflow.com/users/18494", "pm_score": 4, "selected": false, "text": "alter table mytable add (myfield integer);\n\nupdate mytable set myfield = rownum;\n" }, { "answer_id": 108253, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 5, "selected": false, "text": "ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY LAST_INSERT_ID()" }, { "answer_id": 7333178, "author": "Flavien Volken", "author_id": 532695, "author_profile": "https://Stackoverflow.com/users/532695", "pm_score": 3, "selected": false, "text": "ALTER TABLE tableName ADD id SERIAL;\nALTER TABLE tableName ADD PRIMARY KEY (id);\n" }, { "answer_id": 43544856, "author": "Jinlye", "author_id": 3328536, "author_profile": "https://Stackoverflow.com/users/3328536", "pm_score": 0, "selected": false, "text": "IDENTITY INT NULL UPDATE MyTable\nSET MyTable.MyNewColumn = AutoTable.AutoNum\nFROM\n(\n SELECT MyPrimaryKey, \n ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum\n FROM MyTable \n) AutoTable\nWHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey \n ROW_NUMBER()" }, { "answer_id": 47993046, "author": "Snziv Gupta", "author_id": 4412545, "author_profile": "https://Stackoverflow.com/users/4412545", "pm_score": 2, "selected": false, "text": "Alter table table_name\nadd ID UNIQUEIDENTIFIER not null unique default(newid())\n ALTER TABLE table_name\nADD CONSTRAINT PK_name PRIMARY KEY (ID);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ]
108,251
<p>On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though:</p> <pre> root# ls -la /dev/tty1 crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1 </pre> <p>Even weirder, this doesn't work:</p> <pre> root# cat &lt;/dev/tty1 bash: /dev/tty1: Permission denied </pre> <p>I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges?</p> <p>Update: I've made sure SELinux has been disabled; yet, the issue is still there....</p> <p>Update: The strace dump:</p> <pre> 32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0 32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0 32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000 32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35 </pre> <p>Can't say it's making much sense to me... </p>
[ { "answer_id": 172441, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "strace -f -o LOG bash -c 'cat < /dev/tty1'\n" }, { "answer_id": 8039115, "author": "Ryaner", "author_id": 99215, "author_profile": "https://Stackoverflow.com/users/99215", "pm_score": 0, "selected": false, "text": "c1:12345:respawn:/sbin/agetty 38400 tty1 linux\nc2:2345:respawn:/sbin/agetty 38400 tty2 linux\nc3:2345:respawn:/sbin/agetty 38400 tty3 linux\nc4:2345:respawn:/sbin/agetty 38400 tty4 linux\nc5:2345:respawn:/sbin/agetty 38400 tty5 linux\nc6:2345:respawn:/sbin/agetty 38400 tty6 linux\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19627/" ]
108,276
<p>I have a project with a bunch of external sounds to a SWF. I want to play them, but any time I attempt load a new URL into the sound object it fails with either,</p> <blockquote> <p>Error #2068: Invalid Sound</p> </blockquote> <p>or raises an ioError with </p> <blockquote> <p>Error #2032 Stream Error</p> </blockquote> <p>// Tried with path prefixed with "http://.." "file://.." "//.." and "..")</p> <pre><code>var path:String = "http://../assets/the_song.mp3"; var url:URLRequest = new URLRequest( path ); var sound:Sound = new Sound(); sound.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler); sound.addEventListener( SecurityErrorEvent.SECURITY_ERROR, secHandler); sound.load(url); </code></pre>
[ { "answer_id": 111372, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 3, "selected": true, "text": "soundTest/assets/song.mp3 soundTest/swfs/soundTest.swf var path:String = \"../assets/song.mp3\";" }, { "answer_id": 138592, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 2, "selected": false, "text": "var soundRequest:URLRequest = \"path/to/file.mp3\";\nvar s:Sound = new Sound(soundRequest);\nvar sChannel = s.play(0, int.MAX_VALUE); //Causes it to repeat by the highest possible number to flash.\n//Above starts the sound immediatly (Streaming);\n\n //Now to wait for completion instead, pretend we didnt start it before.\ns.addEventLister(Event.SOUND_COMPLETE, onSComplete, false, 0, true);\nfunction onSComplete(e:Event):void\n{\n var sChannel = s.play(0, int.MAX_VALUE); //Causes it to repeat by the highest possible\n} s.addEventLister(Event.SOUND_COMPLETE, onSComplete, false, 0, true);" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
108,281
<p>I have a table <code>y</code> Which has two columns <code>a</code> and <code>b</code></p> <p>Entries are:</p> <pre><code>a b 1 2 1 3 1 4 0 5 0 2 0 4 </code></pre> <p>I want to get 2,3,4 if I search column <code>a</code> for 1, and 5,2,4 if I search column <code>a</code>.</p> <p>So, if I search A for something that is in A, (1) I get those rows, and if there are no entries A for given value, give me the 'Defaults' (<code>a</code> = '0')</p> <p>Here is how I would know how to do it:</p> <pre><code>$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'1\';'); //This gives desired results, 3 rows $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'2\';'); //This does not give desired results yet. //Get the number of rows, and then get the 'defaults' if(mysql_num_rows($r) === 0) $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = 0;'); </code></pre> <p>So, now that it's sufficiently explained, how do I do that in one query, and what about performance concerns? </p> <p>The most used portion would be the third query, because there would only be values in <code>a</code> for a number IF you stray from the defaults.</p>
[ { "answer_id": 108607, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 0, "selected": false, "text": "create proc GetRealElseGetDefault (@key as int)\nas\nbegin\n\n-- Use this default if the correct data is not found\ndeclare @default int\nselect @default = 0\n\n-- See if the desired data exists, and if so, get it. \n-- Otherwise, get defaults.\nif exists (select * from TableY where a = @key)\n select b from TableY where a = @key\nelse\n select b from TableY where a = @default\n\nend -- GetRealElseGetDefault\n" }, { "answer_id": 108729, "author": "Lawrence Barsanti", "author_id": 13054, "author_profile": "https://Stackoverflow.com/users/13054", "pm_score": 2, "selected": false, "text": "SELECT b\nFROM table1 \nWHERE a = (\n SELECT\n CASE count(b)\n WHEN 0 THEN :default_value\n ELSE :passed_value \n END\n FROM table1\n WHERE a = :passed_value\n)\n" }, { "answer_id": 108824, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 1, "selected": false, "text": "$rows = $db->fetchAll('select a, b FROM y WHERE a IN (2, 0) ORDER BY a DESC');\nif(count($rows) > 0) {\n $a = $rows[0]['a'];\n $i = 0;\n while($rows[$i]['a'] === $a) {\n echo $rows[$i++]['b'].\"\\n\";\n }\n}\n" }, { "answer_id": 108913, "author": "Jonathan", "author_id": 19272, "author_profile": "https://Stackoverflow.com/users/19272", "pm_score": 3, "selected": true, "text": "SELECT b FROM y where a=if(@value IN (select a from y group by a),@value,0);\n" }, { "answer_id": 118127, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 1, "selected": false, "text": "// get the value for hte zero's\n$zeros = $db->fetchAll('select a, b FROM y WHERE a = 0');\n\n//checking for 1's\n$ones = $db->fetchAll('select a, b FROM y WHERE a = 1');\nif(empty($ones)) $ones = $zeros;\n\n//checking for 2's\n$twos = $db->fetchAll('select a, b FROM y WHERE a = 2');\nif(empty($twos)) $twos = $zeros;\n\n//checking for 3's\n$threes = $db->fetchAll('select a, b FROM y WHERE a = 3');\nif(empty($threes)) $threes = $zeros;\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
108,292
<p>When developing an application that sends out notification email messages, what are the best practices for </p> <ol> <li>not getting flagged as a spammer by your hosting company. (Cover any of:) <ul> <li>best technique for not flooding a mail server</li> <li>best mail server products, if you were to set up your own</li> <li>sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette</li> <li>any other lessons learned</li> </ul></li> <li>not getting flagged as spam by the receiver's client? (Cover any of:) <ul> <li>configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified</li> <li>best SMTP header techniques to avoid getting flagged as spam when sending emails for users (for example, using Sender and From headers together)</li> <li>any other lessons learned</li> </ul></li> </ol> <p>An additional requirement: this application would be sending a single message to a single recipient based upon an event. So, techniques for sending the same messages to multiple recipients will not apply.</p>
[ { "answer_id": 112607, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "From: me@me.com\nReturn-Path: me@me.com\nReply-To: auto@myapp.com\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16099/" ]
108,301
<p>I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in <code>JSP</code> development, but it appears to be common practice in <code>PHP</code>. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into consideration?</p>
[ { "answer_id": 110026, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 4, "selected": true, "text": "http://site.com/script.php?hello=world&foo=bar\n" }, { "answer_id": 110770, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "header(\"HTTP/1.0 404 Not Found\");\nexit;\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
108,318
<p>I need a function like this:</p> <pre><code>// return true if 'n' is a power of 2, e.g. // is_power_of_2(16) =&gt; true // is_power_of_2(3) =&gt; false bool is_power_of_2(int n); </code></pre> <p>Can anyone suggest how I could write this?</p>
[ { "answer_id": 108329, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 6, "selected": false, "text": "bool powerOfTwo = !(x == 0) && !(x & (x - 1));\n" }, { "answer_id": 108338, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 3, "selected": false, "text": "bool is_power_of_2(int i) {\n if ( i <= 0 ) {\n return 0;\n }\n return ! (i & (i-1));\n}\n" }, { "answer_id": 108340, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 6, "selected": false, "text": "1: 0001\n2: 0010\n4: 0100\n8: 1000\n 10000000\n bool is_power_of_2(int x) {\n return x > 0 && !(x & (x−1));\n}\n" }, { "answer_id": 108345, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 1, "selected": false, "text": "bool is_power_of_2(int n)\n int bitCounter=0;\n while(n) {\n if ((n & 1) == 1) {\n ++bitCounter;\n }\n n >>= 1;\n }\n return (bitCounter == 1);\n}\n" }, { "answer_id": 108360, "author": "Anonymous", "author_id": 19650, "author_profile": "https://Stackoverflow.com/users/19650", "pm_score": 8, "selected": false, "text": "(n & (n - 1)) == 0" }, { "answer_id": 14657714, "author": "Jesse Roberge", "author_id": 2034341, "author_profile": "https://Stackoverflow.com/users/2034341", "pm_score": -1, "selected": false, "text": "SELECT CASE WHEN @X>0 AND (@X) & (@X-1)=0 THEN 1 ELSE 0 END AS IsPowerOfTwo\n" }, { "answer_id": 16198046, "author": "Chethan", "author_id": 377762, "author_profile": "https://Stackoverflow.com/users/377762", "pm_score": 0, "selected": false, "text": "| & bool is_power_of_2(int x) {\n return x > 0 && (x<<1 == (x|(x-1)) +1));\n}\n" }, { "answer_id": 32565217, "author": "Jay Ponkia", "author_id": 3189385, "author_profile": "https://Stackoverflow.com/users/3189385", "pm_score": -1, "selected": false, "text": "int IsPowOf2(int z) {\ndouble x=log2(z);\nint y=x;\nif (x==(double)y)\nreturn 1;\nelse\nreturn 0;\n}\n" }, { "answer_id": 33083952, "author": "Margus", "author_id": 97754, "author_profile": "https://Stackoverflow.com/users/97754", "pm_score": 2, "selected": false, "text": "int isPowerOfTwo(unsigned int x)\n{\n return x && !(x & (x – 1));\n}\n int isPowerOfTwo(unsigned int x)\n{\n return !(x & (x – 1));\n}\n" }, { "answer_id": 39602456, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 1, "selected": false, "text": "bool IsPowerOf2_32(uint32_t x)\n{\n#if __BMI__ || ((_MSC_VER >= 1900) && defined(__AVX2__))\n return !!((x > 0) && _blsr_u32(x));\n#endif\n // Fallback to C/C++ code\n}\n\nbool IsPowerOf2_64(uint64_t x)\n{\n#if __BMI__ || ((_MSC_VER >= 1900) && defined(__AVX2__))\n return !!((x > 0) && _blsr_u64(x));\n#endif\n // Fallback to C/C++ code\n}\n __BMI__ _blsr_u64 _LP64_ #if defined(__GNUC__) && defined(__BMI__)\n# if defined(__clang__)\n# ifndef _tzcnt_u32\n# define _tzcnt_u32(x) __tzcnt_u32(x)\n# endif\n# ifndef _blsr_u32\n# define _blsr_u32(x) __blsr_u32(x)\n# endif\n# ifdef __x86_64__\n# ifndef _tzcnt_u64\n# define _tzcnt_u64(x) __tzcnt_u64(x)\n# endif\n# ifndef _blsr_u64\n# define _blsr_u64(x) __blsr_u64(x)\n# endif\n# endif // x86_64\n# endif // Clang\n#endif // GNUC and BMI\n" }, { "answer_id": 40073700, "author": "Yuxiang Zhang", "author_id": 7011475, "author_profile": "https://Stackoverflow.com/users/7011475", "pm_score": 2, "selected": false, "text": "return n > 0 && 0 == (1 << 30) % n;\n" }, { "answer_id": 55259357, "author": "F10PPY", "author_id": 4739686, "author_profile": "https://Stackoverflow.com/users/4739686", "pm_score": 3, "selected": false, "text": "if(1==__builtin_popcount(n))\n" }, { "answer_id": 56312164, "author": "Rakete1111", "author_id": 3980929, "author_profile": "https://Stackoverflow.com/users/3980929", "pm_score": 4, "selected": false, "text": "std::has_single_bit #include <bit>\nstatic_assert(std::has_single_bit(16));\nstatic_assert(!std::has_single_bit(15));\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19641/" ]
108,320
<p>What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?</p>
[ { "answer_id": 108349, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 2, "selected": false, "text": "ViewPage<Model>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ]
108,346
<p>Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version.</p> <p>I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?</p>
[ { "answer_id": 108378, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": true, "text": "Try\n Assembly.Load(\"System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139\");\nCatch ex As FileNotFoundException\n //do something here\nEnd Try\n" }, { "answer_id": 108457, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "System.Activator.CreateInstance FileNotFoundException FileLoadException BadImageFormatException TypeLoadException MissingMethodException MissingMemberException MissingFieldException" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19638/" ]
108,387
<p>What are some good ways to do this? Is it even possible to do cleanly? </p> <p>Ideally I'd like to use packet headers to decide which server should handle requests. However, if there is an easier/better way let me know.</p>
[ { "answer_id": 108397, "author": "Micky McQuade", "author_id": 12908, "author_profile": "https://Stackoverflow.com/users/12908", "pm_score": 5, "selected": false, "text": "httpcfg.exe net stop http /y httpcfg set iplisten -i 192.168.1.253 httpcfg query iplisten net start w3svc" }, { "answer_id": 121472, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "ProxyPass /winapp http://127.0.0.1:8080/somedir/\n\nProxyPassReverse /winapp http://127.0.0.1:8080/somedir/\n <a href=../pics/mypic.jpg\">\n <a href=\"http://myinternalhostname/somedir/crappydesign.jpg\">\n" }, { "answer_id": 8721605, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 4, "selected": false, "text": "80 8080 mod_proxy mod_proxy_http <VirtualHost *:80>\n ServerName foo.bar\n ServerAlias *\n ProxyPreserveHost On\n ProxyPass / http://127.0.0.1:8080/\n</VirtualHost>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
108,389
<pre><code>class MyContainedClass { }; class MyClass { public: MyContainedClass * getElement() { // ... std::list&lt;MyContainedClass&gt;::iterator it = ... // retrieve somehow return &amp;(*it); } // other methods private: std::list&lt;MyContainedClass&gt; m_contained; }; </code></pre> <p>Though msdn says <code>std::list</code> should not perform relocations of elements on deletion or insertion, is it a good and common way to return pointer to a list element?</p> <p>PS: I know that I can use collection of pointers (and will have to <code>delete</code> elements in destructor), collection of shared pointers (which I don't like), etc.</p>
[ { "answer_id": 108467, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "const setElement const MyContainedClass * getElement() const {\n // ...\n std::list<MyContainedClass>::const_iterator it = ... // retrieve somehow\n return &(*it);\n }\n const MyContainedClass & getElement() const {\n // ...\n std::list<MyContainedClass>::const_iterator it = ... // retrieve somehow\n return *it;\n }\n std::list<MyContainedClass>::const_iterator getElement() const {\n // ...\n std::list<MyContainedClass>::const_iterator it = ... // retrieve somehow\n return it;\n }\n" }, { "answer_id": 108494, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 0, "selected": false, "text": " const MyContainedClass * getElement() const {\n // ...\n std::list<MyContainedClass>::const_iterator it = ... // retrieve somehow\n return &(*it);\n }\n const MyContainedClass& getElement() const {\n // ...\n std::list<MyContainedClass>::const_iterator it = ... // retrieve somehow\n return *it;\n }\n" }, { "answer_id": 108790, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "MyClass typedef std::list<MyContainedClass> MyClass MyClass MyClass Document NewParagraph() DeleteParagraph() GetParagraph() std::list std::list Document Paragraph Paragraph ParagraphSelectionDialog Paragraph Document Document Document ParagraphSelectionDialog Paragraph Paragraph Paragraph Document Paragraph std::list Paragraph Document Document" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
108,396
<p>I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. </p> <pre><code>public class Person { public Person() { GroupsOwned = new List&lt;Groups&gt;(); } public virtual IList&lt;Groups&gt; GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List&lt;Person&gt;(); } public virtual IList&lt;Person&gt; Admins{ get; set; } } </code></pre> <p>With the mapping looking like this</p> <p>Person: ...</p> <pre><code>HasManyToMany&lt;Groups&gt;(x =&gt; x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); </code></pre> <p>Groups: ...</p> <pre><code> HasManyToMany&lt;Person&gt;(x =&gt; x.Admins) .WithTableName("GroupAdministrators") .WithParentKeyColumn("GroupID") .WithChildKeyColumn("PersonID") .Cascade.SaveUpdate(); </code></pre> <p>When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. </p> <p>Thanks for any advice you may have.</p>
[ { "answer_id": 108864, "author": "emeryc", "author_id": 3900, "author_profile": "https://Stackoverflow.com/users/3900", "pm_score": 0, "selected": false, "text": "Context hibContext //Built here\nTransaction hibTrans //build and start the transaction.\n\nPerson p1 = new Person()\nGroups g1 = new Groups()\n\np1.getGroupsOwned().add(g1)\ng1.getAdmins().add(p1)\n\nhibTrans.commit();\nhibContext.close();\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
108,399
<p>I'm looking for embedded database engine supporting <a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="nofollow noreferrer">isolating storage</a>. Currently I'm aware of VistaDB. What else you can recommend?</p> <p>Requirements are pretty simple:</p> <ul> <li>xcopy deployment </li> <li>support for isolated storage</li> <li>preferably free</li> </ul> <p>Note that you don't know exact path to the file when using IS.</p>
[ { "answer_id": 152769, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "uSQLstPoll() uSQLst" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
108,403
<p>Assume a table structure of <code>MyTable(KEY, datafield1, datafield2...)</code>.</p> <p>Often I want to either update an existing record, or insert a new record if it doesn't exist.</p> <p>Essentially:</p> <pre><code>IF (key exists) run update command ELSE run insert command </code></pre> <p>What's the best performing way to write this?</p>
[ { "answer_id": 108410, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 6, "selected": false, "text": "IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)\nUPDATE [Table] SET propertyOne = propOne, property2 . . .\nELSE\nINSERT INTO [Table] (propOne, propTwo . . .)\n" }, { "answer_id": 108420, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 10, "selected": true, "text": "begin tran\nif exists (select * from table with (updlock,serializable) where key = @key)\nbegin\n update table set ...\n where key = @key\nend\nelse\nbegin\n insert into table (key, ...)\n values (@key, ...)\nend\ncommit tran\n begin tran\n update table with (serializable) set ...\n where key = @key\n\n if @@rowcount = 0\n begin\n insert into table (key, ...) values (@key,..)\n end\ncommit tran\n" }, { "answer_id": 108425, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": -1, "selected": false, "text": "DECLARE @RowExists bit\nSET @RowExists = 0\nUPDATE MyTable SET DataField1 = 'xxx', @RowExists = 1 WHERE Key = 123\nIF @RowExists = 0\n INSERT INTO MyTable (Key, DataField1) VALUES (123, 'xxx')\n" }, { "answer_id": 108540, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 5, "selected": false, "text": "MERGE INTO table_name WITH (HOLDLOCK) USING table_name ON (condition)\nWHEN MATCHED THEN UPDATE SET column1 = value1 [, column2 = value2 ...]\nWHEN NOT MATCHED THEN INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])\n" }, { "answer_id": 243670, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 9, "selected": false, "text": "merge merge tablename with(HOLDLOCK) as target\nusing (values ('new value', 'different value'))\n as source (field1, field2)\n on target.idfield = 7\nwhen matched then\n update\n set field1 = source.field1,\n field2 = source.field2,\n ...\nwhen not matched then\n insert ( idfield, field1, field2, ... )\n values ( 7, source.field1, source.field2, ... )\n" }, { "answer_id": 2107205, "author": "user243131", "author_id": 243131, "author_profile": "https://Stackoverflow.com/users/243131", "pm_score": 4, "selected": false, "text": "ALTER PROCEDURE dbo.Merge_Foo2\n @ID int\nAS\n\nSET NOCOUNT, XACT_ABORT ON;\n\nMERGE dbo.Foo2 WITH (HOLDLOCK) AS f\nUSING (SELECT @ID AS ID) AS new_foo\n ON f.ID = new_foo.ID\nWHEN MATCHED THEN\n UPDATE\n SET f.UpdateSpid = @@SPID,\n UpdateTime = SYSDATETIME()\nWHEN NOT MATCHED THEN\n INSERT\n (\n ID,\n InsertSpid,\n InsertTime\n )\n VALUES\n (\n new_foo.ID,\n @@SPID,\n SYSDATETIME()\n );\n\nRETURN @@ERROR;\n" }, { "answer_id": 7186101, "author": "Kristen", "author_id": 65703, "author_profile": "https://Stackoverflow.com/users/65703", "pm_score": 2, "selected": false, "text": "INSERT INTO MyTable (Key, FieldA)\n SELECT @Key, @FieldA\n WHERE NOT EXISTS\n (\n SELECT *\n FROM MyTable\n WHERE Key = @Key\n )\nIF @@ROWCOUNT = 0\nBEGIN\n UPDATE MyTable\n SET FieldA=@FieldA\n WHERE Key=@Key\n IF @@ROWCOUNT = 0\n ... record was deleted, consider looping to re-run the INSERT, or RAISERROR ...\nEND\n" }, { "answer_id": 11931778, "author": "Victor Sanchez", "author_id": 192389, "author_profile": "https://Stackoverflow.com/users/192389", "pm_score": 0, "selected": false, "text": " BEGIN TRAN\n\n UPDATE table\n SET Id = @ID, Description = @Description\n WHERE Id = @Id\n\n INSERT INTO table(Id, Description)\n SELECT @Id, @Description\n WHERE NOT EXISTS (SELECT NULL FROM table WHERE Id = @Id)\n\n COMMIT TRAN\n" }, { "answer_id": 21209295, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 7, "selected": false, "text": "MERGE BEGIN TRANSACTION;\n\nUPDATE dbo.table WITH (UPDLOCK, SERIALIZABLE) \n SET ... WHERE PK = @PK;\n\nIF @@ROWCOUNT = 0\nBEGIN\n INSERT dbo.table(PK, ...) SELECT @PK, ...;\nEND\n\nCOMMIT TRANSACTION;\n SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n\nBEGIN TRANSACTION;\n\nIF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)\nBEGIN\n UPDATE ...\nEND\nELSE\nBEGIN\n INSERT ...\nEND\nCOMMIT TRANSACTION;\n BEGIN TRY\n INSERT ...\nEND TRY\nBEGIN CATCH\n IF ERROR_NUMBER() = 2627\n UPDATE ...\nEND CATCH\n" }, { "answer_id": 26612200, "author": "Denver", "author_id": 4190548, "author_profile": "https://Stackoverflow.com/users/4190548", "pm_score": 3, "selected": false, "text": "/*\nCREATE TABLE ApplicationsDesSocietes (\n id INT IDENTITY(0,1) NOT NULL,\n applicationId INT NOT NULL,\n societeId INT NOT NULL,\n suppression BIT NULL,\n CONSTRAINT PK_APPLICATIONSDESSOCIETES PRIMARY KEY (id)\n)\nGO\n--*/\n\nDECLARE @applicationId INT = 81, @societeId INT = 43, @suppression BIT = 0\n\nMERGE dbo.ApplicationsDesSocietes WITH (HOLDLOCK) AS target\n--set the SOURCE table one row\nUSING (VALUES (@applicationId, @societeId, @suppression))\n AS source (applicationId, societeId, suppression)\n --here goes the ON join condition\n ON target.applicationId = source.applicationId and target.societeId = source.societeId\nWHEN MATCHED THEN\n UPDATE\n --place your list of SET here\n SET target.suppression = source.suppression\nWHEN NOT MATCHED THEN\n --insert a new line with the SOURCE table one row\n INSERT (applicationId, societeId, suppression)\n VALUES (source.applicationId, source.societeId, source.suppression);\nGO\n" }, { "answer_id": 31206622, "author": "Dev", "author_id": 5077561, "author_profile": "https://Stackoverflow.com/users/5077561", "pm_score": 1, "selected": false, "text": "begin tran\nif exists (select * from table with (updlock,serializable) where key = @key)\nbegin\n update table set ...\n where key = @key\nend\nelse\nbegin\n insert table (key, ...)\n values (@key, ...)\nend\ncommit tran\n" }, { "answer_id": 33588589, "author": "Saleh Najar", "author_id": 5537967, "author_profile": "https://Stackoverflow.com/users/5537967", "pm_score": 3, "selected": false, "text": "UPDATE <tableName> SET <field>=@field WHERE key=@key;\n\nIF @@ROWCOUNT = 0\nBEGIN\n INSERT INTO <tableName> (field)\n SELECT @field\n WHERE NOT EXISTS (select * from tableName where key = @key);\nEND\n" }, { "answer_id": 40005414, "author": "Daniel Acosta", "author_id": 7009558, "author_profile": "https://Stackoverflow.com/users/7009558", "pm_score": 3, "selected": false, "text": "MERGE MERGE INTO Employee AS e\nusing EmployeeUpdate AS eu\nON e.EmployeeID = eu.EmployeeID`\n" }, { "answer_id": 63689042, "author": "Nenad", "author_id": 186822, "author_profile": "https://Stackoverflow.com/users/186822", "pm_score": 0, "selected": false, "text": "REPEATABLE READ SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nBEGIN TRANSACTION\n\n IF (EXISTS (SELECT * FROM myTable WHERE key=@key)\n UPDATE myTable SET ...\n WHERE key=@key\n ELSE\n INSERT INTO myTable (key, ...)\n VALUES (@key, ...)\n\nCOMMIT TRANSACTION\n WHERE key=@key WHERE key=@key2" }, { "answer_id": 72134891, "author": "Jay", "author_id": 17137922, "author_profile": "https://Stackoverflow.com/users/17137922", "pm_score": -1, "selected": false, "text": "INSERT INTO tableName (...) VALUES (...) \nON DUPLICATE KEY \nUPDATE ...\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
108,405
<p>It's really annoying that visual studio hides typos in aspx pages (not the code behind). If the compiler would compile them, I would get a compile error.</p>
[ { "answer_id": 8825115, "author": "Alex Rouillard", "author_id": 274879, "author_profile": "https://Stackoverflow.com/users/274879", "pm_score": 4, "selected": false, "text": "%windir%\\Microsoft.NET\\Framework64\\v4.0.30319\\aspnet_compiler.exe -v / -p \"$(SolutionDir)$(ProjectName)\"\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376/" ]
108,439
<p>I'm looking to get the result of a command as a variable in a Windows batch script (see <a href="https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash#58214">how to get the result of a command in bash</a> for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome. </p>
[ { "answer_id": 108465, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": false, "text": "SET /P Set /P\n _MyVar=<MyFilename.txt _MyVar MyFilename.txt myCmd > tmp.txt set\n /P myVar=<tmp.txt" }, { "answer_id": 108480, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "FOR /F %I IN ('DIR *.* /O:D /B') DO SET V=%I\n FOR /F %%I IN ('DIR *.* /O:D /B') DO SET V=%%I\n" }, { "answer_id": 108511, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 7, "selected": false, "text": "D:\\> FOR /F \"delims=\" %i IN ('date /t') DO set today=%i\nD:\\> echo %today%\nSat 20/09/2008\n \"delims=\" REM NB:in a batch file, need to use %%i not %i\nsetlocal EnableDelayedExpansion\nSET lf=-\nFOR /F \"delims=\" %%i IN ('dir \\ /b') DO if (\"!out!\"==\"\") (set out=%%i) else (set out=!out!%lf%%%i)\nECHO %out%\n ^| FOR /F \"delims=\" %%i IN ('svn info . ^| findstr \"Root:\"') DO set \"URL=%%i\"\n" }, { "answer_id": 108515, "author": "Evil Activity", "author_id": 15520, "author_profile": "https://Stackoverflow.com/users/15520", "pm_score": 5, "selected": false, "text": "CD > tmpFile\nSET /p myvar= < tmpFile\nDEL tmpFile\necho test: %myvar%\n @echo off\n\nrem ---------\nrem Obtain line numbers from the file\nrem ---------\n\nrem This is the file that is being read: You can replace this with %1 for dynamic behaviour or replace it with some command like the first example i gave with the 'CD' command.\nset _readfile=test.txt\n\nfor /f \"usebackq tokens=2 delims=:\" %%a in (`find /c /v \"\" %_readfile%`) do set _max=%%a\nset /a _max+=1\nset _i=0\nset _filename=temp.dat\n\nrem ---------\nrem Make the list\nrem ---------\n\n:makeList\nfind /n /v \"\" %_readfile% >%_filename%\n\nrem ---------\nrem Read the list\nrem ---------\n\n:readList\nif %_i%==%_max% goto printList\n\nrem ---------\nrem Read the lines into the array\nrem ---------\nfor /f \"usebackq delims=] tokens=2\" %%a in (`findstr /r \"\\[%_i%]\" %_filename%`) do set _data%_i%=%%a\nset /a _i+=1\ngoto readList\n\n:printList\ndel %_filename%\nset _i=1\n:printMore\nif %_i%==%_max% goto finished\nset _data%_i%\nset /a _i+=1\ngoto printMore\n\n:finished\n" }, { "answer_id": 108615, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 6, "selected": true, "text": "@ECHO OFF\nIF NOT \"%1\"==\"\" GOTO ADDV\nSET VAR=\nFOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I\nSET VAR\nGOTO END\n\n:ADDV\nSET VAR=%VAR%!%1\n\n:END\n @ECHO off\n@SET MY_VAR=\nFOR /F %%I IN ('npm prefix') DO @SET \"MY_VAR=%%I\"\n\n@REM Do something with MY_VAR variable...\n" }, { "answer_id": 108656, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 1, "selected": false, "text": "@echo off\nsetlocal EnableDelayedExpansion\nfor /f \"delims=\" %%i in ('dir /b') do (\n if \"!DIR!\"==\"\" (set DIR=%%i) else (set DIR=!DIR!#%%i)\n)\necho directory contains:\necho %DIR%\n @echo off\nsetlocal EnableDelayedExpansion\nset count=0\nfor /f \"delims=\" %%i in ('dir /b') do (\n if \"!DIR!\"==\"\" (set DIR=%%i) else (set DIR=!DIR!#%%i)\n set /a count = !count! + 1\n)\n\necho directory contains:\necho %DIR%\n\nfor /l %%c in (1,1,%count%) do (\n for /f \"delims=#\" %%i in (\"!DIR!\") do (\n echo %%i\n set DIR=!DIR:%%i=!\n )\n)\n" }, { "answer_id": 108716, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": false, "text": "@echo off\nif not \"%1\"==\"\" goto get_basename_pwd\nfor /f \"delims=X\" %%i in ('cd') do call %0 %%i\nfor /f \"delims=X\" %%i in ('dir /o:d /b') do echo %%i>>%filename%.txt\ngoto end\n\n:get_basename_pwd\nset filename=%~n1\n\n:end\n" }, { "answer_id": 12755627, "author": "Hike", "author_id": 1724296, "author_profile": "https://Stackoverflow.com/users/1724296", "pm_score": 2, "selected": false, "text": "@echo off\n\nver | find \"6.1.\" > nul\nif %ERRORLEVEL% == 0 (\necho Win7\nfor /f \"delims=\" %%a in ('DIR \"C:\\Program Files\\Microsoft Office\\*Outlook.EXE\" /B /P /S') do call set findoutlook=%%a\n%findoutlook%\n)\n\nver | find \"5.1.\" > nul\nif %ERRORLEVEL% == 0 (\necho WinXP\nfor /f \"delims=\" %%a in ('DIR \"C:\\Program Files\\Microsoft Office\\*Outlook.EXE\" /B /P /S') do call set findoutlook=%%a\n%findoutlook%\n)\necho Outlook dir: %findoutlook%\n\"%findoutlook%\"\n" }, { "answer_id": 23385707, "author": "Raceableability", "author_id": 3568856, "author_profile": "https://Stackoverflow.com/users/3568856", "pm_score": 2, "selected": false, "text": "FOR for /F \"delims=\" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)\n %%I %%I %%I" }, { "answer_id": 48305783, "author": "Gilles Maisonneuve", "author_id": 3676932, "author_profile": "https://Stackoverflow.com/users/3676932", "pm_score": 2, "selected": false, "text": "$ for /f \"tokens=* USEBACKQ\" %f in (\n `\"\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" Hello '\"F:\\GLW7\\Distrib\\System\\Shells and scripting\"'`\n) do echo %f\nThe filename, directory name, or volume label syntax is incorrect.\n $ for /f \"tokens=* USEBACKQ\" %f in (\n `\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\" \"Hello World\" \"F:\\GLW7\\Distrib\\System\\Shells and scripting\"`\n) do echo %f\n'F:\\GLW7\\Distrib\\System\\Shells' is not recognized as an internal or external command, operable program or batch file.\n `$ for /f \"tokens=* USEBACKQ\" %f in (\n `\"\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" \"Hello World\" \"F:\\GLW7\\Distrib\\System\\Shells and scripting\"`\n) do echo %f\n'\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" \"Hello' is not recognized as an internal or external command, operable program or batch file.\n pushd \"%~d0%~p0\"\nFOR /F \"tokens=* USEBACKQ\" %%F IN (\n `FOLDERBROWSE \"Hello world!\" \"F:\\GLW7\\Distrib\\System\\Layouts (print,display...)\"`\n) DO (SET MyFolder=%%F)\npopd\necho My selected folder: %MyFolder%\n My selected folder: F:\\GLW7\\Distrib\\System\\OS install, recovery, VM\\\nPress any key to continue . . .\n" }, { "answer_id": 54670814, "author": "ivan rc", "author_id": 10806969, "author_profile": "https://Stackoverflow.com/users/10806969", "pm_score": 1, "selected": false, "text": "@echo off\nsetlocal EnableDelayedExpansion\nFOR /F \"tokens=1 delims= \" %%i IN ('echo hola') DO (\n set TXT=%%i\n)\necho 'TXT: %TXT%'\n" }, { "answer_id": 55245989, "author": "Hayz", "author_id": 11085919, "author_profile": "https://Stackoverflow.com/users/11085919", "pm_score": 0, "selected": false, "text": "for @echo off\nrem Commands go here\nexit /b\n:output\nfor /f \"tokens=* useback\" %%a in (`%~1`) do set \"output=%%a\"\n call :output \"Command goes here\" %output% set" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535/" ]
108,443
<p>I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this?</p> <p>Should I use structs to link the structure into a program flow. Are objects better?</p> <pre><code>struct asm_code { int type; int value; int optimized; asm_code *next_to_execute; } asm_imp; </code></pre> <p>Update: I think it will turn out, like a linked list.</p> <p>Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves.</p> <p>Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished?</p>
[ { "answer_id": 108493, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "unsigned int isqrt32 (unsigned int value) \n{\n unsigned int g = 0;\n unsigned int bshift = 15;\n unsigned int b = 1<<bshift;\n do {\n unsigned int temp = (g+g+b)<<bshift;\n if (value >= temp) {\n g += b;\n value -= temp;\n }\n b>>=1;\n } while (bshift--);\n return g;\n}\n define i32 @isqrt32(i32 %value) nounwind {\nentry:\n br label %bb\n\nbb: ; preds = %bb, %entry\n %indvar = phi i32 [ 0, %entry ], [ %indvar.next, %bb ] \n %b.0 = phi i32 [ 32768, %entry ], [ %tmp23, %bb ]\n %g.1 = phi i32 [ 0, %entry ], [ %g.0, %bb ] \n %value_addr.1 = phi i32 [ %value, %entry ], [ %value_addr.0, %bb ] \n %bshift.0 = sub i32 15, %indvar \n %tmp5 = shl i32 %g.1, 1 \n %tmp7 = add i32 %tmp5, %b.0 \n %tmp9 = shl i32 %tmp7, %bshift.0 \n %tmp12 = icmp ult i32 %value_addr.1, %tmp9 \n %tmp17 = select i1 %tmp12, i32 0, i32 %b.0 \n %g.0 = add i32 %tmp17, %g.1 \n %tmp20 = select i1 %tmp12, i32 0, i32 %tmp9 \n %value_addr.0 = sub i32 %value_addr.1, %tmp20 \n %tmp23 = lshr i32 %b.0, 1 \n %indvar.next = add i32 %indvar, 1 \n %exitcond = icmp eq i32 %indvar.next, 16 \n br i1 %exitcond, label %bb30, label %bb\n\nbb30: ; preds = %bb\n ret i32 %g.0\n}\n typedef void (* voidfunc) (void);\n\nvoid * generate_code (void)\n{\n // reserve some space\n unsigned char * buffer = (unsigned char *) malloc (1024);\n\n\n // write a single RET-instruction\n buffer[0] = 0xc3; \n\n return buffer;\n}\n\nint main (int argc, char **args)\n{\n // generate some code:\n voidfunc func = (voidfunc) generate_code();\n\n // flush instruction cache:\n FlushInstructionCache(GetCurrentProcess(), func, 1024);\n\n // execute the code (it does nothing atm)\n func();\n\n // free memory and exit.\n free (func);\n}\n" }, { "answer_id": 108510, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "struct asm_code {\n asm_code()\n : type(0), value(0), optimized(0) {}\n\n asm_code(int type_, int value_, int optimized_)\n : type(type_), value(value_), optimized(_optimized) {}\n\n int type;\n int value;\n int optimized;\n };\n struct asm_code {\n\n int getType() { return type ; }\n void setType(int type_) { VERIFY_TYPE(type_) ; type = type_ ; }\n\n // Etc.\n\n private :\n int type;\n int value;\n int optimized;\n };\n" }, { "answer_id": 108578, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 1, "selected": false, "text": "add r1, r2, <int>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
108,461
<p>I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible.</p>
[ { "answer_id": 108496, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 4, "selected": true, "text": "<a href=\"#\">Text <img class=\"popup\" src=\"pic.gif\" /></a>\n a img.popup { display: none }\n a:hover img.popup { display: block }\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18748/" ]
108,523
<p>I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?</p> <p>Class code here:</p> <pre><code>class Enum(object): '''Simple Enum Class Example Usage: &gt;&gt;&gt; codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) </code></pre>
[ { "answer_id": 108549, "author": "tsg", "author_id": 15685, "author_profile": "https://Stackoverflow.com/users/15685", "pm_score": 2, "selected": false, "text": "(FOO, BAR, BAZ) = range(3)\n" }, { "answer_id": 108556, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": false, "text": "FOO_BAR = 'FOO_BAR'\nFOO_BAZ = 'FOO_BAZ'\nFOO_QUX = 'FOO_QUX'\n if something is FOO_BAR: pass # do something here\nelif something is FOO_BAZ: pass # do something else\nelif something is FOO_QUX: pass # do something else\nelse: raise Exception('Invalid value for something')\n is == your_module.FOO_BAR 'FOO_BAR' is FOO_BAZ 2 split()" }, { "answer_id": 108816, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "class DoTheNeedful( object ):\n ONE_CHOICE = 1\n ANOTHER_CHOICE = 2 \n YET_ANOTHER = 99\n def __init__( self, aSelection ):\n assert aSelection in ( self.ONE_CHOICE, self.ANOTHER_CHOICE, self.YET_ANOTHER )\n self.selection= aSelection\n dtn = DoTheNeeful( DoTheNeeful.ONE_CHOICE )\n" }, { "answer_id": 674652, "author": "Spell", "author_id": 7185, "author_profile": "https://Stackoverflow.com/users/7185", "pm_score": 1, "selected": false, "text": "class enumSeason():\n Spring = 0\n Summer = 1\n Fall = 2\n Winter = 3\n def __init__(self, Type):\n self.value = Type\n def __str__(self):\n if self.value == enumSeason.Spring:\n return 'Spring'\n if self.value == enumSeason.Summer:\n return 'Summer'\n if self.value == enumSeason.Fall:\n return 'Fall'\n if self.value == enumSeason.Winter:\n return 'Winter'\n def __eq__(self,y):\n return self.value==y.value\n >>> x = enumSeason(enumSeason.Spring)\n >>> print(x)\n Spring\n >>> y = enumSeason(enumSeason.Spring)\n >>> x == y\n True\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9127/" ]
108,558
<p>Can a cookie be shared between two sites on the same top level domain? Say <code>www.example.com</code> and <code>secure.example.com</code> ? We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain. What parameters does the cookie need? I'm using asp.net</p>
[ { "answer_id": 108569, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 6, "selected": true, "text": "Response.Cookies(\"UID\").Domain = \".myserver.com\"\n" }, { "answer_id": 108681, "author": "Jess Chadwick", "author_id": 13960, "author_profile": "https://Stackoverflow.com/users/13960", "pm_score": 3, "selected": false, "text": "<forms cookieDomain=\"example.com\">\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
108,567
<p>I have a SVN structure like this:</p> <pre><code>/Projects /Project1 /Project2 /someFolder /Project3 /Project4 </code></pre> <p>I would like to move all the projects into the /Projects folder, which means I want to move Projects 3 and 4 from /someFolder into the /projects folder.</p> <p>The caveat: I'd like to keep the full history. I assume that every client would have to check out the stuff from the new location again, which is fine, but I still wonder what the simplest approach is to move directories without completely destroying the history?</p> <p>Subversion 1.5 if that matters.</p>
[ { "answer_id": 108583, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 7, "selected": true, "text": "svn help rename\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
108,586
<p>Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... </p> <pre><code>A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } </code></pre> <p>I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': a, c, d, e, g, f, b</p> <p>So, right now (a non-generator solution):</p> <pre><code>def get_all(D,k): L = [] def get2(D,k): L.append(k) for ii in D.get(k,[]): get2(D, ii) get2(D,k) return L </code></pre> <p>Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.</p>
[ { "answer_id": 108606, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 3, "selected": true, "text": "#!/usr/bin/env python\n\ndef get_all(D, k):\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii):\n yield jj\n\nA = { 'a' : dict(b=1, c=1),\n 'c' : dict(d=1),\n 'd' : dict(e=1,f=1,g=1),\n 'h' : dict(j=1)\n }\n\nfor ii in get_all(A,'a'):\n print ii\n" }, { "answer_id": 108852, "author": "HenryR", "author_id": 2827, "author_profile": "https://Stackoverflow.com/users/2827", "pm_score": 3, "selected": false, "text": "\na\nc\nd\ne\ng\nf\nb\nd\ne\ng\nf\n def get_all(D, k, seen=None):\n if not seen:\n seen = set( )\n if k not in seen:\n seen.add(k)\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii, seen):\n yield jj\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
108,598
<p>Considering the following architecture:</p> <ul> <li>a base object 'Entity'</li> <li>a derived object 'Entry:Base'</li> <li>and a further derived object 'CancelledEntry:Entry'</li> </ul> <p>In EntitySQL I can write the following: </p> <pre><code>[...] where it is of (only MyEntities.Entry) [...] </code></pre> <p>to return only objects of type Entry and no Entity or CancelledEntry.</p> <p>In linq to sql, the following command will return objects of type Entry and CancelledEntry. </p> <pre><code>EntityContext.EntitySet.OfType&lt;Entry&gt;() </code></pre> <p>What is the syntax/function to use to return only objects of type Entry?</p>
[ { "answer_id": 108644, "author": "ADB", "author_id": 3610, "author_profile": "https://Stackoverflow.com/users/3610", "pm_score": 1, "selected": false, "text": "EntityContext.EntitySet.OfType<Entry>().Where( obj => !(obj is CancelledEntry) )\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610/" ]
108,650
<p>I'm struggling with a problem with the Script.aculo.us Autocompleter control in IE (I've tried it in IE6 &amp; 7). The suggestions fail to appear for the first character is entered into the text box after the page has been loaded. After that initial failure, the control works as it should.</p> <p>I've verified that the suggestions data is returned from the server correctly; the problem appears to have something to do with the positioning of the suggestions element, as other relatively positioned elements on the page move out of position at the moment that you'd expect the suggestions to appear.</p> <p>Has anyone heard of such a problem or have any suggestions on how to fix it?</p> <p>Edit: In response to Chris, I have set the partialChars parameter to 1 and the control works in all the other browsers I've tried, which are the latest versions of Firefox, Safari, Opera, and Chrome. I should probably have made that clear in the first place. Thanks.</p>
[ { "answer_id": 120572, "author": "Nick Higgs", "author_id": 3187, "author_profile": "https://Stackoverflow.com/users/3187", "pm_score": 1, "selected": false, "text": "new Ajax.Autocompleter(textInputId, suggestionsHolderId, suggestionsUrl, params);\n\n//Hack\nEvent.observe(window, 'load', function()\n{\n try\n {\n Position.clone($(textInputId), $(suggestionsHolderId),\n { setHeight: false, offsetTop: $(textInputId).offsetHeight});\n }\n catch(e){}\n});\n" }, { "answer_id": 949896, "author": "Giacomo1968", "author_id": 117259, "author_profile": "https://Stackoverflow.com/users/117259", "pm_score": 2, "selected": false, "text": "function positionAuto(element, entry) {\n setTimeout( function() {\n Element.clonePosition('choices_div', 'text_element', {\n 'setWidth': false,\n 'setHeight': false,\n 'offsetTop': $('text_element').offsetHeight\n } );\n }, 300);\n return entry;\n}\n\nnew Ajax.Autocompleter('text_element', 'choices_div', [url to web service], {\n paramName: 'fulltext',\n minChars: 2,\n callback: positionAuto, // See above\n [etc...]\n" }, { "answer_id": 7194731, "author": "Atlantic", "author_id": 912689, "author_profile": "https://Stackoverflow.com/users/912689", "pm_score": 2, "selected": false, "text": "div.acwrap {\n position: absolute;\n height: 40px;\n}\n\ndiv.autocomplete {\n position: relative !important;\n top: -5px !important;\n left: 0px !important;\n width:250px;\n margin:0;\n padding:0;\n}\n <div class=\"acwrap\">\n <div id=\"autocomplete_choices\" class=\"autocomplete\">\n </div>\n</div>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3187/" ]
108,687
<p>I want to create a box shape and I am having trouble. I want the box to have a background color, and then different color inside the box.<br> The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box. Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible.</p> <p>Here is a rough sketch of what I am trying to do:</p> <p><a href="https://i.stack.imgur.com/aZ2W7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aZ2W7.png" alt=""></a></p>
[ { "answer_id": 108708, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "<div class=\"panel\">\n <div>Some other stuff</div>\n <ul>\n <li>Item 1</li>\n <li>Item 2</li>\n </ul>\n</div>\n div.panel { background-color: #A74; border: solid 0.5em #520; width: 10em; \n border-width: 0.75em 0.25em 0.75em 0.25em; }\ndiv.panel div { padding: 2px; height: 4em; }\ndiv.panel ul li { display: block; background-color: white; \n margin: 2px; padding: 1px 4px 1px 4px; }\ndiv.panel ul { margin: 0; padding-left: 0; }\n" }, { "answer_id": 108778, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 4, "selected": true, "text": ".box {\n width: 100px;\n border: solid #884400;\n border-width: 8px 3px 8px 3px;\n background-color: #ccaa77;\n}\n\n.box ul {\n margin: 0px;\n padding: 0px;\n padding-top: 50px; /* presuming the non-list header space at the top of\n your box is desirable */\n}\n\n.box ul li {\n margin: 0px 2px 2px 2px; /* reduce to 1px if you find the separation\n sufficiently visible */\n background-color: #ffffff;\n list-style-type: none;\n padding-left: 2px;\n}\n <div class=\"box\">\n <ul>\n <li>Lorem</li>\n <li>Ipsum</li>\n </ul>\n</div>\n" }, { "answer_id": 675332, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<div id=\"content\">\n <a><div class=\"title\">Title</div>Text</a>\n <ul>\n <li>Text</li>\n <li>More Text...</li>\n </ul>\n </div>\n #content{\n text-align:left;\n width:200px;\n background:#e0c784;\n border-top:solid 10px #7f4200;\n border-bottom:solid 10px #7f4200;\n border-right:solid 5px #7f4200;\n border-left:solid 5px #7f4200;\n }\n #content a{\n margin-left:20px;\n }\n\n #content ul{\n list-style-type:none;\n margin-bottom:0px;\n }\n #content ul li{\n padding-left:20px;\n margin:0px 0px 1px -40px;\n text-align:left;\n width:180px;\n list-style-type:none;\n background-color:white;\n }\n #content .title{\n text-align:center;\n font-weight:bolder;\n text-align:center;\n font-size:20px;\n border-bottom:solid 2px #ffcc99;\n background:#996633;\n color:#ffffff;\n margin-bottom:20px;\n }\n" }, { "answer_id": 5762047, "author": "bryant jaquez", "author_id": 721400, "author_profile": "https://Stackoverflow.com/users/721400", "pm_score": 1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<HTML>\n <HEAD>\n <TITLE>Examples of margins, padding, and borders</TITLE>\n <STYLE type=\"text/css\">\n UL { \n background: yellow; \n margin: 12px 12px 12px 12px;\n padding: 3px 3px 3px 3px;\n /* No borders set */\n }\n LI { \n color: white; /* text color is white */ \n background: blue; /* Content, padding will be blue */\n margin: 12px 12px 12px 12px;\n padding: 12px 0px 12px 12px; /* Note 0px padding right */\n list-style: none /* no glyphs before a list item */\n /* No borders set */\n }\n LI.withborder {\n border-style: dashed;\n border-width: medium; /* sets border width on all sides */\n border-color: lime;\n }\n </STYLE>\n </HEAD>\n <BODY>\n <UL>\n <LI>First element of list\n <LI class=\"withborder\">Second element of list is\n a bit longer to illustrate wrapping.\n </UL>\n </BODY>\n</HTML>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
108,692
<p>There is a well-known debate in Java (and other communities, I'm sure) whether or not trivial getter/setter methods should be tested. Usually, this is with respect to code coverage. Let's agree that this is an open debate, and not try to answer it here.</p> <p>There have been several blog posts on using Java reflection to auto-test such methods.</p> <p>Does any framework (e.g. jUnit) provide such a feature? e.g. An annotation that says "this test T should auto-test all the getters/setters on class C, because I assert that they are standard".</p> <p>It seems to me that it would add value, and if it were configurable, the 'debate' would be left as an option to the user.</p>
[ { "answer_id": 109871, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 4, "selected": true, "text": "assertRefEquals" }, { "answer_id": 114145, "author": "Daniel Fanjul", "author_id": 16135, "author_profile": "https://Stackoverflow.com/users/16135", "pm_score": 0, "selected": false, "text": "interface NamedAndObservable {\n String getName();\n void setName(String name);\n void addPropertyChangeListener(PropertyChangeListener listener);\n void addPropertyChangeListener(String propertyName,\n PropertyChangeListener listener);\n}\n" }, { "answer_id": 5199221, "author": "Franck Valentin", "author_id": 521615, "author_profile": "https://Stackoverflow.com/users/521615", "pm_score": 1, "selected": false, "text": "setters getters hashCode(), equals() and toString()" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12704/" ]
108,699
<p>Is there a good object-relational-mapping library for PHP? </p> <p>I know of <a href="http://www.php.net/manual/en/intro.pdo.php" rel="noreferrer">PDO</a>/ADO, but they seem to only provide abstraction of differences between database vendors not an actual mapping between the domain model and the relational model. I'm looking for a PHP library that functions similarly to the way <a href="http://en.wikipedia.org/wiki/Hibernate_%28Java%29" rel="noreferrer">Hibernate</a> does for Java and NHibernate does for .NET.</p>
[ { "answer_id": 795897, "author": "Olivier Lalonde", "author_id": 96855, "author_profile": "https://Stackoverflow.com/users/96855", "pm_score": 3, "selected": false, "text": "<?php \n$object = $dorm->getClassName('id_here');\n$dorm->save($object);\n$dorm->delete($object);\n" }, { "answer_id": 1678537, "author": "Kurt", "author_id": 203188, "author_profile": "https://Stackoverflow.com/users/203188", "pm_score": 1, "selected": false, "text": "$urun = new Product();\n$urun->name='CPU'\n$urun->prince='124';\n$urun->save();\n" }, { "answer_id": 3382929, "author": "bcosca", "author_id": 336508, "author_profile": "https://Stackoverflow.com/users/336508", "pm_score": 5, "selected": false, "text": "/* SQL */\nCREATE TABLE products (\n product_id INTEGER,\n description VARCHAR(128),\n PRIMARY KEY (product_id)\n);\n\n/* PHP */\n// Create\n$product=new Axon('products'); // Automatically reads the above schema\n$product->product_id=123;\n$product->description='Sofa bed';\n$product->save(); // ORM knows it's a new record\n\n// Retrieve\n$product->load('product_id=123');\necho $product->description;\n\n// Update\n$product->description='A better sofa bed';\n$product->save(); // ORM knows it's an existing record\n\n// Delete\n$product->erase();\n" }, { "answer_id": 7872945, "author": "romaninsh", "author_id": 204819, "author_profile": "https://Stackoverflow.com/users/204819", "pm_score": 2, "selected": false, "text": "$emp=$this->add('Model_Employee');\n$emp['name']='John';\n$emp['salary']=500;\n$emp->save();\n $result = $emp->count()->where('salary','>',400)->getOne();\n $this->add('CRUD')->setModel('Employee');\n" }, { "answer_id": 11575675, "author": "Charlie Chai", "author_id": 1144536, "author_profile": "https://Stackoverflow.com/users/1144536", "pm_score": 2, "selected": false, "text": "include \"NotORM.php\";\n $pdo = new PDO(\"mysql:dbname=software\");\n $db = new NotORM($pdo);\n $applications = $db->application()\n->select(\"id, title\")\n->where(\"web LIKE ?\", \"http://%\")\n->order(\"title\")\n->limit(10)\n;\nforeach ($applications as $id => $application) {\necho \"$application[title]\\n\";\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
108,728
<p>I am redesigning a command line application and am looking for a way to make its use more intuitive. Are there any conventions for the format of parameters passed into a command line application? Or any other method that people have found useful?</p>
[ { "answer_id": 108738, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 0, "selected": false, "text": "YourApp.exe -file %YourProject.prj% -Secure true\n" }, { "answer_id": 108744, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 2, "selected": false, "text": "c:\\>FOO\n\nFOO\n\nUSAGE FOO -{Option}{Value}\n\n-A Do A stuff\n-B Do B stuff\n\nc:\\>\n" }, { "answer_id": 108755, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "myCli.exe describe someThing\nmyCli.exe descr someThing\nmyCli.exe desc someThing\n" }, { "answer_id": 108789, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": " myCli.exe describe someThing\n myCli.exe destroy someThing\n myCli.exe des someThing ???\n" }, { "answer_id": 108791, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 6, "selected": true, "text": "--help -h tar -zxvf filename" }, { "answer_id": 23799547, "author": "Kiquenet", "author_id": 206730, "author_profile": "https://Stackoverflow.com/users/206730", "pm_score": 2, "selected": false, "text": "Install-Package CommandLineParser Install-Package CommandLineParser -pre CommandLine.Parser.Default.ParseArguments(...) HelpText.AutoBuild(...) IList<string> git commit -a // Define a class to receive parsed values\nclass Options {\n [Option('r', \"read\", Required = true,\n HelpText = \"Input file to be processed.\")]\n public string InputFile { get; set; }\n\n [Option('v', \"verbose\", DefaultValue = true,\n HelpText = \"Prints all messages to standard output.\")]\n public bool Verbose { get; set; }\n\n [ParserState]\n public IParserState LastParserState { get; set; }\n\n [HelpOption]\n public string GetUsage() {\n return HelpText.AutoBuild(this,\n (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));\n }\n}\n\n// Consume them\nstatic void Main(string[] args) {\n var options = new Options();\n if (CommandLine.Parser.Default.ParseArguments(args, options)) {\n // Values are available here\n if (options.Verbose) Console.WriteLine(\"Filename: {0}\", options.InputFile);\n }\n}\n" }, { "answer_id": 44124794, "author": "Junior", "author_id": 2510673, "author_profile": "https://Stackoverflow.com/users/2510673", "pm_score": 1, "selected": false, "text": "namespace Example.Initialization.Simple\n{\n using SysCommand.ConsoleApp;\n\n public class Program\n {\n public static int Main(string[] args)\n {\n return App.RunApplication();\n }\n }\n\n // Classes inheriting from `Command` will be automatically found by the system\n // and its public properties and methods will be available for use.\n public class MyCommand : Command\n {\n public void Main(string arg1, int? arg2 = null)\n {\n if (arg1 != null)\n this.App.Console.Write(string.Format(\"Main arg1='{0}'\", arg1));\n if (arg2 != null)\n this.App.Console.Write(string.Format(\"Main arg2='{0}'\", arg2));\n }\n\n public void MyAction(bool a)\n {\n this.App.Console.Write(string.Format(\"MyAction a='{0}'\", a));\n }\n }\n}\n // auto-generate help\n$ my-app.exe help\n\n// method \"Main\" typed\n$ my-app.exe --arg1 value --arg2 1000\n\n// or without \"--arg2\"\n$ my-app.exe --arg1 value\n\n// actions support\n$ my-app.exe my-action -a\n" }, { "answer_id": 45321427, "author": "Gene", "author_id": 3373555, "author_profile": "https://Stackoverflow.com/users/3373555", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing coptions;\n\n[ApplicationInfo(Help = \"This program does something useful.\")]\npublic class Options\n{\n [Flag('s', \"silent\", Help = \"Produce no output.\")]\n public bool Silent;\n\n [Option('n', \"name\", \"NAME\", Help = \"Name of user.\")]\n public string Name\n {\n get { return _name; }\n set { if (String.IsNullOrWhiteSpace(value))\n throw new InvalidOptionValueException(\"Name must not be blank\");\n _name = value;\n }\n }\n private string _name;\n\n [Option(\"size\", Help = \"Size to output.\")]\n public int Size = 3;\n\n [Option('i', \"ignore\", \"FILENAME\", Help = \"Files to ignore.\")]\n public List<string> Ignore;\n\n [Flag('v', \"verbose\", Help = \"Increase the amount of output.\")]\n public int Verbose = 1;\n\n [Value(\"OUT\", Help = \"Output file.\")]\n public string OutputFile;\n\n [Value(\"INPUT\", Help = \"Input files.\")]\n public List<string> InputFiles;\n}\n\nnamespace coptions.ReadmeExample\n{\n class Program\n {\n static int Main(string[] args)\n {\n try\n {\n Options opt = CliParser.Parse<Options>(args);\n\n Console.WriteLine(opt.Silent);\n Console.WriteLine(opt.OutputFile);\n return 0;\n }\n catch (CliParserExit)\n {\n // --help\n return 0;\n\n } catch (Exception e)\n {\n // unknown options etc...\n Console.Error.WriteLine(\"Fatal Error: \" + e.Message);\n return 1;\n }\n }\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064/" ]
108,768
<p>I got a comment to my answer on this thread:</p> <p><a href="https://stackoverflow.com/questions/105477">Malloc inside a function call appears to be getting freed on return?</a></p> <p>In short I had code like this:</p> <pre><code>int * somefunc (void) { int * temp = (int*) malloc (sizeof (int)); temp[0] = 0; return temp; } </code></pre> <p>I got this comment:</p> <blockquote> <p>Can I just say, please don't cast the return value of malloc? It is not required and can hide errors.</p> </blockquote> <p>I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.</p> <p>However, I wonder how casts like this can hide errors. Any ideas?</p> <h1>Edit:</h1> <p>Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.</p>
[ { "answer_id": 108781, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": true, "text": "stdlib.h malloc int TYPE * p;\np = (TYPE *)malloc(n*sizeof(TYPE));\n p TYPe TYPE p = malloc(sizeof(*p)*n); p malloc malloc" }, { "answer_id": 108785, "author": "jbl", "author_id": 2353001, "author_profile": "https://Stackoverflow.com/users/2353001", "pm_score": 0, "selected": false, "text": "int *temp = (int *)malloc(sizeof(double));\n" }, { "answer_id": 108803, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "int int_array[10];\n/* initialize array */\nint *p = &(int_array[3]);\nshort *sp = (short *)p;\nshort my_val = *sp;\n struct {\n /* something */\n} my_struct[100];\n\nint my_int_array[100];\n/* initialize array */\nstruct my_struct *p = &(my_int_array[99]);\n" }, { "answer_id": 108840, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 0, "selected": false, "text": "T1 *p;\np = (T2*) malloc(sizeof(T3));\n" }, { "answer_id": 108979, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "stdlib.h malloc int malloc(); malloc" }, { "answer_id": 108995, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "void * int * malloc_Int(size_t p_iSize) /* number of ints wanted */\n{\n return malloc(sizeof(int) * p_iSize) ;\n}\n template <typename T>\nT * myMalloc(const size_t p_iSize)\n{\n return static_cast<T *>(malloc(sizeof(T) * p_iSize)) ;\n}\n int * p = myMalloc<int>(25) ;\nfree(p) ;\n\nMyStruct * p2 = myMalloc<MyStruct>(12) ;\nfree(p2) ;\n // error: cannot convert ‘int*’ to ‘short int*’ in initialization\nshort * p = myMalloc<int>(25) ;\nfree(p) ;\n extern \"C\" {}" }, { "answer_id": 145050, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "#if CPLUSPLUS\n#define MALLOC_CAST(T) (T)\n#else\n#define MALLOC_CAST(T)\n#endif\n...\nint * p;\np = MALLOC_CAST(int *) malloc(sizeof(int) * n);\n #if CPLUSPLUS\n#define MYMALLOC(T, N) static_cast<T*>(malloc(sizeof(T) * N))\n#else\n#define MYMALLOC(T, N) malloc(sizeof(T) * N)\n#endif\n...\nint * p;\np = MYMALLOC(int, n);\n" }, { "answer_id": 2239357, "author": "Chris Lutz", "author_id": 60777, "author_profile": "https://Stackoverflow.com/users/60777", "pm_score": 1, "selected": false, "text": "stdlib.h sizeof *p int from_f(float f)\n{\n return *(int *)&f;\n}\n int *p = (int *)malloc(sizeof(int) * 10);\n malloc *(int *)&f; new" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
108,807
<p>I have an application where a user has to remember and insert an unix timestamp like 1221931027. In order to make it easier to remember the key I like to reduce the number of characters to insert through allowing the characters [a-z]. So I'm searching for an algorithm to convert the timestamp to a shorter alphanum version and do the same backwards. Any hints?</p>
[ { "answer_id": 108990, "author": "Thom Boyer", "author_id": 19725, "author_profile": "https://Stackoverflow.com/users/19725", "pm_score": 2, "selected": false, "text": "#include <time.h>\n#include <stdio.h>\n\n// tobase36() returns a pointer to static storage which is overwritten by \n// the next call to this function. \n//\n// This implementation presumes ASCII or Latin1.\n\nchar * tobase36(time_t n)\n{\n static char text[32];\n char *ptr = &text[sizeof(text)];\n *--ptr = 0; // NUL terminator\n\n // handle special case of n==0\n if (n==0) {\n *--ptr = '0';\n return ptr;\n }\n\n // some systems don't support negative time values, but some do\n int isNegative = 0;\n if (n < 0)\n {\n isNegative = 1;\n n = -n;\n }\n\n // this loop is the heart of the conversion\n while (n != 0)\n {\n int digit = n % 36;\n n /= 36;\n *--ptr = digit + (digit < 10 ? '0' : 'A'-10);\n }\n\n // insert '-' if needed\n if (isNegative)\n {\n *--ptr = '-';\n }\n\n return ptr;\n}\n\nint main(int argc, const char **argv)\n{\n int i;\n for (i=1; i<argc; ++i)\n {\n long timestamp = atol(argv[i]);\n printf(\"%12d => %8s\\n\", timestamp, tobase36(timestamp));\n }\n}\n\n/*\n$ gcc -o base36 base36.c\n$ ./base36 0 1 -1 10 11 20 30 35 36 71 72 2147483647 -2147483647\n 0 => 0\n 1 => 1\n -1 => -1\n 10 => A\n 11 => B\n 20 => K\n 30 => U\n 35 => Z\n 36 => 10\n 71 => 1Z\n 72 => 20\n 2147483647 => ZIK0ZJ\n -2147483647 => -ZIK0ZJ\n*/\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
108,813
<p>How can I Handler 404 errors without the framework throwing an Exception 500 error code?</p>
[ { "answer_id": 108830, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 5, "selected": true, "text": "routes.MapRoute(\"Error\", \n \"{*url}\", \n new { controller = \"Error\", action = \"Http404\" });\n public ActionResult Http404(string url) {\n Response.StatusCode = 404;\n ViewData[\"url\"] = url;\n return View();\n}\n" }, { "answer_id": 8525665, "author": "Bryan Legend", "author_id": 52771, "author_profile": "https://Stackoverflow.com/users/52771", "pm_score": 0, "selected": false, "text": "public ActionResult Download(string fontName)\n{\n FontCache.InitalizeFonts();\n\n fontName = HttpUtility.UrlDecode(fontName);\n\n var font = FontCache.GetFontByName(fontName);\n if (font == null)\n return HttpNotFound();\n\n return View(font);\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19710/" ]
108,819
<p>What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new <code>Array</code> with the same strings but in a random order.</p> <p>Please include a C# example in your answer.</p>
[ { "answer_id": 108831, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 2, "selected": false, "text": "for i = 0 -> i= array.length * 5\n swap two strings in random places\n" }, { "answer_id": 108835, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "var stringlist = ... // add your values to stringlist\n\nvar r = new Random();\n\nvar res = new List<string>(stringlist.Count);\n\nwhile (stringlist.Count >0)\n{\n var i = r.Next(stringlist.Count);\n res.Add(stringlist[i]);\n stringlist.RemoveAt(i);\n}\n" }, { "answer_id": 108836, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 9, "selected": true, "text": "Random rnd=new Random();\nstring[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray(); \n Dim rnd As New System.Random\nDim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()\n lock (MyRandomArray) rnd System.Security.Cryptography.RandomNumberGenerator using System.Security.Cryptography;\n RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();\nstring[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();\n static int GetNextInt32(RNGCryptoServiceProvider rnd)\n {\n byte[] randomInt = new byte[4];\n rnd.GetBytes(randomInt);\n return Convert.ToInt32(randomInt[0]);\n }\n" }, { "answer_id": 108845, "author": "Tarsier", "author_id": 19357, "author_profile": "https://Stackoverflow.com/users/19357", "pm_score": 2, "selected": false, "text": "public string[] Randomize(string[] input)\n{\n List<string> inputList = input.ToList();\n string[] output = new string[input.Length];\n Random randomizer = new Random();\n int i = 0;\n\n while (inputList.Count > 0)\n {\n int index = r.Next(inputList.Count);\n output[i++] = inputList[index];\n inputList.RemoveAt(index);\n }\n\n return (output);\n}\n" }, { "answer_id": 108851, "author": "nullDev", "author_id": 6621, "author_profile": "https://Stackoverflow.com/users/6621", "pm_score": 0, "selected": false, "text": "Random r = new Random();\nList<string> list = new List(originalArray);\nList<string> randomStrings = new List();\n\nwhile(list.Count > 0)\n{\nint i = r.Random(list.Count);\nrandomStrings.Add(list[i]);\nlist.RemoveAt(i);\n}\n" }, { "answer_id": 109019, "author": "Seth Morris", "author_id": 13434, "author_profile": "https://Stackoverflow.com/users/13434", "pm_score": -1, "selected": false, "text": "// Input array\nList<String> lst = new List<string>();\nfor (int i = 0; i < 500; i += 1) lst.Add(i.ToString());\n\n// Output array\nList<String> lstRandom = new List<string>();\n\n// Randomize\nRandom rnd = new Random();\nlstRandom.AddRange(from s in lst orderby rnd.Next(100) select s);\n" }, { "answer_id": 110570, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 8, "selected": false, "text": "static class RandomExtensions\n{\n public static void Shuffle<T> (this Random rng, T[] array)\n {\n int n = array.Length;\n while (n > 1) \n {\n int k = rng.Next(n--);\n T temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n }\n}\n var array = new int[] {1, 2, 3, 4};\nvar rng = new Random();\nrng.Shuffle(array);\nrng.Shuffle(array); // different order from first call to Shuffle\n" }, { "answer_id": 3513921, "author": "Aaron", "author_id": 424209, "author_profile": "https://Stackoverflow.com/users/424209", "pm_score": 2, "selected": false, "text": " namespace System\n {\n public static class MSSystemExtenstions\n {\n private static Random rng = new Random();\n public static void Shuffle<T>(this T[] array)\n {\n rng = new Random();\n int n = array.Length;\n while (n > 1)\n {\n int k = rng.Next(n);\n n--;\n T temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n }\n }\n }\n string[] names = new string[] {\n \"Aaron Moline1\", \n \"Aaron Moline2\", \n \"Aaron Moline3\", \n \"Aaron Moline4\", \n \"Aaron Moline5\", \n \"Aaron Moline6\", \n \"Aaron Moline7\", \n \"Aaron Moline8\", \n \"Aaron Moline9\", \n };\n names.Shuffle<string>();\n" }, { "answer_id": 10397345, "author": "Himalaya Garg", "author_id": 1129978, "author_profile": "https://Stackoverflow.com/users/1129978", "pm_score": -1, "selected": false, "text": "private ArrayList ShuffleArrayList(ArrayList source)\n{\n ArrayList sortedList = new ArrayList();\n Random generator = new Random();\n\n while (source.Count > 0)\n {\n int position = generator.Next(source.Count);\n sortedList.Add(source[position]);\n source.RemoveAt(position);\n } \n return sortedList;\n}\n" }, { "answer_id": 13052597, "author": "jlarsson", "author_id": 1057524, "author_profile": "https://Stackoverflow.com/users/1057524", "pm_score": 1, "selected": false, "text": "public static class EnumerableExtensions\n{\n static readonly RNGCryptoServiceProvider RngCryptoServiceProvider = new RNGCryptoServiceProvider();\n public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable)\n {\n var randomIntegerBuffer = new byte[4];\n Func<int> rand = () =>\n {\n RngCryptoServiceProvider.GetBytes(randomIntegerBuffer);\n return BitConverter.ToInt32(randomIntegerBuffer, 0);\n };\n return from item in enumerable\n let rec = new {item, rnd = rand()}\n orderby rec.rnd\n select rec.item;\n }\n}\n Enumerable.Range(0,1000).Shuffle().ToList()\n" }, { "answer_id": 29614719, "author": "bytecode77", "author_id": 1199684, "author_profile": "https://Stackoverflow.com/users/1199684", "pm_score": 0, "selected": false, "text": "Random random = new Random();\narray.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();\n Array List List" }, { "answer_id": 36604736, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 0, "selected": false, "text": "class Program\n{\n static string[] words1 = new string[] { \"brown\", \"jumped\", \"the\", \"fox\", \"quick\" };\n\n static void Main()\n {\n var result = Shuffle(words1);\n foreach (var i in result)\n {\n Console.Write(i + \" \");\n }\n Console.ReadKey();\n }\n\n static string[] Shuffle(string[] wordArray) {\n Random random = new Random();\n for (int i = wordArray.Length - 1; i > 0; i--)\n {\n int swapIndex = random.Next(i + 1);\n string temp = wordArray[i];\n wordArray[i] = wordArray[swapIndex];\n wordArray[swapIndex] = temp;\n }\n return wordArray;\n } \n}\n" }, { "answer_id": 42074323, "author": "Nitish Katare", "author_id": 486276, "author_profile": "https://Stackoverflow.com/users/486276", "pm_score": 0, "selected": false, "text": " int[] numbers = {0,1,2,3,4,5,6,7,8,9};\n List<int> numList = new List<int>();\n numList.AddRange(numbers);\n\n Console.WriteLine(\"Original Order\");\n for (int i = 0; i < numList.Count; i++)\n {\n Console.Write(String.Format(\"{0} \",numList[i]));\n }\n\n Random random = new Random();\n Console.WriteLine(\"\\n\\nRandom Order\");\n for (int i = 0; i < numList.Capacity; i++)\n {\n int randomIndex = random.Next(numList.Count);\n Console.Write(String.Format(\"{0} \", numList[randomIndex]));\n numList.RemoveAt(randomIndex);\n }\n Console.ReadLine();\n" }, { "answer_id": 70203369, "author": "Sith2021", "author_id": 1712913, "author_profile": "https://Stackoverflow.com/users/1712913", "pm_score": 0, "selected": false, "text": "Random random = new();\n\nstring RandomWord()\n{\n const string CHARS = \"abcdefghijklmnoprstuvwxyz\";\n int n = random.Next(CHARS.Length);\n return string.Join(\"\", CHARS.OrderBy(x => random.Next()).ToArray())[0..n];\n}\n" }, { "answer_id": 70973950, "author": "lev krinitsky", "author_id": 15795755, "author_profile": "https://Stackoverflow.com/users/15795755", "pm_score": 2, "selected": false, "text": " public static void Shuffle(object[] arr)\n {\n Random rand = new Random();\n for (int i = arr.Length - 1; i >= 1; i--)\n {\n int j = rand.Next(i + 1);\n object tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n }\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
108,822
<p>I would like to wipe out all data for a specific kind in Google App Engine. What is the best way to do this? I wrote a delete script (hack), but since there is so much data is timeout's out after a few hundred records. </p>
[ { "answer_id": 108939, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 3, "selected": false, "text": "# Deleting all messages older than \"earliest_date\"\nq = db.GqlQuery(\"SELECT * FROM Message WHERE create_date < :1\", earliest_date)\nresults = q.fetch(1000)\n\nwhile results:\n db.delete(results)\n results = q.fetch(1000, len(results))\n" }, { "answer_id": 323041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "from google.appengine.ext import db\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nimport wsgiref.handlers\nfrom mainPage import YourData #replace this with your data\nclass CleanTable(webapp.RequestHandler):\n def get(self, param):\n txt = self.request.get('table')\n q = db.GqlQuery(\"SELECT * FROM \"+txt)\n results = q.fetch(10)\n self.response.headers['Content-Type'] = 'text/plain'\n #replace yourapp and YouData your app info below.\n self.response.out.write(\"\"\"\n <html>\n <meta HTTP-EQUIV=\"REFRESH\" content=\"5; url=http://yourapp.appspot.com/cleanTable?table=YourData\">\n <body>\"\"\")\n\n try:\n for i in range(10):\n db.delete(results)\n results = q.fetch(10, len(results))\n self.response.out.write(\"<p>10 removed</p>\")\n self.response.out.write(\"\"\"\n </body>\n </html>\"\"\")\n\n except Exception, ints:\n self.response.out.write(str(inst))\n\ndef main():\n application = webapp.WSGIApplication([\n ('/cleanTable(.*)', CleanTable),\n ])\n\n wsgiref.handlers.CGIHandler().run(application) \n" }, { "answer_id": 1023729, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "from google.appengine.ext import db\n\nclass bulkdelete(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n try:\n while True:\n q = db.GqlQuery(\"SELECT __key__ FROM MyModel\")\n assert q.count()\n db.delete(q.fetch(200))\n time.sleep(0.5)\n except Exception, e:\n self.response.out.write(repr(e)+'\\n')\n pass\n" }, { "answer_id": 1882697, "author": "babakm", "author_id": 153168, "author_profile": "https://Stackoverflow.com/users/153168", "pm_score": 3, "selected": false, "text": "package com.intillium.formshnuker;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\n\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport com.google.appengine.api.datastore.Key;\nimport com.google.appengine.api.datastore.Query;\nimport com.google.appengine.api.datastore.Entity;\nimport com.google.appengine.api.datastore.FetchOptions;\nimport com.google.appengine.api.datastore.DatastoreService;\nimport com.google.appengine.api.datastore.DatastoreServiceFactory;\n\nimport com.google.appengine.api.labs.taskqueue.QueueFactory;\nimport com.google.appengine.api.labs.taskqueue.TaskOptions.Method;\n\nimport static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;\n\n@SuppressWarnings(\"serial\")\npublic class FormsnukerServlet extends HttpServlet {\n\n public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {\n\n response.setContentType(\"text/plain\");\n\n final String kind = request.getParameter(\"kind\");\n final String passcode = request.getParameter(\"passcode\");\n\n if (kind == null) {\n throw new NullPointerException();\n }\n\n if (passcode == null) {\n throw new NullPointerException();\n }\n\n if (!passcode.equals(\"LONGSECRETCODE\")) {\n response.getWriter().println(\"BAD PASSCODE!\");\n return;\n }\n\n System.err.println(\"*** deleting entities form \" + kind);\n\n final long start = System.currentTimeMillis();\n\n int deleted_count = 0;\n boolean is_finished = false;\n\n final DatastoreService dss = DatastoreServiceFactory.getDatastoreService();\n\n while (System.currentTimeMillis() - start < 16384) {\n\n final Query query = new Query(kind);\n\n query.setKeysOnly();\n\n final ArrayList<Key> keys = new ArrayList<Key>();\n\n for (final Entity entity: dss.prepare(query).asIterable(FetchOptions.Builder.withLimit(128))) {\n keys.add(entity.getKey());\n }\n\n keys.trimToSize();\n\n if (keys.size() == 0) {\n is_finished = true;\n break;\n }\n\n while (System.currentTimeMillis() - start < 16384) {\n\n try {\n\n dss.delete(keys);\n\n deleted_count += keys.size();\n\n break;\n\n } catch (Throwable ignore) {\n\n continue;\n\n }\n\n }\n\n }\n\n System.err.println(\"*** deleted \" + deleted_count + \" entities form \" + kind);\n\n if (is_finished) {\n\n System.err.println(\"*** deletion job for \" + kind + \" is completed.\");\n\n } else {\n\n final int taskcount;\n\n final String tcs = request.getParameter(\"taskcount\");\n\n if (tcs == null) {\n taskcount = 0;\n } else {\n taskcount = Integer.parseInt(tcs) + 1;\n }\n\n QueueFactory.getDefaultQueue().add(\n url(\"/formsnuker?kind=\" + kind + \"&passcode=LONGSECRETCODE&taskcount=\" + taskcount).method(Method.GET));\n\n System.err.println(\"*** deletion task # \" + taskcount + \" for \" + kind + \" is queued.\");\n\n }\n\n response.getWriter().println(\"OK\");\n\n }\n\n}\n" }, { "answer_id": 2511446, "author": "Janusz Skonieczny", "author_id": 260480, "author_profile": "https://Stackoverflow.com/users/260480", "pm_score": 1, "selected": false, "text": "url(r'^Model/bdelete/$', v.bulk_delete_models, {'model':'ModelKind'}),\n def bulk_delete_models(request, model):\n import time\n limit = request.GET['limit'] or 200\n start = time.clock()\n set = db.GqlQuery(\"SELECT __key__ FROM %s\" % model).fetch(int(limit))\n count = len(set)\n db.delete(set)\n return HttpResponse(\"Deleted %s %s in %s\" % (count,model,(time.clock() - start)))\n $client = new-object System.Net.WebClient\n$client.DownloadString(\"http://your-app.com/Model/bdelete/?limit=400\")\n" }, { "answer_id": 3376429, "author": "Timothy Jordan", "author_id": 407246, "author_profile": "https://Stackoverflow.com/users/407246", "pm_score": 0, "selected": false, "text": "class ClearHandler(webapp.RequestHandler): \n def get(self): \n self.response.headers['Content-Type'] = 'text/plain' \n q = db.GqlQuery(\"SELECT * FROM SomeModel\") \n self.response.out.write(\"deleting...\") \n db.delete(q)\n" }, { "answer_id": 3671769, "author": "systempuntoout", "author_id": 130929, "author_profile": "https://Stackoverflow.com/users/130929", "pm_score": 3, "selected": false, "text": "from mapreduce import operation as op\ndef process(entity):\n yield op.db.Delete(entity)\n @Override\npublic void map(Key key, Entity value, Context context) {\n log.info(\"Adding key to deletion pool: \" + key);\n DatastoreMutationPool mutationPool = this.getAppEngineContext(context)\n .getMutationPool();\n mutationPool.delete(value.getKey());\n}\n" }, { "answer_id": 4600511, "author": "bebeastie", "author_id": 331628, "author_profile": "https://Stackoverflow.com/users/331628", "pm_score": 1, "selected": false, "text": " em = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory)\n Query q = em.createQuery(\"delete from Table t\");\n int number = q.executeUpdate();\n" }, { "answer_id": 7291775, "author": "Kjuly", "author_id": 904365, "author_profile": "https://Stackoverflow.com/users/904365", "pm_score": 0, "selected": false, "text": "python bulkdel.py 10 DB_1\n python bulkdel.py 11\n import sys, os\n\nURL = 'http://localhost:8080'\nDB_MODEL_LIST = ['DB_1', 'DB_2', 'DB_3']\n\n# Delete Model\nif sys.argv[1] == '10' :\n command = 'curl %s/clear_db?model=%s' % ( URL, sys.argv[2] )\n os.system( command )\n\n# Delete All DB Models\nif sys.argv[1] == '11' :\n for model in DB_MODEL_LIST :\n command = 'curl %s/clear_db?model=%s' % ( URL, model )\n os.system( command )\n from google.appengine.ext import db\nclass DBDelete( webapp.RequestHandler ):\n def get( self ):\n self.response.headers['Content-Type'] = 'text/plain'\n db_model = self.request.get('model')\n sql = 'SELECT __key__ FROM %s' % db_model\n\n try:\n while True:\n q = db.GqlQuery( sql )\n assert q.count()\n db.delete( q.fetch(200) )\n time.sleep(0.5)\n except Exception, e:\n self.response.out.write( repr(e)+'\\n' )\n pass\n from google.appengine.ext import webapp\nimport utility # DBDelete was defined in utility.py\napplication = webapp.WSGIApplication([('/clear_db',utility.DBDelete ),('/',views.MainPage )],debug = True)\n" }, { "answer_id": 13626511, "author": "Herbert", "author_id": 853462, "author_profile": "https://Stackoverflow.com/users/853462", "pm_score": -1, "selected": false, "text": "document.getElementById(\"allkeys\").checked=true;\ncheckAllEntities();\ndocument.getElementById(\"delete_button\").setAttribute(\"onclick\",\"\");\ndocument.getElementById(\"delete_button\").click();\n" }, { "answer_id": 33964279, "author": "hamx0r", "author_id": 682515, "author_profile": "https://Stackoverflow.com/users/682515", "pm_score": 1, "selected": false, "text": "dev_appserver.py --clear_datastore=yes .\n" }, { "answer_id": 54553447, "author": "jcrv", "author_id": 9056430, "author_profile": "https://Stackoverflow.com/users/9056430", "pm_score": 0, "selected": false, "text": "from google.cloud import datastore\n\nquery = datastore.Client().query(kind = <KIND>)\nresults = query.fetch()\nfor result in results:\n datastore.Client().delete(result.key)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8548/" ]
108,848
<p>I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on <a href="http://wiki.python.org/moin/PythonInMusic" rel="nofollow noreferrer">music</a> and <a href="http://wiki.python.org/moin/Audio/" rel="nofollow noreferrer">basic audio</a> as well as a StackOverflow question on <a href="https://stackoverflow.com/questions/45385/good-python-library-for-generating-audio-files">generating audio files</a>, but <strong><em>what I'm looking for is a decent library for music creation</em></strong>. Has anyone on here tried to do something like this before? If so, what was your solution? What, either of the ones I've found, or something I haven't found, would be a decent library for audio manipulation?</p> <p>Minimally, I'd like to be able to do something similar to <a href="http://audacity.sourceforge.net/" rel="nofollow noreferrer">Audacity's</a> scope within python, but if anyone knows of a library that can do more... I'm all ears.</p>
[ { "answer_id": 108936, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 3, "selected": false, "text": "import pymedia\nimport time\n\ndemuxer = pymedia.muxer.Demuxer('mp3') #this thing decodes the multipart file i call it a demucker\n\nf = open(r\"path to \\song.mp3\", 'rb')\n\n\nspot = f.read()\nframes = demuxer.parse(spot)\nprint 'read it has %i frames' % len(frames)\ndecoder = pymedia.audio.acodec.Decoder(demuxer.streams[0]) #this thing does the actual decoding\nframe = decoder.decode(spot)\nprint dir(frame)\n#sys.exit(1)\nsound = pymedia.audio.sound\nprint frame.bitrate, frame.sample_rate\nsong = sound.Output( frame.sample_rate, frame.channels, 16 ) #this thing handles playing the song\n\nwhile len(spot) > 0:\n try:\n if frame: song.play(frame.data)\n spot = f.read(512)\n frame = decoder.decode(spot)\n except:\n pass\n\nwhile song.isPlaying(): time.sleep(.05)\nprint 'well done'\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
108,853
<p>I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.</p> <p>I.e., the same script is included on <code>/</code>, <code>/help</code>, <code>/whatever</code>, and so on, while it will always need to request from <code>/data.json</code>. Additionally, the same site is run on different servers, where the <code>/</code>-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.</p> <p>Are there small scripts that will work on all browsers made for this?</p>
[ { "answer_id": 108860, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "document.location.href" }, { "answer_id": 108894, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<link> <head> <link id=\"link-action-1\" href=\"${reverse_url ('action_1')}\"/>\n <link id=\"link-action-1\" href=\"/my/web/root/action-1/\"/>\n document.getElementById ('link-action-1').href;\n" }, { "answer_id": 108901, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 2, "selected": false, "text": "<base href=\"http://path/to/webapp/root/\" />\n" }, { "answer_id": 108949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/**\n * Build current url, depending on protocal (http/https),\n * port, server name and path suffix\n */\n$site_root = 'http';\nif (isset($_SERVER[\"HTTPS\"]) && $_SERVER[\"HTTPS\"] == \"on\") \n $site_root .= \"s\";\n$site_root .= \"://\" . $_SERVER[\"SERVER_NAME\"];\nif ($_SERVER[\"SERVER_PORT\"] != \"80\")\n $site_root .= \":\" . $_SERVER[\"SERVER_PORT\"];\n$site_root .= $g_config[\"paths\"][\"site_suffix\"];\n\n$g_config[\"paths\"][\"site_root\"] = $site_root;\n <link id=\"site_root\" href=\"<?php echo $g_config[\"paths\"][\"site_root\"] ?>\"/>\n <script type = \"text/javascript\">\nvar SiteRoot = \"<?php echo $g_config[\"paths\"][\"site_root\"]; ?>\";\n</script>\n" }, { "answer_id": 7235971, "author": "Abc", "author_id": 369724, "author_profile": "https://Stackoverflow.com/users/369724", "pm_score": 2, "selected": false, "text": "function getScriptUrl ( name ) {\n var scripts = document.getElementsByTagName('script');\n var re = RegExp(\"(\\/|^)\" + name + \"$\");\n var src;\n for( var i = 0; i < scripts.length; i++){\n src = scripts[i].getAttribute('src');\n if( src.match(re) )\n return src;\n }\n return null;\n}\n\nconsole.log( 'found ' + getScriptUrl('demo.js') );\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
108,866
<p>Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following:</p> <pre><code>int32_t array[10]; memset32(array, 0xDEADBEEF, sizeof(array)); </code></pre> <p>This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.</p> <p>Specifically, I am interested in a 64 bit version of memset(). Know anything like that?</p>
[ { "answer_id": 108876, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 3, "selected": false, "text": "wmemset(3)" }, { "answer_id": 108884, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 6, "selected": true, "text": "void memset64( void * dest, uint64_t value, uintptr_t size )\n{\n uintptr_t i;\n for( i = 0; i < (size & (~7)); i+=8 )\n {\n memcpy( ((char*)dest) + i, &value, 8 );\n } \n for( ; i < size; i++ )\n {\n ((char*)dest)[i] = ((char*)&value)[i&7];\n } \n}\n" }, { "answer_id": 108908, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "//pseudo code\nasm\n{\n rep stosq ...\n}\n" }, { "answer_id": 8820379, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 3, "selected": false, "text": "memcpy(..) --------------------\n\nFirst copy one:\nN-------------------\n\nThen copy it to the neighbour:\nNN------------------\n\nThen copy them to make four:\nNNNN----------------\n\nAnd so on:\nNNNNNNNN------------\n\nNNNNNNNNNNNNNNNN----\n\nThen copy enough to fill the array:\nNNNNNNNNNNNNNNNNNNNN\n memcpy(..) int *memset_int(int *ptr, int value, size_t num) {\n if (num < 1) return ptr;\n memcpy(ptr, &value, sizeof(int));\n size_t start = 1, step = 1;\n for ( ; start + step <= num; start += step, step *= 2)\n memcpy(ptr + start, ptr, sizeof(int) * step);\n\n if (start < num)\n memcpy(ptr + start, ptr, sizeof(int) * (num - start));\n return ptr;\n}\n memcpy(..) memcpy(..)" }, { "answer_id": 15210350, "author": "Cosmin", "author_id": 1735438, "author_profile": "https://Stackoverflow.com/users/1735438", "pm_score": 2, "selected": false, "text": "inline void memset32(void *buf, uint32_t n, int32_t c)\n{\n __asm {\n mov ecx, n\n mov eax, c\n mov edi, buf\n rep stosd\n }\n}\n for(uint32_t i = 0;i < n;i++)\n{\n ((int_32 *)buf)[i] = c;\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7748/" ]
108,892
<p>Basically, growl notifications (or other callbacks) when tests break or pass. <strong>Does anything like this exist?</strong></p> <p>If not, it should be pretty easy to write.. Easiest way would be to..</p> <ol> <li>run <code>python-autotest myfile1.py myfile2.py etc.py</code> <ul> <li>Check if files-to-be-monitored have been modified (possibly just if they've been saved).</li> <li>Run any tests in those files.</li> <li>If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass.</li> <li>Wait, and repeat steps 2-5.</li> </ul></li> </ol> <p>The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc..</p> <p>The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement?</p> <p>To summarise:</p> <ul> <li>Is there anything like the Ruby tool <code>autotest</code> (part of the <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" rel="noreferrer">ZenTest package</a>), but for Python code?</li> <li>How do you check which functions have changed between two revisions of a script?</li> <li>Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback)</li> </ul>
[ { "answer_id": 108934, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "trace >>> def y(a): return a*a\n>>> def x(a): return y(a)\n>>> import trace\n>>> tracer = trace.Trace(countfuncs = 1)\n>>> tracer.runfunc(x, 2)\n4\n>>> res = tracer.results()\n>>> res.calledfuncs\n{('<stdin>', '<stdin>', 'y'): 1, ('<stdin>', '<stdin>', 'x'): 1}\n res.calledfuncs countcallers = 1 trace" }, { "answer_id": 482668, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": false, "text": "import" }, { "answer_id": 9461979, "author": "jkp", "author_id": 912, "author_profile": "https://Stackoverflow.com/users/912", "pm_score": 6, "selected": true, "text": "$ pip install sniffer\n$ cd myproject\n $ sniffer\n nosetests --verbose --with-doctest $ sniffer -x--verbose -x--with-doctest\n pyinotify pywin32 MacFSEvents pip" }, { "answer_id": 40910385, "author": "Oto Brglez", "author_id": 226622, "author_profile": "https://Stackoverflow.com/users/226622", "pm_score": 2, "selected": false, "text": "*.py ls */**.py | entr python -m unittest discover -s test\n" }, { "answer_id": 52110595, "author": "Mark", "author_id": 3600510, "author_profile": "https://Stackoverflow.com/users/3600510", "pm_score": 2, "selected": false, "text": "manage.py test nodemon --ext py --exec \"python manage.py test\" nodemon" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
108,900
<p>How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <a href="http://www.compuphase.com/svnrev.htm" rel="nofollow noreferrer">http://www.compuphase.com/svnrev.htm</a> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info. </p> <p>What's the best way to proceed?</p>
[ { "answer_id": 109026, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "VS_VERSION_INFO #define SVN_VERSION_NO xxx\n" }, { "answer_id": 109050, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": ".rc #include .c version.h #define MY_PRODUCT_VERSION \"0.47\"\n#define MY_PRODUCT_VERSION_NUM 0,47,0,0\n .rc #include \"version.h\" VS_VERSION_INFO VERSIONINFO\n FILEVERSION MY_PRODUCT_VERSION_NUM\n PRODUCTVERSION MY_PRODUCT_VERSION_NUM\n...\n VALUE \"FileVersion\", MY_PRODUCT_VERSION \"\\0\"\n VALUE \"ProductVersion\", MY_PRODUCT_VERSION \"\\0\"\n...\n VS_VERSION_INFO .rc2" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17259/" ]
108,938
<p>Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session.</p> <p>I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible.</p> <p>So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts?</p>
[ { "answer_id": 117610, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 4, "selected": true, "text": "@@arbitrary_name ||= Model.find_by_stupidly_long_query(param)\n" }, { "answer_id": 2733368, "author": "TraderJoeChicago", "author_id": 124708, "author_profile": "https://Stackoverflow.com/users/124708", "pm_score": 0, "selected": false, "text": "APP_CONTEXT = Hash.new" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041950/" ]
108,940
<p>I am trying to evaluate the answer <a href="https://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp">provided here</a>, and am getting the error: <code>"A file with name ASDF-INSTALL does not exist"</code> when using clisp:</p> <pre><code>dsm@localhost:~$ clisp -q [1]&gt; (require :asdf-install) *** - LOAD: A file with name ASDF-INSTALL does not exist The following restarts are available: ABORT :R1 ABORT Break 1 [2]&gt; :r1 [3]&gt; (quit) dsm@localhost:~$ </code></pre> <p>cmucl throws a similar error:</p> <pre><code>dsm@localhost:~$ cmucl -q Warning: #&lt;Command Line Switch "q"&gt; is an illegal switch CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile With core: /usr/lib/cmucl/lisp.core Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS. or to pvaneynd@debian.org type (help) for help, (quit) to exit, and (demo) to see the demos Loaded subsystems: Python 1.1, target Intel x86 CLOS based on Gerd's PCL 2004/04/14 03:32:47 * (require :asdf-install) Error in function REQUIRE: Don't know how to load ASDF-INSTALL [Condition of type SIMPLE-ERROR] Restarts: 0: [ABORT] Return to Top-Level. Debug (type H for help) (REQUIRE :ASDF-INSTALL NIL) Source: ; File: target:code/module.lisp (ERROR "Don't know how to load ~A" MODULE-NAME) 0] (quit) dsm@localhost:~$ </code></pre> <p>But sbcl works perfectly:</p> <pre><code>dsm@localhost:~$ sbcl -q This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp. More information about SBCL is available at &lt;http://www.sbcl.org/&gt;. SBCL is free software, provided as is, with absolutely no warranty. It is mostly in the public domain; some portions are provided under BSD-style licenses. See the CREDITS and COPYING files in the distribution for more information. * (require :asdf-install) ; loading system definition from ; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #&lt;PACKAGE "ASDF0"&gt; ; registering #&lt;SYSTEM SB-BSD-SOCKETS {AB01A89}&gt; as SB-BSD-SOCKETS ; registering #&lt;SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}&gt; as SB-BSD-SOCKETS-TESTS ("SB-BSD-SOCKETS" "ASDF-INSTALL") * (quit) </code></pre> <p>Any ideas on how to fix this? I found <a href="https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208" rel="nofollow noreferrer">this post</a> on the internet, but using that didn't work either.</p>
[ { "answer_id": 109028, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 2, "selected": false, "text": "(require :asdf)\n" }, { "answer_id": 109253, "author": "FlinkmanSV", "author_id": 15054, "author_profile": "https://Stackoverflow.com/users/15054", "pm_score": 2, "selected": false, "text": "darcs get http://common-lisp.net/project/clbuild/clbuild\ncd clbuild\nchmod +x ./clbuild\n./clbuild check\n./clbuild build slime hunchentoot\n./clbuild preloaded\n * (hunchentoot:start-server :port 8080)\n wget -O - http://localhost:8080/\n\n<html><head><title>Hunchentoot</title></head>\n <body><h2>Hunchentoot Default Page</h2>\n <p>This is the Hunchentoot default page....\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
108,971
<p>We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.</p> <p>Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?</p>
[ { "answer_id": 156024, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 7, "selected": true, "text": "(cmd.exe)\nC:\nmkdir \\TEMP\\CrossPlatformTest\ncd \\TEMP\\CrossPlatformTest\n // file 'library.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Library\n{\n public static class Worker\n {\n public static void Run()\n {\n System.Console.WriteLine(\"Worker is running\");\n System.Console.WriteLine(\"(Enter to continue)\");\n System.Console.ReadLine();\n }\n }\n}\n (cmd.exe from Note 2)\nmkdir platform\\x86\ncsc /out:platform\\x86\\library.dll /target:library /platform:x86 library.cs\nmkdir platform\\amd64\ncsc /out:platform\\amd64\\library.dll /target:library /platform:x64 library.cs\n // file 'bootstrapper.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Program\n{\n public static class Bootstrapper\n {\n public static void Main()\n {\n System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve;\n App.Run();\n }\n\n private static System.Reflection.Assembly CustomResolve(\n object sender,\n System.ResolveEventArgs args)\n {\n if (args.Name.StartsWith(\"library\"))\n {\n string fileName = System.IO.Path.GetFullPath(\n \"platform\\\\\"\n + System.Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\")\n + \"\\\\library.dll\");\n System.Console.WriteLine(fileName);\n if (System.IO.File.Exists(fileName))\n {\n return System.Reflection.Assembly.LoadFile(fileName);\n }\n }\n return null;\n }\n }\n}\n // file 'program.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Program\n{\n public static class App\n {\n public static void Run()\n {\n Cross.Platform.Library.Worker.Run();\n }\n }\n}\n (cmd.exe from Note 2)\ncsc /reference:platform\\x86\\library.dll /out:program.exe program.cs bootstrapper.cs\n (C:\\TEMP\\CrossPlatformTest, root dir)\n platform (dir)\n amd64 (dir)\n library.dll\n x86 (dir)\n library.dll\n program.exe\n *.cs (source files)\n" }, { "answer_id": 9951658, "author": "Yuri Astrakhan", "author_id": 177275, "author_profile": "https://Stackoverflow.com/users/177275", "pm_score": 5, "selected": false, "text": "AppDomain.CurrentDomain.SetupInformation.ApplicationBase Path.GetFullPath() Environment.Is64BitProcess PROCESSOR_ARCHITECTURE IntPtr.Size == 8 public static class MultiplatformDllLoader\n{\n private static bool _isEnabled;\n\n public static bool Enable\n {\n get { return _isEnabled; }\n set\n {\n lock (typeof (MultiplatformDllLoader))\n {\n if (_isEnabled != value)\n {\n if (value)\n AppDomain.CurrentDomain.AssemblyResolve += Resolver;\n else\n AppDomain.CurrentDomain.AssemblyResolve -= Resolver;\n _isEnabled = value;\n }\n }\n }\n }\n\n /// Will attempt to load missing assembly from either x86 or x64 subdir\n private static Assembly Resolver(object sender, ResolveEventArgs args)\n {\n string assemblyName = args.Name.Split(new[] {','}, 2)[0] + \".dll\";\n string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,\n Environment.Is64BitProcess ? \"x64\" : \"x86\",\n assemblyName);\n\n return File.Exists(archSpecificPath)\n ? Assembly.LoadFile(archSpecificPath)\n : null;\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6156/" ]
109,000
<p>My C application uses 3rd libraries, which do their own memory management. In order to be robust, my application has code to deal with failures of library functions due to lack of free memory.</p> <p>I would like to test this code, and for this, I need to simulate failures due to lack of memory.</p> <p>What tool/s are recommended for this? My environment is Linux/gcc.</p>
[ { "answer_id": 109008, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 2, "selected": false, "text": "#define malloc(s) (my_malloc(s))\n #include \"memhook.h\"\n#undef malloc\n#include <stdlib.h>\n" }, { "answer_id": 109012, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": false, "text": "ulimit ulimit -m 64\n" }, { "answer_id": 53161379, "author": "Antonin GAVREL", "author_id": 3161139, "author_profile": "https://Stackoverflow.com/users/3161139", "pm_score": 1, "selected": false, "text": "if ((int *x = malloc(sizeof(int))) == NULL)\n{\n return NULL;\n}\n # define malloc(X) NULL\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11886/" ]
109,023
<p>8 bits representing the number 7 look like this:</p> <pre><code>00000111 </code></pre> <p>Three bits are set.</p> <p>What are the algorithms to determine the number of set bits in a 32-bit integer?</p>
[ { "answer_id": 109025, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 11, "selected": true, "text": "popcnt std::popcount() std::bitset<32>::count() int numberOfSetBits(uint32_t i)\n{\n // Java: use int, and use >>> instead of >>. Or use Integer.bitCount()\n // C or C++: use uint32_t\n i = i - ((i >> 1) & 0x55555555); // add pairs of bits\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads\n i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8\n return (i * 0x01010101) >> 24; // horizontal sum of bytes\n}\n |0 i = (i|0) - ((i >> 1) & 0x55555555); i = i - ((i >> 1) & 0x55555555);\n (i & 0x55555555) + ((i>>1) & 0x55555555) i - ... 0x33... 0xccc... (i + (i >> 4)) & 0x0F0F0F0F 4 i + (i >> 4) x * 0x01010101 x + (x<<8) + (x<<16) + (x<<24) >>56 __builtin_popcountll popcnt PSHUFB vpternlogd" }, { "answer_id": 109054, "author": "Noether", "author_id": 12210, "author_profile": "https://Stackoverflow.com/users/12210", "pm_score": 6, "selected": false, "text": "Integer.bitCount" }, { "answer_id": 109069, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 8, "selected": false, "text": "std::bitset<>::count() std::popcount(T x) java.lang.Integer.bitCount() System.Numerics.BitOperations.PopCount() int.bit_count() int __builtin_popcount (unsigned int x);\nint __builtin_popcountll (unsigned long long x);\n * / -mpopcnt popcnt -mpopcnt -msse4.2 -march=nehalem -mtune=skylake -march= -march=native popcnt std::bitset<>::count() std::bitset<> std::bitset popcnt std::bitset<>::count /Ox /arch:AVX std::popcount popcnt #include <bitset>\n#include <limits>\n#include <type_traits>\n\ntemplate<typename T>\n//static inline // static if you want to compile with -mpopcnt in one compilation unit but not others\ntypename std::enable_if<std::is_integral<T>::value, unsigned >::type \npopcount(T x)\n{\n static_assert(std::numeric_limits<T>::radix == 2, \"non-binary type\");\n\n // sizeof(x)*CHAR_BIT\n constexpr int bitwidth = std::numeric_limits<T>::digits + std::numeric_limits<T>::is_signed;\n // std::bitset constructor was only unsigned long before C++11. Beware if porting to C++03\n static_assert(bitwidth <= std::numeric_limits<unsigned long long>::digits, \"arg too wide for std::bitset() constructor\");\n\n typedef typename std::make_unsigned<T>::type UT; // probably not needed, bitset width chops after sign-extension\n\n std::bitset<bitwidth> bs( static_cast<UT>(x) );\n return bs.count();\n}\n gcc -O3 -std=gnu++11 -mpopcnt unsigned test_short(short a) { return popcount(a); }\n movzx eax, di # note zero-extension, not sign-extension\n popcnt rax, rax\n ret\n\nunsigned test_int(int a) { return popcount(a); }\n mov eax, edi\n popcnt rax, rax # unnecessary 64-bit operand size\n ret\n\nunsigned test_u64(unsigned long long a) { return popcount(a); }\n xor eax, eax # gcc avoids false dependencies for Intel CPUs\n popcnt rax, rdi\n ret\n gcc -O3 -std=gnu++11 int rldicl 3,3,0,32 # zero-extend from 32 to 64-bit\n popcntd 3,3 # popcount\n blr\n std::popcount(T) if(x==0) return 0; #include <bit>\nint bar(unsigned x) {\n return std::popcount(x);\n}\n -O3 -std=gnu++20 -march=nehalem # clang 11\n bar(unsigned int): # @bar(unsigned int)\n popcnt eax, edi\n cmove eax, edi # redundant: if popcnt result is 0, return the original 0 instead of the popcnt-generated 0...\n ret\n # gcc 10\n xor eax, eax # break false dependency on Intel SnB-family before Ice Lake.\n popcnt eax, edi\n ret\n -arch:AVX -std:c++latest int bar(unsigned int) PROC ; bar, COMDAT\n popcnt eax, ecx\n ret 0\nint bar(unsigned int) ENDP ; bar\n" }, { "answer_id": 109093, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 3, "selected": false, "text": " static final int[] BIT_COUNT = { 0, 1, 1, ... 256 values with a bitsize of a byte ... };\n static int bitCountOfByte( int value ){\n return BIT_COUNT[ value & 0xFF ];\n }\n\n static int bitCountOfInt( int value ){\n return bitCountOfByte( value ) \n + bitCountOfByte( value >> 8 ) \n + bitCountOfByte( value >> 16 ) \n + bitCountOfByte( value >> 24 );\n }\n" }, { "answer_id": 109117, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 7, "selected": false, "text": "int pop(unsigned x)\n{\n x = x - ((x >> 1) & 0x55555555);\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333);\n x = (x + (x >> 4)) & 0x0F0F0F0F;\n x = x + (x >> 8);\n x = x + (x >> 16);\n return x & 0x0000003F;\n}\n" }, { "answer_id": 109915, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 8, "selected": false, "text": "unsigned int bitCount (unsigned int value) {\n unsigned int count = 0;\n while (value > 0) { // until all bits are zero\n if ((value & 1) == 1) // check lower bit\n count++;\n value >>= 1; // shift bits, removing lower bit\n }\n return count;\n}\n // Lookup table for fast calculation of bits set in 8-bit unsigned char.\n\nstatic unsigned char oneBitsInUChar[] = {\n// 0 1 2 3 4 5 6 7 8 9 A B C D E F (<- n)\n// =====================================================\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 0n\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1n\n : : :\n 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, // Fn\n};\n\n// Function for fast calculation of bits set in 16-bit unsigned short.\n\nunsigned char oneBitsInUShort (unsigned short x) {\n return oneBitsInUChar [x >> 8]\n + oneBitsInUChar [x & 0xff];\n}\n\n// Function for fast calculation of bits set in 32-bit unsigned int.\n\nunsigned char oneBitsInUInt (unsigned int x) {\n return oneBitsInUShort (x >> 16)\n + oneBitsInUShort (x & 0xffff);\n}\n" }, { "answer_id": 113098, "author": "PhirePhly", "author_id": 20082, "author_profile": "https://Stackoverflow.com/users/20082", "pm_score": 5, "selected": false, "text": "int bitcount(unsigned int num){\n int count = 0;\n static int nibblebits[] =\n {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};\n for(; num != 0; num >>= 4)\n count += nibblebits[num & 0x0f];\n return count;\n}\n" }, { "answer_id": 131212, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "static unsigned char wordbits[65536] = { bitcounts of ints between 0 and 65535 };\nstatic int popcount( unsigned int i )\n{\n return( wordbits[i&0xFFFF] + wordbits[i>>16] );\n}\n" }, { "answer_id": 2786288, "author": "Baban", "author_id": 335085, "author_profile": "https://Stackoverflow.com/users/335085", "pm_score": 3, "selected": false, "text": "count = 0\nwhile n != 0\nif ((n % 2) == 1 || (n % 2) == -1\n count += 1\n n /= 2 \nreturn count\n int bit_count(int num)\n{\n int count=0;\n while(num)\n {\n num=(num)&(num-1);\n count++;\n }\n return count;\n}\n" }, { "answer_id": 3026418, "author": "systemBuilder", "author_id": 364891, "author_profile": "https://Stackoverflow.com/users/364891", "pm_score": 3, "selected": false, "text": "#define BitCount(X,Y) \\\n Y = X - ((X >> 1) & 033333333333) - ((X >> 2) & 011111111111); \\\n Y = ((Y + (Y >> 3)) & 030707070707); \\\n Y = (Y + (Y >> 6)); \\\n Y = (Y + (Y >> 12) + (Y >> 24)) & 077;\n input output\nAB CD Note\n00 00 = AB\n01 01 = AB\n10 01 = AB - (A >> 1) & 0x1\n11 10 = AB - (A >> 1) & 0x1\n" }, { "answer_id": 4413115, "author": "Rahul", "author_id": 538356, "author_profile": "https://Stackoverflow.com/users/538356", "pm_score": 3, "selected": false, "text": "Integer.highestOneBit(n);\nInteger.lowestOneBit(n);\nInteger.numberOfLeadingZeros(n);\nInteger.numberOfTrailingZeros(n);\n\n//Beginning with the value 1, rotate left 16 times\n n = 1;\n for (int i = 0; i < 16; i++) {\n n = Integer.rotateLeft(n, 1);\n System.out.println(n);\n }\n" }, { "answer_id": 5469563, "author": "Robert S. Barnes", "author_id": 71074, "author_profile": "https://Stackoverflow.com/users/71074", "pm_score": 3, "selected": false, "text": "#ifndef _BITCOUNT_H_\n#define _BITCOUNT_H_\n\n/* Return the Hamming Wieght of val, i.e. the number of 'on' bits. */\nint bitcount( unsigned int );\n\n/* List of available bitcount algorithms. \n * onTheFly: Calculate the bitcount on demand.\n *\n * lookupTalbe: Uses a small lookup table to determine the bitcount. This\n * method is on average 3 times as fast as onTheFly, but incurs a small\n * upfront cost to initialize the lookup table on the first call.\n *\n * strategyCount is just a placeholder. \n */\nenum strategy { onTheFly, lookupTable, strategyCount };\n\n/* String represenations of the algorithm names */\nextern const char *strategyNames[];\n\n/* Choose which bitcount algorithm to use. */\nvoid setStrategy( enum strategy );\n\n#endif\n #include <limits.h>\n\n#include \"bitcount.h\"\n\n/* The number of entries needed in the table is equal to the number of unique\n * values a char can represent which is always UCHAR_MAX + 1*/\nstatic unsigned char _bitCountTable[UCHAR_MAX + 1];\nstatic unsigned int _lookupTableInitialized = 0;\n\nstatic int _defaultBitCount( unsigned int val ) {\n int count;\n\n /* Starting with:\n * 1100 - 1 == 1011, 1100 & 1011 == 1000\n * 1000 - 1 == 0111, 1000 & 0111 == 0000\n */\n for ( count = 0; val; ++count )\n val &= val - 1;\n\n return count;\n}\n\n/* Looks up each byte of the integer in a lookup table.\n *\n * The first time the function is called it initializes the lookup table.\n */\nstatic int _tableBitCount( unsigned int val ) {\n int bCount = 0;\n\n if ( !_lookupTableInitialized ) {\n unsigned int i;\n for ( i = 0; i != UCHAR_MAX + 1; ++i )\n _bitCountTable[i] =\n ( unsigned char )_defaultBitCount( i );\n\n _lookupTableInitialized = 1;\n }\n\n for ( ; val; val >>= CHAR_BIT )\n bCount += _bitCountTable[val & UCHAR_MAX];\n\n return bCount;\n}\n\nstatic int ( *_bitcount ) ( unsigned int ) = _defaultBitCount;\n\nconst char *strategyNames[] = { \"onTheFly\", \"lookupTable\" };\n\nvoid setStrategy( enum strategy s ) {\n switch ( s ) {\n case onTheFly:\n _bitcount = _defaultBitCount;\n break;\n case lookupTable:\n _bitcount = _tableBitCount;\n break;\n case strategyCount:\n break;\n }\n}\n\n/* Just a forwarding function which will call whichever version of the\n * algorithm has been selected by the client \n */\nint bitcount( unsigned int val ) {\n return _bitcount( val );\n}\n\n#ifdef _BITCOUNT_EXE_\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n/* Use the same sequence of pseudo random numbers to benmark each Hamming\n * Weight algorithm.\n */\nvoid benchmark( int reps ) {\n clock_t start, stop;\n int i, j;\n static const int iterations = 1000000;\n\n for ( j = 0; j != strategyCount; ++j ) {\n setStrategy( j );\n\n srand( 257 );\n\n start = clock( );\n\n for ( i = 0; i != reps * iterations; ++i )\n bitcount( rand( ) );\n\n stop = clock( );\n\n printf\n ( \"\\n\\t%d psudoe-random integers using %s: %f seconds\\n\\n\",\n reps * iterations, strategyNames[j],\n ( double )( stop - start ) / CLOCKS_PER_SEC );\n }\n}\n\nint main( void ) {\n int option;\n\n while ( 1 ) {\n printf( \"Menu Options\\n\"\n \"\\t1.\\tPrint the Hamming Weight of an Integer\\n\"\n \"\\t2.\\tBenchmark Hamming Weight implementations\\n\"\n \"\\t3.\\tExit ( or cntl-d )\\n\\n\\t\" );\n\n if ( scanf( \"%d\", &option ) == EOF )\n break;\n\n switch ( option ) {\n case 1:\n printf( \"Please enter the integer: \" );\n if ( scanf( \"%d\", &option ) != EOF )\n printf\n ( \"The Hamming Weight of %d ( 0x%X ) is %d\\n\\n\",\n option, option, bitcount( option ) );\n break;\n case 2:\n printf\n ( \"Please select number of reps ( in millions ): \" );\n if ( scanf( \"%d\", &option ) != EOF )\n benchmark( option );\n break;\n case 3:\n goto EXIT;\n break;\n default:\n printf( \"Invalid option\\n\" );\n }\n\n }\n\n EXIT:\n printf( \"\\n\" );\n\n return 0;\n}\n\n#endif\n" }, { "answer_id": 5646017, "author": "Mostafa", "author_id": 593387, "author_profile": "https://Stackoverflow.com/users/593387", "pm_score": 3, "selected": false, "text": "unsigned int v; // count the number of bits set in v\nunsigned int c; // c accumulates the total bits set in v\n\n// option 1, for at most 14-bit values in v:\nc = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;\n\n// option 2, for at most 24-bit values in v:\nc = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;\nc += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) \n % 0x1f;\n\n// option 3, for at most 32-bit values in v:\nc = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;\nc += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % \n 0x1f;\nc += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;\n" }, { "answer_id": 8144833, "author": "Raymond Chenon", "author_id": 311420, "author_profile": "https://Stackoverflow.com/users/311420", "pm_score": 2, "selected": false, "text": "count public static int bitCount( int n){\n int count = 0;\n for (int i=n; i!=0; i = i >> 1){\n count += i & 1;\n }\n return count;\n}\n" }, { "answer_id": 9426462, "author": "sanjay gopalakrishnan", "author_id": 1230114, "author_profile": "https://Stackoverflow.com/users/1230114", "pm_score": 0, "selected": false, "text": "private static final int[] bitCountArr = new int[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};\nprivate static final int firstByteFF = 255;\npublic static final int getCountOfSetBits(int value){\n int count = 0;\n for(int i=0;i<4;i++){\n if(value == 0) break;\n count += bitCountArr[value & firstByteFF];\n value >>>= 8;\n }\n return count;\n}\n" }, { "answer_id": 9432202, "author": "oxygen", "author_id": 584490, "author_profile": "https://Stackoverflow.com/users/584490", "pm_score": 0, "selected": false, "text": "function bits_population($nInteger)\n{\n\n $nPop=0;\n while($nInteger)\n {\n $nInteger^=(1<<(floor(1+log($nInteger)/log(2))-1));\n $nPop++;\n }\n return $nPop;\n}\n" }, { "answer_id": 10004919, "author": "pentaphobe", "author_id": 679950, "author_profile": "https://Stackoverflow.com/users/679950", "pm_score": 3, "selected": false, "text": "// recursive template to sum bits in an int\ntemplate <int BITS>\nint countBits(int val) {\n // return the least significant bit plus the result of calling ourselves with\n // .. the shifted value\n return (val & 0x1) + countBits<BITS-1>(val >> 1);\n}\n\n// template specialisation to terminate the recursion when there's only one bit left\ntemplate<>\nint countBits<1>(int val) {\n return val & 0x1;\n}\n // to count bits in a byte/char (this returns 8)\ncountBits<8>( 255 )\n\n// another byte (this returns 7)\ncountBits<8>( 254 )\n\n// counting bits in a word/short (this returns 1)\ncountBits<16>( 256 )\n" }, { "answer_id": 10049437, "author": "Jim McCurdy", "author_id": 227695, "author_profile": "https://Stackoverflow.com/users/227695", "pm_score": -1, "selected": false, "text": "// How about the following:\npublic int CountBits(int value)\n{\n int count = 0;\n while (value > 0)\n {\n if (value & 1)\n count++;\n value <<= 1;\n }\n return count;\n}\n" }, { "answer_id": 10326415, "author": "SteveR", "author_id": 1291368, "author_profile": "https://Stackoverflow.com/users/1291368", "pm_score": 2, "selected": false, "text": " public static int myBitCount(long L){\n int count = 0;\n while (L != 0) {\n count++;\n L ^= L & -L; \n }\n return count;\n }\n" }, { "answer_id": 10459753, "author": "Manish Mulani", "author_id": 316419, "author_profile": "https://Stackoverflow.com/users/316419", "pm_score": 3, "selected": false, "text": "int countSetBits(int n) {\n return !n ? 0 : 1 + countSetBits(n & (n-1));\n}\n" }, { "answer_id": 10921350, "author": "dhpant28", "author_id": 1440678, "author_profile": "https://Stackoverflow.com/users/1440678", "pm_score": 0, "selected": false, "text": "#!/user/local/bin/perl\n\n\n $c=0x11BBBBAB;\n $count=0;\n $m=0x00000001;\n for($i=0;$i<32;$i++)\n {\n $f=$c & $m;\n if($f == 1)\n {\n $count++;\n }\n $c=$c >> 1;\n }\n printf(\"%d\",$count);\n\nive done it through a perl script. the number taken is $c=0x11BBBBAB \nB=3 1s \nA=2 1s \nso in total \n1+1+3+3+3+2+3+3=19\n" }, { "answer_id": 11139377, "author": "Green goblin", "author_id": 1347366, "author_profile": "https://Stackoverflow.com/users/1347366", "pm_score": -1, "selected": false, "text": "int countSetBits(int n)\n{\n n=((n&0xAAAAAAAA)>>1) + (n&0x55555555);\n n=((n&0xCCCCCCCC)>>2) + (n&0x33333333);\n n=((n&0xF0F0F0F0)>>4) + (n&0x0F0F0F0F);\n n=((n&0xFF00FF00)>>8) + (n&0x00FF00FF);\n return n;\n}\n\nint main()\n{\n int n=10;\n printf(\"Number of set bits: %d\",countSetBits(n));\n return 0;\n}\n" }, { "answer_id": 11816547, "author": "abcdabcd987", "author_id": 1332817, "author_profile": "https://Stackoverflow.com/users/1332817", "pm_score": 5, "selected": false, "text": "unsigned int count_bit(unsigned int x)\n{\n x = (x & 0x55555555) + ((x >> 1) & 0x55555555);\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333);\n x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);\n x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);\n x = (x & 0x0000FFFF) + ((x >> 16)& 0x0000FFFF);\n return x;\n}\n +-------------------------------+\n| 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | <- x\n| 1 0 | 0 1 | 0 1 | 0 1 | <- first time merge\n| 0 0 1 1 | 0 0 1 0 | <- second time merge\n| 0 0 0 0 0 1 0 1 | <- third time ( answer = 00000101 = 5)\n+-------------------------------+\n" }, { "answer_id": 12974349, "author": "Peter", "author_id": 1759303, "author_profile": "https://Stackoverflow.com/users/1759303", "pm_score": 4, "selected": false, "text": "unsigned int f(unsigned int x)\n{\n switch (x) {\n case 0:\n return 0;\n case 1:\n return 1;\n case 2:\n return 1;\n case 3:\n return 2;\n default:\n return f(x/4) + f(x%4);\n }\n}\n" }, { "answer_id": 15979139, "author": "vidit", "author_id": 962111, "author_profile": "https://Stackoverflow.com/users/962111", "pm_score": 6, "selected": false, "text": "int popcount(int v) {\n v = v - ((v >> 1) & 0x55555555); // put count of each 2 bits into those 2 bits\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // put count of each 4 bits into those 4 bits \n return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;\n}\n Divide and Conquer v = v - ((v >> 1) & 0x55555555); \n 0b00 0b01 0b10 ---------------------------------------------\n | v | (v >> 1) & 0b0101 | v - x |\n ---------------------------------------------\n 0b00 0b00 0b00 \n 0b01 0b00 0b01 \n 0b10 0b01 0b01\n 0b11 0b01 0b10\n >= 2 (0b10) and 0b01 0b00 v = (v & 0x33333333) + ((v >> 2) & 0x33333333); \n v & 0b00110011 //masks out even two bits\n(v >> 2) & 0b00110011 // masks out odd two bits\n c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;\n v + (v >> 4)\n 0b01000010 v = 0b01000010\n(v >> 4) = 0b00000100\nv + (v >> 4) = 0b01000010 + 0b00000100\n 0b01000110 0b01000110 & 0x0F = 0b00000110\n 0b10101010 A B C D A+B+C+D B+C+D C+D D 0b00100000 >> 24 32 bit 64 bit" }, { "answer_id": 16809972, "author": "prongs", "author_id": 459384, "author_profile": "https://Stackoverflow.com/users/459384", "pm_score": -1, "selected": false, "text": "int msb(int num)\n{\n int m = 0;\n for (int i = 16; i > 0; i = i>>1)\n {\n // debug(i, num, m);\n if(num>>i)\n {\n m += i;\n num>>=i;\n }\n }\n return m;\n}\n" }, { "answer_id": 20230136, "author": "Stefan", "author_id": 1209253, "author_profile": "https://Stackoverflow.com/users/1209253", "pm_score": 1, "selected": false, "text": "gcc -O3 #include <stdio.h>\n#include <stdlib.h>\n\n#define LENGTH 100000000\n\ntypedef struct {\n unsigned char bit0 : 1;\n unsigned char bit1 : 1;\n unsigned char bit2 : 1;\n unsigned char bit3 : 1;\n unsigned char bit4 : 1;\n unsigned char bit5 : 1;\n unsigned char bit6 : 1;\n unsigned char bit7 : 1;\n} bits;\n\nunsigned char sum_bits(const unsigned char x) {\n const bits *b = (const bits*) &x;\n return b->bit0 + b->bit1 + b->bit2 + b->bit3 \\\n + b->bit4 + b->bit5 + b->bit6 + b->bit7;\n}\n\nint NumberOfSetBits(int i) {\n i = i - ((i >> 1) & 0x55555555);\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n}\n\n#define out(s) \\\n printf(\"bits set: %lu\\nbits counted: %lu\\n\", 8*LENGTH*sizeof(short)*3/4, s);\n\nint main(int argc, char **argv) {\n unsigned long i, s;\n unsigned short *x = malloc(LENGTH*sizeof(short));\n unsigned char lut[65536], *p;\n unsigned short *ps;\n int *pi;\n\n /* set 3/4 of the bits */\n for (i=0; i<LENGTH; ++i)\n x[i] = 0xFFF0;\n\n /* sum_bits (1.772s) */\n for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=sum_bits(*p++));\n out(s);\n\n /* NumberOfSetBits (0.404s) */\n for (i=LENGTH*sizeof(short)/sizeof(int), pi=(int*)x, s=0; i--; s+=NumberOfSetBits(*pi++));\n out(s);\n\n /* populate lookup table */\n for (i=0, p=(unsigned char*) &i; i<sizeof(lut); ++i)\n lut[i] = sum_bits(p[0]) + sum_bits(p[1]);\n\n /* 256-bytes lookup table (0.317s) */\n for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=lut[*p++]);\n out(s);\n\n /* 65536-bytes lookup table (0.250s) */\n for (i=LENGTH, ps=x, s=0; i--; s+=lut[*ps++]);\n out(s);\n\n free(x);\n return 0;\n}\n NumberOfSetBits()" }, { "answer_id": 20697993, "author": "John Dimm", "author_id": 1976377, "author_profile": "https://Stackoverflow.com/users/1976377", "pm_score": 5, "selected": false, "text": "unsigned int bitCount(unsigned int x)\n{\n x = ((x >> 1) & 0b01010101010101010101010101010101)\n + (x & 0b01010101010101010101010101010101);\n x = ((x >> 2) & 0b00110011001100110011001100110011)\n + (x & 0b00110011001100110011001100110011); \n x = ((x >> 4) & 0b00001111000011110000111100001111)\n + (x & 0b00001111000011110000111100001111); \n x = ((x >> 8) & 0b00000000111111110000000011111111)\n + (x & 0b00000000111111110000000011111111); \n x = ((x >> 16)& 0b00000000000000001111111111111111)\n + (x & 0b00000000000000001111111111111111); \n return x;\n}\n" }, { "answer_id": 21114060, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 4, "selected": false, "text": "O(k) k int NumberOfSetBits(int n)\n{\n int count = 0;\n\n while (n){\n ++ count;\n n = (n - 1) & n;\n }\n\n return count;\n}\n" }, { "answer_id": 21455308, "author": "dadhi", "author_id": 2492669, "author_profile": "https://Stackoverflow.com/users/2492669", "pm_score": 3, "selected": false, "text": "public static class BitCount\n{\n public static uint GetSetBitsCount(uint n)\n {\n var counts = BYTE_BIT_COUNTS;\n return n <= 0xff ? counts[n]\n : n <= 0xffff ? counts[n & 0xff] + counts[n >> 8]\n : n <= 0xffffff ? counts[n & 0xff] + counts[(n >> 8) & 0xff] + counts[(n >> 16) & 0xff]\n : counts[n & 0xff] + counts[(n >> 8) & 0xff] + counts[(n >> 16) & 0xff] + counts[(n >> 24) & 0xff];\n }\n\n public static readonly uint[] BYTE_BIT_COUNTS =\n {\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8\n };\n}\n" }, { "answer_id": 24099386, "author": "Mufaddal Kagda", "author_id": 1925185, "author_profile": "https://Stackoverflow.com/users/1925185", "pm_score": 1, "selected": false, "text": "int bitcount(unsigned int n)\n{ \n int count=0;\n while(n)\n {\n count += n & 0x1u;\n n >>= 1;\n }\n return count;\n }\n" }, { "answer_id": 27853048, "author": "Nikhil Katre", "author_id": 3030376, "author_profile": "https://Stackoverflow.com/users/3030376", "pm_score": -1, "selected": false, "text": "package countSetBitsInAnInteger;\n\nimport java.util.Scanner;\n\npublic class UsingLoop {\n\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n try {\n System.out.println(\"Enter a integer number to check for set bits in it\");\n int n = in.nextInt();\n System.out.println(\"Using while loop, we get the number of set bits as: \" + usingLoop(n));\n System.out.println(\"Using Brain Kernighan's Algorithm, we get the number of set bits as: \" + usingBrainKernighan(n));\n System.out.println(\"Using \");\n }\n finally {\n in.close();\n }\n }\n\n private static int usingBrainKernighan(int n) {\n int count = 0;\n while(n > 0) {\n n& = (n-1);\n count++;\n }\n return count;\n }\n\n /*\n Analysis:\n Time complexity = O(lgn)\n Space complexity = O(1)\n */\n\n private static int usingLoop(int n) {\n int count = 0;\n for(int i=0; i<32; i++) {\n if((n&(1 << i)) != 0)\n count++;\n }\n return count;\n }\n\n /*\n Analysis:\n Time Complexity = O(32) // Maybe the complexity is O(lgn)\n Space Complexity = O(1)\n */\n}\n" }, { "answer_id": 28469209, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 2, "selected": false, "text": "int countBits(int x)\n{\n int n = 0;\n if (x) do n++;\n while(x=x&(x-1));\n return n;\n} \n int countBits(int x) { return (x)? 1+countBits(x&(x-1)): 0; }\n #include <stdio.h>\nint countBits(int x)\n{\n int n = 0;\n if (x) do n++; /* Totally Normal Valid code. */\n while(x=x&(x-1)); /* Nothing to see here. */\n return n;\n} \n \nint main(void) {\n printf(\"%d\\n\", countBits(25));\n return 0;\n}\n \n 3\n if (x)\n{\n do\n {\n n++;\n } while(x=x&(x-1));\n}\n int countBits(int x)\n{\n int n = 0;\n while (x) x=(n++,x&(x-1));\n return n;\n} \n" }, { "answer_id": 32787654, "author": "Burhan ARAS", "author_id": 1149401, "author_profile": "https://Stackoverflow.com/users/1149401", "pm_score": -1, "selected": false, "text": "public class BinaryCounter {\n\nprivate int N;\n\npublic BinaryCounter(int N) {\n this.N = N;\n}\n\npublic static void main(String[] args) {\n\n BinaryCounter counter=new BinaryCounter(7); \n System.out.println(\"Number of ones is \"+ counter.count());\n\n}\n\npublic int count(){\n if(N<=0) return 0;\n int counter=0;\n int K = 0;\n do{\n K = biggestPowerOfTwoSmallerThan(N);\n N = N-K;\n counter++;\n }while (N != 0);\n return counter;\n\n}\n\nprivate int biggestPowerOfTwoSmallerThan(int N) {\n if(N==1) return 1;\n for(int i=0;i<N;i++){\n if(Math.pow(2, i) > N){\n int power = i-1;\n return (int) Math.pow(2, power);\n }\n }\n return 0;\n}\n}\n" }, { "answer_id": 33791923, "author": "Anders Cedronius", "author_id": 2353816, "author_profile": "https://Stackoverflow.com/users/2353816", "pm_score": 1, "selected": false, "text": "the_weight = __tzcnt_u64(~_pext_u64(data[i], data[i]));\n" }, { "answer_id": 35200163, "author": "KeineKaefer", "author_id": 1684019, "author_profile": "https://Stackoverflow.com/users/1684019", "pm_score": 0, "selected": false, "text": "substr_count(decbin($integer), '1');\n" }, { "answer_id": 35412017, "author": "ErmIg", "author_id": 2831104, "author_profile": "https://Stackoverflow.com/users/2831104", "pm_score": 3, "selected": false, "text": "#include <smmintrin.h>\n#include <stdint.h>\n\nconst __m128i Z = _mm_set1_epi8(0x0);\nconst __m128i F = _mm_set1_epi8(0xF);\n//Vector with pre-calculated bit count:\nconst __m128i T = _mm_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);\n\nuint64_t BitCount(const uint8_t * src, size_t size)\n{\n __m128i _sum = _mm128_setzero_si128();\n for (size_t i = 0; i < size; i += 16)\n {\n //load 16-byte vector\n __m128i _src = _mm_loadu_si128((__m128i*)(src + i));\n //get low 4 bit for every byte in vector\n __m128i lo = _mm_and_si128(_src, F);\n //sum precalculated value from T\n _sum = _mm_add_epi64(_sum, _mm_sad_epu8(Z, _mm_shuffle_epi8(T, lo)));\n //get high 4 bit for every byte in vector\n __m128i hi = _mm_and_si128(_mm_srli_epi16(_src, 4), F);\n //sum precalculated value from T\n _sum = _mm_add_epi64(_sum, _mm_sad_epu8(Z, _mm_shuffle_epi8(T, hi)));\n }\n uint64_t sum[2];\n _mm_storeu_si128((__m128i*)sum, _sum);\n return sum[0] + sum[1];\n}\n #include <immintrin.h>\n#include <stdint.h>\n\nconst __m256i Z = _mm256_set1_epi8(0x0);\nconst __m256i F = _mm256_set1_epi8(0xF);\n//Vector with pre-calculated bit count:\nconst __m256i T = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, \n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);\n\nuint64_t BitCount(const uint8_t * src, size_t size)\n{\n __m256i _sum = _mm256_setzero_si256();\n for (size_t i = 0; i < size; i += 32)\n {\n //load 32-byte vector\n __m256i _src = _mm256_loadu_si256((__m256i*)(src + i));\n //get low 4 bit for every byte in vector\n __m256i lo = _mm256_and_si256(_src, F);\n //sum precalculated value from T\n _sum = _mm256_add_epi64(_sum, _mm256_sad_epu8(Z, _mm256_shuffle_epi8(T, lo)));\n //get high 4 bit for every byte in vector\n __m256i hi = _mm256_and_si256(_mm256_srli_epi16(_src, 4), F);\n //sum precalculated value from T\n _sum = _mm256_add_epi64(_sum, _mm256_sad_epu8(Z, _mm256_shuffle_epi8(T, hi)));\n }\n uint64_t sum[4];\n _mm256_storeu_si256((__m256i*)sum, _sum);\n return sum[0] + sum[1] + sum[2] + sum[3];\n}\n" }, { "answer_id": 37558380, "author": "Erorr", "author_id": 4686763, "author_profile": "https://Stackoverflow.com/users/4686763", "pm_score": 4, "selected": false, "text": "int countSetBits(unsigned int n) { \n unsigned int n; // count the number of bits set in n\n unsigned int c; // c accumulates the total bits set in n\n for (c=0;n>0;n=n&(n-1)) c++; \n return c; \n}\n" }, { "answer_id": 39861725, "author": "Jonatan Kaźmierczak", "author_id": 1131188, "author_profile": "https://Stackoverflow.com/users/1131188", "pm_score": 1, "selected": false, "text": "Integer.bitCount" }, { "answer_id": 40411172, "author": "iamdeit", "author_id": 4830460, "author_profile": "https://Stackoverflow.com/users/4830460", "pm_score": 3, "selected": false, "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint countOnes(int n) {\n bitset<32> b(n);\n return b.count();\n}\n" }, { "answer_id": 44566978, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 1, "selected": false, "text": "int __builtin_popcount (unsigned int x);\n" }, { "answer_id": 44981129, "author": "cipilo", "author_id": 8272794, "author_profile": "https://Stackoverflow.com/users/8272794", "pm_score": 0, "selected": false, "text": "int nbits(unsigned char v) {\n return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;\n}\n" }, { "answer_id": 45846017, "author": "Varun Gusain", "author_id": 7113494, "author_profile": "https://Stackoverflow.com/users/7113494", "pm_score": 3, "selected": false, "text": "while(n){\n n = n & (n-1);\n count++;\n}\n &" }, { "answer_id": 47182710, "author": "stacktay", "author_id": 6858149, "author_profile": "https://Stackoverflow.com/users/6858149", "pm_score": 3, "selected": false, "text": "private int get_bits_set(int v)\n{\n int c; // 'c' accumulates the total bits set in 'v'\n for (c = 0; v>0; c++)\n {\n v &= v - 1; // Clear the least significant bit set\n }\n return c;\n}\n" }, { "answer_id": 48731845, "author": "decrypto", "author_id": 7488288, "author_profile": "https://Stackoverflow.com/users/7488288", "pm_score": -1, "selected": false, "text": "int ans = 0;\nwhile(num) {\n ans += (num & 1);\n num = num >> 1;\n} \nreturn ans;\n" }, { "answer_id": 56481445, "author": "Arjun Singh", "author_id": 10389478, "author_profile": "https://Stackoverflow.com/users/10389478", "pm_score": 0, "selected": false, "text": "int countbits(n) {\n int count = 0;\n while(n != 0) {\n n = n & (n-1);\n count++;\n }\n return count;\n}\n" }, { "answer_id": 57285674, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "std::popcount <bit> #include <bit>\n#include <iostream>\n\nint main() {\n std::cout << std::popcount(0x55) << std::endl;\n}\n g++-9 -std=c++2a <bit> namespace std {\n\n // 25.5.6, counting\n template<class T>\n constexpr int popcount(T x) noexcept;\n template<class T>\n constexpr int popcount(T x) noexcept;\n std::rotl std::rotr" }, { "answer_id": 57650036, "author": "Bamidele Alegbe", "author_id": 4934096, "author_profile": "https://Stackoverflow.com/users/4934096", "pm_score": -1, "selected": false, "text": "func CountBitSet(n int) int {\n\n\n count := 0\n for n > 0 {\n count += n & 1\n n >>= 1\n\n }\n return count\n}\n" }, { "answer_id": 60796828, "author": "Shyambeer Singh", "author_id": 1442015, "author_profile": "https://Stackoverflow.com/users/1442015", "pm_score": 0, "selected": false, "text": "def hammingWeight(n):\n count = 0\n while n:\n if n&1:\n count += 1\n n >>= 1\n return count\n" }, { "answer_id": 63889264, "author": "Boštjan Mejak", "author_id": 7771315, "author_profile": "https://Stackoverflow.com/users/7771315", "pm_score": 1, "selected": false, "text": "int.bit_count() def bit_count(integer):\n return bin(integer).count(\"1\")\n" }, { "answer_id": 64391462, "author": "monoceres", "author_id": 242348, "author_profile": "https://Stackoverflow.com/users/242348", "pm_score": 0, "selected": false, "text": "template<typename T>\nint popcnt(T n)\n{\n if (n>0)\n return n&1 + popcnt(n>>1);\n return 0; \n}\n" }, { "answer_id": 65121086, "author": "Steven Chou", "author_id": 2971851, "author_profile": "https://Stackoverflow.com/users/2971851", "pm_score": 0, "selected": false, "text": "java.util.BitSet" }, { "answer_id": 66086390, "author": "Jerry An", "author_id": 10153574, "author_profile": "https://Stackoverflow.com/users/10153574", "pm_score": 2, "selected": false, "text": "def hammingWeight(n: int) -> int:\n sums = 0\n while (n!=0):\n sums+=1\n n = n &(n-1)\n\n return sums\n" }, { "answer_id": 67185779, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 1, "selected": false, "text": "#include <type_traits>\n#include <cstdint>\n\ntemplate <typename IntT>\ninline size_t PopCntParallel(IntT n) {\n // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n using T = std::make_unsigned_t<IntT>;\n\n T v = T(n);\n v = v - ((v >> 1) & (T)~(T)0/3); // temp\n v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp\n v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp\n return size_t((T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8); // count\n}\n template <typename IntT>\ninline size_t PopCntKernighan(IntT n) {\n // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan\n using T = std::make_unsigned_t<IntT>;\n T v = T(n);\n size_t c;\n for (c = 0; v; ++c)\n v &= v - 1; // Clear the least significant bit set\n return c;\n}\n __popcnt16() __popcnt() __popcnt64() __builtin_popcount #ifdef _MSC_VER\n // https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-160\n #include <intrin.h>\n #define popcnt16 __popcnt16\n #define popcnt32 __popcnt\n #define popcnt64 __popcnt64\n#else\n // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\n #define popcnt16 __builtin_popcount\n #define popcnt32 __builtin_popcount\n #define popcnt64 __builtin_popcountll\n#endif\n\ntemplate <typename IntT>\ninline size_t PopCntBuiltin(IntT n) {\n using T = std::make_unsigned_t<IntT>;\n T v = T(n);\n if constexpr(sizeof(IntT) <= 2)\n return popcnt16(uint16_t(v));\n else if constexpr(sizeof(IntT) <= 4)\n return popcnt32(uint32_t(v));\n else if constexpr(sizeof(IntT) <= 8)\n return popcnt64(uint64_t(v));\n else\n static_assert([]{ return false; }());\n}\n 08 bit Builtin 8.2 ns\n08 bit Parallel 8.2 ns\n08 bit Kernighan 26.7 ns\n\n16 bit Builtin 7.7 ns\n16 bit Parallel 7.7 ns\n16 bit Kernighan 39.7 ns\n\n32 bit Builtin 7.0 ns\n32 bit Parallel 7.0 ns\n32 bit Kernighan 47.9 ns\n\n64 bit Builtin 7.5 ns\n64 bit Parallel 7.5 ns\n64 bit Kernighan 59.4 ns\n\n128 bit Builtin 7.8 ns\n128 bit Parallel 13.8 ns\n128 bit Kernighan 127.6 ns\n unsigned __int128 #include <type_traits>\n#include <cstdint>\n\nusing std::size_t;\n\n#if defined(_MSC_VER) && !defined(__clang__)\n #define IS_MSVC 1\n#else\n #define IS_MSVC 0\n#endif\n\n#if IS_MSVC\n #define HAS128 false\n#else\n using int128_t = __int128;\n using uint128_t = unsigned __int128;\n #define HAS128 true\n#endif\n\ntemplate <typename T> struct UnSignedT { using type = std::make_unsigned_t<T>; };\n#if HAS128\n template <> struct UnSignedT<int128_t> { using type = uint128_t; };\n template <> struct UnSignedT<uint128_t> { using type = uint128_t; };\n#endif\ntemplate <typename T> using UnSigned = typename UnSignedT<T>::type;\n\ntemplate <typename IntT>\ninline size_t PopCntParallel(IntT n) {\n // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n using T = UnSigned<IntT>;\n\n T v = T(n);\n v = v - ((v >> 1) & (T)~(T)0/3); // temp\n v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp\n v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp\n return size_t((T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8); // count\n}\n\ntemplate <typename IntT>\ninline size_t PopCntKernighan(IntT n) {\n // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan\n using T = UnSigned<IntT>;\n T v = T(n);\n size_t c;\n for (c = 0; v; ++c)\n v &= v - 1; // Clear the least significant bit set\n return c;\n}\n\n#if IS_MSVC\n // https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-160\n #include <intrin.h>\n #define popcnt16 __popcnt16\n #define popcnt32 __popcnt\n #define popcnt64 __popcnt64\n#else\n // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\n #define popcnt16 __builtin_popcount\n #define popcnt32 __builtin_popcount\n #define popcnt64 __builtin_popcountll\n#endif\n\n#define popcnt128(x) (popcnt64(uint64_t(x)) + popcnt64(uint64_t(x >> 64)))\n\ntemplate <typename IntT>\ninline size_t PopCntBuiltin(IntT n) {\n using T = UnSigned<IntT>;\n T v = T(n);\n if constexpr(sizeof(IntT) <= 2)\n return popcnt16(uint16_t(v));\n else if constexpr(sizeof(IntT) <= 4)\n return popcnt32(uint32_t(v));\n else if constexpr(sizeof(IntT) <= 8)\n return popcnt64(uint64_t(v));\n else if constexpr(sizeof(IntT) <= 16)\n return popcnt128(uint128_t(v));\n else\n static_assert([]{ return false; }());\n}\n\n#include <random>\n#include <vector>\n#include <chrono>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <map>\n\ninline double Time() {\n static auto const gtb = std::chrono::high_resolution_clock::now();\n return std::chrono::duration_cast<std::chrono::duration<double>>(\n std::chrono::high_resolution_clock::now() - gtb).count();\n}\n\ntemplate <typename T, typename F>\nvoid Test(std::string const & name, F f) {\n std::mt19937_64 rng{123};\n size_t constexpr bit_size = sizeof(T) * 8, ntests = 1 << 6, nnums = 1 << 14;\n std::vector<T> nums(nnums);\n for (size_t i = 0; i < nnums; ++i)\n nums[i] = T(rng() % ~T(0));\n static std::map<size_t, size_t> times;\n double min_time = 1000;\n for (size_t i = 0; i < ntests; ++i) {\n double timer = Time();\n size_t sum = 0;\n for (size_t j = 0; j < nnums; j += 4)\n sum += f(nums[j + 0]) + f(nums[j + 1]) + f(nums[j + 2]) + f(nums[j + 3]);\n auto volatile vsum = sum;\n min_time = std::min(min_time, (Time() - timer) / nnums);\n if (times.count(bit_size) && times.at(bit_size) != sum)\n std::cout << \"Wrong bit cnt checksum!\" << std::endl;\n times[bit_size] = sum;\n }\n std::cout << std::setw(2) << std::setfill('0') << bit_size\n << \" bit \" << name << \" \" << std::fixed << std::setprecision(1)\n << min_time * 1000000000 << \" ns\" << std::endl;\n}\n\nint main() {\n #define TEST(T) \\\n Test<T>(\"Builtin\", PopCntBuiltin<T>); \\\n Test<T>(\"Parallel\", PopCntParallel<T>); \\\n Test<T>(\"Kernighan\", PopCntKernighan<T>); \\\n std::cout << std::endl;\n \n TEST(uint8_t); TEST(uint16_t); TEST(uint32_t); TEST(uint64_t);\n #if HAS128\n TEST(uint128_t);\n #endif\n \n #undef TEST\n}\n" }, { "answer_id": 67410903, "author": "Jfm Meyers", "author_id": 6499953, "author_profile": "https://Stackoverflow.com/users/6499953", "pm_score": 0, "selected": false, "text": " fun NumberOfSetBits(i: Int): Int {\n var i = i\n i -= (i ushr 1 and 0x55555555)\n i = (i and 0x33333333) + (i ushr 2 and 0x33333333)\n return (i + (i ushr 4) and 0x0F0F0F0F) * 0x01010101 ushr 24\n }\n fun NumberOfSetBits(i: Int): Int {\n return i.countOneBits()\n }\n Integer.bitCount @SinceKotlin(\"1.4\")\n@WasExperimental(ExperimentalStdlibApi::class)\n@kotlin.internal.InlineOnly\npublic actual inline fun Int.countOneBits(): Int = Integer.bitCount(this)\n\n" }, { "answer_id": 67619076, "author": "Amisha Sahu", "author_id": 14651946, "author_profile": "https://Stackoverflow.com/users/14651946", "pm_score": 2, "selected": false, "text": "int countSet(unsigned int n)\n{\n int res=0;\n while(n!=0){\n res += (n&1);\n n >>= 1; // logical right shift, like C unsigned or Java >>>\n }\n return res;\n}\n int countSet(unsigned int n)\n{\n int res=0;\n while(n != 0)\n {\n n = (n & (n-1));\n res++;\n }\n return res;\n} \n static unsigned char table[256]; /* the table size is 256,\n the number of values i&0xFF (8 bits) can have */\n\nvoid initialize() //holds the number of set bits from 0 to 255\n{\n table[0]=0;\n for(unsigned int i=1;i<256;i++)\n table[i]=(i&1)+table[i>>1];\n}\n\nint countSet(unsigned int n)\n{\n // 0xff is hexadecimal representation of 8 set bits.\n int res=table[n & 0xff];\n n=n>>8;\n res=res+ table[n & 0xff];\n n=n>>8;\n res=res+ table[n & 0xff];\n n=n>>8;\n res=res+ table[n & 0xff];\n return res;\n}\n" }, { "answer_id": 70767495, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 0, "selected": false, "text": "#include <stdint.h>\n#include <limits>\n#include <type_traits>\n\nconst constexpr uint32_t uint32_max = (std::numeric_limits<uint32_t>::max)();\n\nnamespace detail\n{\n template <typename T>\n inline constexpr T _count_bits_0(const T & v)\n {\n return v - ((v >> 1) & 0x55555555);\n }\n\n template <typename T>\n inline constexpr T _count_bits_1(const T & v)\n {\n return (v & 0x33333333) + ((v >> 2) & 0x33333333);\n }\n\n template <typename T>\n inline constexpr T _count_bits_2(const T & v)\n {\n return (v + (v >> 4)) & 0x0F0F0F0F;\n }\n\n template <typename T>\n inline constexpr T _count_bits_3(const T & v)\n {\n return v + (v >> 8);\n }\n\n template <typename T>\n inline constexpr T _count_bits_4(const T & v)\n {\n return v + (v >> 16);\n }\n\n template <typename T>\n inline constexpr T _count_bits_5(const T & v)\n {\n return v & 0x0000003F;\n }\n\n template <typename T, bool greater_than_uint32>\n struct _impl\n {\n static inline constexpr T _count_bits_with_shift(const T & v)\n {\n return\n detail::_count_bits_5(\n detail::_count_bits_4(\n detail::_count_bits_3(\n detail::_count_bits_2(\n detail::_count_bits_1(\n detail::_count_bits_0(v)))))) + count_bits(v >> 32);\n }\n };\n\n template <typename T>\n struct _impl<T, false>\n {\n static inline constexpr T _count_bits_with_shift(const T & v)\n {\n return 0;\n }\n };\n}\n\ntemplate <typename T>\ninline constexpr T count_bits(const T & v)\n{\n static_assert(std::is_integral<T>::value, \"type T must be an integer\");\n static_assert(!std::is_signed<T>::value, \"type T must be not signed\");\n\n return uint32_max >= v ?\n detail::_count_bits_5(\n detail::_count_bits_4(\n detail::_count_bits_3(\n detail::_count_bits_2(\n detail::_count_bits_1(\n detail::_count_bits_0(v)))))) :\n detail::_impl<T, sizeof(uint32_t) < sizeof(v)>::_count_bits_with_shift(v);\n}\n #include <stdlib.h>\n#include <time.h>\n\nnamespace {\n template <typename T>\n inline uint32_t _test_count_bits(const T & v)\n {\n uint32_t count = 0;\n T n = v;\n while (n > 0) {\n if (n % 2) {\n count += 1;\n }\n n /= 2;\n }\n return count;\n }\n}\n\nTEST(FunctionsTest, random_count_bits_uint32_100K)\n{\n srand(uint_t(time(NULL)));\n for (uint32_t i = 0; i < 100000; i++) {\n const uint32_t r = uint32_t(rand()) + (uint32_t(rand()) << 16);\n ASSERT_EQ(_test_count_bits(r), count_bits(r));\n }\n}\n\nTEST(FunctionsTest, random_count_bits_uint64_100K)\n{\n srand(uint_t(time(NULL)));\n for (uint32_t i = 0; i < 100000; i++) {\n const uint64_t r = uint64_t(rand()) + (uint64_t(rand()) << 16) + (uint64_t(rand()) << 32) + (uint64_t(rand()) << 48);\n ASSERT_EQ(_test_count_bits(r), count_bits(r));\n }\n}\n" }, { "answer_id": 70898893, "author": "Mayukh Pankaj", "author_id": 16168153, "author_profile": "https://Stackoverflow.com/users/16168153", "pm_score": 0, "selected": false, "text": "int countSetBits(unsigned int n){\n\nint count = 0;\n\nwhile(n!=0){\n\n count += n&1;\n\n n = n >>1;\n}\n\n return count;\n\n}\n int main(){\n\n int x = 5;\n cout<<countSetBits(x);\n\n return 0;\n}\n" }, { "answer_id": 71935909, "author": "Lance", "author_id": 169992, "author_profile": "https://Stackoverflow.com/users/169992", "pm_score": -1, "selected": false, "text": "const COUNT_BITS_TABLE = makeLookupTable()\n\nfunction makeLookupTable() {\n const table = new Uint8Array(256)\n for (let i = 0; i < 256; i++) {\n table[i] = (i & 1) + table[(i / 2) | 0];\n }\n return table\n}\n\nfunction countOneBits32(n) {\n return COUNT_BITS_TABLE[n & 0xff] +\n COUNT_BITS_TABLE[(n >> 8) & 0xff] +\n COUNT_BITS_TABLE[(n >> 16) & 0xff] +\n COUNT_BITS_TABLE[(n >> 24) & 0xff];\n}\n\nfunction countOneBits16(n) {\n return COUNT_BITS_TABLE[n & 0xff] +\n COUNT_BITS_TABLE[(n >> 8) & 0xff]\n}\n\nfunction countOneBits8(n) {\n return COUNT_BITS_TABLE[n & 0xff]\n}\n\nconsole.log('countOneBits32', countOneBits32(0b10101010000000001010101000000000))\nconsole.log('countOneBits32', countOneBits32(0b10101011110000001010101000000000))\nconsole.log('countOneBits16', countOneBits16(0b1010101000000000))\nconsole.log('countOneBits8', countOneBits8(0b10000010))" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
109,027
<p>I need to display many pages of news in a site. Should I do the pagination in the database query using <code>LIMIT</code> or with the PHP script after getting all the results?</p>
[ { "answer_id": 421587, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 1, "selected": false, "text": "LIMIT WHERE --- First page (showing first 50 records)\nSELECT * FROM people ORDER BY id LIMIT 50\n--- Second page\nSELECT * FROM people WHERE id > 50 ORDER BY id LIMIT 50\n WHERE LIMIT LIMIT 50,50" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13116/" ]
109,032
<p>I have a <strong>RichTextBox</strong> control on my form. I also have this button, labeled <strong>Bold</strong>, that I want, if someone selects text in the <strong>RichTextBox</strong>, then presses the button, <strong>the selected text turns bold.</strong> Any way to do that? Simple, everyday task for end users. Thanks.</p>
[ { "answer_id": 421587, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 1, "selected": false, "text": "LIMIT WHERE --- First page (showing first 50 records)\nSELECT * FROM people ORDER BY id LIMIT 50\n--- Second page\nSELECT * FROM people WHERE id > 50 ORDER BY id LIMIT 50\n WHERE LIMIT LIMIT 50,50" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,064
<p>Could you recommend me a way to place a coundown timer on ASP.NET page?</p> <p>Now I use this code:</p> <p><strong>Default.aspx</strong></p> <pre><code>&lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:Label ID="Label1" runat="server"&gt;60&lt;/asp:Label&gt; &lt;asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"&gt; &lt;/asp:Timer&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p><strong>Default.aspx.cs</strong></p> <pre><code>protected void Timer1_Tick(object sender, EventArgs e) { int seconds = int.Parse(Label1.Text); if (seconds &gt; 0) Label1.Text = (seconds - 1).ToString(); else Timer1.Enabled = false; } </code></pre> <p>But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET? </p>
[ { "answer_id": 109096, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<form name=\"counter\"><input type=\"text\" size=\"8\" \nname=\"d2\"></form> \n\n<script> \n<!-- \n// \n var milisec=0 \n var seconds=30 \n document.counter.d2.value='30' \n\nfunction display(){ \n if (milisec<=0){ \n milisec=9 \n seconds-=1 \n } \n if (seconds<=-1){ \n milisec=0 \n seconds+=1 \n } \n else \n milisec-=1 \n document.counter.d2.value=seconds+\".\"+milisec \n setTimeout(\"display()\",100) \n} \ndisplay() \n--> \n</script> \n" }, { "answer_id": 111002, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": true, "text": "<span id=\"timerLabel\" runat=\"server\"></span>\n\n<script type=\"text/javascript\">\n\n function countdown() \n {\n seconds = document.getElementById(\"timerLabel\").innerHTML;\n if (seconds > 0) \n {\n document.getElementById(\"timerLabel\").innerHTML = seconds - 1;\n setTimeout(\"countdown()\", 1000);\n }\n }\n\n setTimeout(\"countdown()\", 1000);\n\n</script>\n" }, { "answer_id": 3492283, "author": "rakesh", "author_id": 421610, "author_profile": "https://Stackoverflow.com/users/421610", "pm_score": 1, "selected": false, "text": "var sec=0 ;\n var min=0;\nvar hour=0;\nvar t;\n\nfunction display(){ \n if (sec<=0){ \n sec+=1;\n } \nif(sec==60)\n{\nsec=0;\nmin+=1;\n}\nif(min==60){\nhour+=1;\nmin=0;\n}\n\n if (min<=-1){ \n sec=0; \n min+=1;\n } \n\n else \n sec+=1 ;\ndocument.getElementById(\"<%=TextBox1.ClientID%>\").value=hour+\":\"+min+\":\"+sec;\n t=setTimeout(\"display()\",1000);\n }\nwindow.onload=display; \n" }, { "answer_id": 5014096, "author": "user554151", "author_id": 554151, "author_profile": "https://Stackoverflow.com/users/554151", "pm_score": 2, "selected": false, "text": "time1 = (DateTime)ViewState[\"time\"] - DateTime.Now;\n\nif (time1.TotalSeconds <= 0)\n{\n Label1.Text = Label2.Text = \"TimeOut!\"; \n}\nelse\n{\n if (time1.TotalMinutes > 59)\n {\n Label1.Text = Label2.Text = string.Format(\"{0}:{1:D2}:{2:D2}\",\n time1.Hours,\n time1.Minutes,\n time1.Seconds);\n }\n else\n {\n Label1.Text = Label2.Text = string.Format(\"{0:D2}:{1:D2}\", \n time1.Minutes,\n time1.Seconds);\n }\n}\n" }, { "answer_id": 8153199, "author": "Casselj", "author_id": 1049861, "author_profile": "https://Stackoverflow.com/users/1049861", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n var sec = 10;\n var min = 0\n var hour = 0;\n var t;\n\n function display() {\n sec -= 1\n if ((sec == 0) && (min == 0) && (hour == 0)) {\n //if a popup window is used:\n setTimeout(\"self.close()\", 1000);\n return;\n }\n if (sec < 0) {\n sec = 59;\n min -= 1;\n }\n if (min < 0) {\n min = 59;\n hour -= 1;\n }\n else\n document.getElementById(\"<%=TextBox1.ClientID%>\").value = hour + \":\" + min + \":\" + sec;\n t = setTimeout(\"display()\", 1000);\n }\n window.onload = display; \n</script>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
109,066
<p>I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.</p> <p>See answers for the link</p>
[ { "answer_id": 109067, "author": "Eliram", "author_id": 18790, "author_profile": "https://Stackoverflow.com/users/18790", "pm_score": 1, "selected": false, "text": "var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;\n" }, { "answer_id": 132047, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": true, "text": "package {\n import flash.display.Sprite;\n\n public class Main extends Sprite {\n\n public function Main() {\n var test1:String = '';\n\n if (this.loaderInfo.parameters.test1 !== undefined) {\n test1 = this.loaderInfo.parameters.test1;\n }\n }\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18790/" ]
109,072
<p>Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.</p> <p>I know the .NET framework <a href="http://weblogs.asp.net/astopford/archive/2008/08/25/mbunit-typefixture.aspx" rel="nofollow noreferrer">mbUnit</a> has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).</p> <p><strong>Clarification:</strong> I could definitely build something like this. I was asking if there was anything out there that already enabled this.</p>
[ { "answer_id": 109132, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "ITargetInterface" }, { "answer_id": 109796, "author": "Angelo van der Sijpt", "author_id": 19144, "author_profile": "https://Stackoverflow.com/users/19144", "pm_score": 1, "selected": false, "text": "comparable String" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11284/" ]
109,083
<p>Does anyone know of any problems with using WCF to expose a SOAP interface for non .NET clients? For example incompatibilities with other SOAP libraries?</p> <p>This is so that the SOAP interface can be exposed for third parties to integrate with our software.</p>
[ { "answer_id": 110909, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 4, "selected": true, "text": "xsd:import" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
109,086
<p>I am using <code>setInterval(fname, 10000);</code> to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? </p> <p>I want the user to be able to stop the repeated refresh of data.</p>
[ { "answer_id": 109091, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 12, "selected": true, "text": "setInterval() clearInterval() var refreshIntervalId = setInterval(fname, 10000);\n\n/* later */\nclearInterval(refreshIntervalId);\n setInterval() clearInterval()" }, { "answer_id": 109098, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 7, "selected": false, "text": "setInterval clearInterval var myTimer = setInterval(...);\nclearInterval(myTimer);\n" }, { "answer_id": 2844027, "author": "OMGrant", "author_id": 342388, "author_profile": "https://Stackoverflow.com/users/342388", "pm_score": 6, "selected": false, "text": "var intervalId = null;\nvar varCounter = 0;\nvar varName = function(){\n if(varCounter <= 10) {\n varCounter++;\n /* your code goes here */\n } else {\n clearInterval(intervalId);\n }\n};\n\n$(document).ready(function(){\n intervalId = setInterval(varName, 10000);\n});\n" }, { "answer_id": 29902905, "author": "Aart den Braber", "author_id": 1056159, "author_profile": "https://Stackoverflow.com/users/1056159", "pm_score": -1, "selected": false, "text": "var i = 0;\nthis.setInterval(function() {\n if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'\n console.log('Counting...');\n $('#counter').html(i++); //just for explaining and showing\n } else {\n console.log('Stopped counting');\n }\n}, 500);\n\n/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */\n$('#counter').hover(function() { //mouse enter\n $(this).addClass('pauseInterval');\n },function() { //mouse leave\n $(this).removeClass('pauseInterval');\n }\n);\n\n/* Other example */\n$('#pauseInterval').click(function() {\n $('#counter').toggleClass('pauseInterval');\n}); body {\n background-color: #eee;\n font-family: Calibri, Arial, sans-serif;\n}\n#counter {\n width: 50%;\n background: #ddd;\n border: 2px solid #009afd;\n border-radius: 5px;\n padding: 5px;\n text-align: center;\n transition: .3s;\n margin: 0 auto;\n}\n#counter.pauseInterval {\n border-color: red; \n} <!-- you'll need jQuery for this. If you really want a vanilla version, ask -->\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n\n<p id=\"counter\">&nbsp;</p>\n<button id=\"pauseInterval\">Pause</button></p>" }, { "answer_id": 39104954, "author": "Onur Yıldırım", "author_id": 112731, "author_profile": "https://Stackoverflow.com/users/112731", "pm_score": 4, "selected": false, "text": "// Timer with 1000ms (1 second) base interval resolution.\nconst timer = new TaskTimer(1000);\n\n// Add task(s) based on tick intervals.\ntimer.add({\n id: 'job1', // unique id of the task\n tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)\n totalRuns: 10, // run 10 times only. (omit for unlimited times)\n callback(task) {\n // code to be executed on each run\n console.log(task.name + ' task has run ' + task.currentRuns + ' times.');\n // stop the timer anytime you like\n if (someCondition()) timer.stop();\n // or simply remove this task if you have others\n if (someCondition()) timer.remove(task.id);\n }\n});\n\n// Start the timer\ntimer.start();\n timer.pause() timer.resume()" }, { "answer_id": 63892625, "author": "assayag.org", "author_id": 2244093, "author_profile": "https://Stackoverflow.com/users/2244093", "pm_score": 3, "selected": false, "text": "setInterval(\n function clear() {\n clearInterval(this) \n return clear;\n }()\n, 1000)\n Timeout {...}" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
109,087
<p>Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:</p> <pre><code>class hi: def __init__(self): self.ii = "foo" self.kk = "bar" </code></pre> <p>Is there a way for me to do this:</p> <pre><code>&gt;&gt;&gt; mystery_method(hi) ["ii", "kk"] </code></pre> <p>Edit: I originally had asked for class variables erroneously.</p>
[ { "answer_id": 109106, "author": "cnu", "author_id": 1448, "author_profile": "https://Stackoverflow.com/users/1448", "pm_score": 9, "selected": true, "text": "__dict__ >>> hi_obj = hi()\n>>> hi_obj.__dict__.keys()\n dict_keys(['ii', 'kk'])\n" }, { "answer_id": 109122, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 4, "selected": false, "text": ">>> hi_obj = hi()\n>>> hasattr(hi_obj, \"some attribute\")\nFalse\n>>> hasattr(hi_obj, \"ii\")\nTrue\n>>> hasattr(hi_obj, \"kk\")\nTrue\n" }, { "answer_id": 109127, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "hi_obj.__class__.__dict__.items() class Hi( object ):\n class_var = ( 23, 'skidoo' ) # class variable\n def __init__( self ):\n self.ii = \"foo\" # instance variable\n self.jj = \"bar\"\n" }, { "answer_id": 109173, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 7, "selected": false, "text": "class Foo(object):\n def __init__(self):\n self.a = 1\n self.b = 2\n\nvars(Foo()) #==> {'a': 1, 'b': 2}\nvars(Foo()).keys() #==> ['a', 'b']\n" }, { "answer_id": 109207, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 3, "selected": false, "text": ">>> print vars.__doc__\nvars([object]) -> dictionary\n\nWithout arguments, equivalent to locals().\nWith an argument, equivalent to object.__dict__.\n" }, { "answer_id": 111876, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 3, "selected": false, "text": ">>> def f(x, y):\n z = x**2 + y**2\n sqrt_z = z**.5\n return sqrt_z\n\n>>> f.func_code.co_varnames\n('x', 'y', 'z', 'sqrt_z')\n>>> \n def exec_command(self, cmd, msg, sig):\n\n def message(msg):\n a = self.link.process(self.link.recieved_message(msg))\n self.exec_command(*a)\n\n def error(msg):\n self.printer.printInfo(msg)\n\n def set_usrlist(msg):\n self.client.connected_users = msg\n\n def chatmessage(msg):\n self.printer.printInfo(msg)\n\n if not locals().has_key(cmd): return\n cmd = locals()[cmd]\n\n try:\n if 'sig' in cmd.func_code.co_varnames and \\\n 'msg' in cmd.func_code.co_varnames: \n cmd(msg, sig)\n elif 'msg' in cmd.func_code.co_varnames: \n cmd(msg)\n else:\n cmd()\n except Exception, e:\n print '\\n-----------ERROR-----------'\n print 'error: ', e\n print 'Error proccessing: ', cmd.__name__\n print 'Message: ', msg\n print 'Sig: ', sig\n print '-----------ERROR-----------\\n'\n" }, { "answer_id": 4522706, "author": "dmark", "author_id": 552829, "author_profile": "https://Stackoverflow.com/users/552829", "pm_score": 4, "selected": false, "text": "class foo:\n a = 'foo'\n b = 'bar'\n def printVars(object):\n for i in [v for v in dir(object) if not callable(getattr(object,v))]:\n print '\\n%s:' % i\n exec('print object.%s\\n\\n') % i\n" }, { "answer_id": 56897819, "author": "Ethan Joffe", "author_id": 1516256, "author_profile": "https://Stackoverflow.com/users/1516256", "pm_score": 2, "selected": false, "text": "def sprint(object):\n result = ''\n for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:\n result += '\\n%s:' % i + str(getattr(object, i, ''))\n return result\n" }, { "answer_id": 61438322, "author": "hi2meuk", "author_id": 9638474, "author_profile": "https://Stackoverflow.com/users/9638474", "pm_score": 2, "selected": false, "text": "def pub_vars(self):\n \"\"\"Gives the variable names of our instance we want to expose\n \"\"\"\n return [k for k in vars(self) if not k.startswith('_')]\n" }, { "answer_id": 65427547, "author": "Eric Silveira", "author_id": 13430089, "author_profile": "https://Stackoverflow.com/users/13430089", "pm_score": 0, "selected": false, "text": "__code__.co_varnames types" }, { "answer_id": 71689332, "author": "Valentin", "author_id": 11221432, "author_profile": "https://Stackoverflow.com/users/11221432", "pm_score": 0, "selected": false, "text": "def print_inspect(obj):\n print(f\"{type(obj)}\\n\")\n var_names = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith(\"__\")]\n for v in var_names: \n print(f\"\\tself.{v} = {getattr(obj, v)}\\n\")\n\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
109,124
<p>Is it possible to run an external process from Perl, capture its stderr, stdout AND the process exit code?</p> <p>I seem to be able to do combinations of these, e.g. use backticks to get stdout, IPC::Open3 to capture outputs, and system() to get exit codes.</p> <p>How do you capture stderr, stdout, and the exit code all at once?</p>
[ { "answer_id": 109139, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 6, "selected": true, "text": "$? $? >> 8 $?" }, { "answer_id": 109150, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": false, "text": "system $cmd; # using system()\n$output = `$cmd`; # using backticks (``)\nopen (PIPE, \"cmd |\"); # using open()\n system() STDOUT STDOUT STDERR, system() open() STDOUT STDOUT STDERR open(PIPE, \"cmd 2>&1 |\");\n $?" }, { "answer_id": 109672, "author": "xdg", "author_id": 11800, "author_profile": "https://Stackoverflow.com/users/11800", "pm_score": 5, "selected": false, "text": "use IO::CaptureOutput qw/capture_exec/;\n\nmy ($stdout, $stderr, $success, $exit_code) = capture_exec( @cmd );\n" }, { "answer_id": 109902, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 4, "selected": false, "text": " use IPC::System::Simple qw(capture system $EXITVAL);\n\n my $output = capture($cmd, @args);\n\n my $exit_value = $EXITVAL;\n use IPC::System::Simple qw(system capture $EXIT_ANY);\n\n system( [0,1], \"frobincate\", @files); # Must return exitval 0 or 1\n\n my @lines = capture($EXIT_ANY, \"baznicate\", @files); # Any exitval is OK.\n\n foreach my $record (@lines) {\n system( [0, 32], \"barnicate\", $record); # Must return exitval 0 or 32\n }\n" }, { "answer_id": 10320508, "author": "Ian", "author_id": 640427, "author_profile": "https://Stackoverflow.com/users/640427", "pm_score": 1, "selected": false, "text": "use IPC::Run3\n\nmy $number;\nmy $run = run3(\"cmd arg1 arg2 >output_file\",\\undef, \\undef, \\$number);\ndie \"Command failed: $!\" unless ($run && $? == 0);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19214/" ]
109,134
<p>How do I change the style (color) of a div such as the following? </p> <pre><code>"&lt;div id=foo class="ed" style="display: &lt;%= ((foo.isTrue) ? string.Empty : "none") %&gt;"&gt; &lt;%= ((foo.isTrue) ? foo.Name: "false foo") %&gt;"` </code></pre>
[ { "answer_id": 109142, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "\n.important { background: red; }\n.todo { background: blue; }\n \n<div class=\"important\">\n \n<div style=\"background-color: red;\">\n" }, { "answer_id": 109145, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "div.Error {\n color:red;\n}\n <div class='<%=Iif(HasError, \"Error\", \"\")%>'> .... </div>\n" }, { "answer_id": 109159, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 4, "selected": true, "text": "<script>\n var fooElement = document.getElementById(\"foo\");\n fooElement.style.color = \"red\"; //to change the font color\n</script>\n" }, { "answer_id": 109160, "author": "starec", "author_id": 19727, "author_profile": "https://Stackoverflow.com/users/19727", "pm_score": 3, "selected": false, "text": "<div id=\"myDiv\" runat=\"server\">\n Some text\n</div>\n myDiv.Style[\"color\"] = \"red\";\n" }, { "answer_id": 3213603, "author": "Ben Call", "author_id": 328042, "author_profile": "https://Stackoverflow.com/users/328042", "pm_score": 3, "selected": false, "text": "myDiv.Attributes[\"class\"] = \"otherClassName\"\n" }, { "answer_id": 61762611, "author": "Deathstalker", "author_id": 773704, "author_profile": "https://Stackoverflow.com/users/773704", "pm_score": 0, "selected": false, "text": "var div = document.createElement('div');\ndiv.style.cssText = \"border-radius: 6px 6px 6px 6px; height: 250px; width: 600px\";\n var div = document.getElementById('foo');\ndiv.style.cssText = \"background-color: red;\";\n $(\"#\" + TDDeviceTicketID).attr(\"style\", \"padding: 10px;\");\n$(\"#\" + TDDeviceTicketID).attr(\"class\", \"roundbox1\");\n\nThis works for removing it JQUERY\n$(\"#\" + TDDeviceTicketID).removeAttr(\"style\");\n$(\"#\" + TDDeviceTicketID).removeAttr(\"class\");\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
109,149
<p>What's the best javascript framework for drawing (lines, curves whatnot) on images?</p>
[ { "answer_id": 109166, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "var p = Processing(CanvasElement);\np.size(100, 100);\np.background(0);\np.fill(255);\np.ellipse(50, 50, 50, 50);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,186
<p>We are setting up a new SharePoint for which we don't have a valid SSL certificate yet. I would like to call the Lists web service on it to retrieve some meta data about the setup. However, when I try to do this, I get the exception:</p> <blockquote> <p>The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.</p> </blockquote> <p>The nested exception contains the error message:</p> <blockquote> <p>The remote certificate is invalid according to the validation procedure.</p> </blockquote> <p>This is correct since we are using a temporary certificate.</p> <p>My question is: how can I tell the .Net web service client (<em>SoapHttpClientProtocol</em>) to ignore these errors? </p>
[ { "answer_id": 427820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "...\nServicePointManager.ServerCertificateValidationCallback = MyCertHandler;\n...\n\nstatic bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)\n{\n// Ignore errors\nreturn true;\n}\n" }, { "answer_id": 865786, "author": "Keith Sirmons", "author_id": 1048, "author_profile": "https://Stackoverflow.com/users/1048", "pm_score": 6, "selected": false, "text": "ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };\n app.config (ConfigurationManager.AppSettings[\"IgnoreSSLCertificates\"] == \"True\")" }, { "answer_id": 3423696, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 5, "selected": false, "text": "using System.Net;\nusing System.Net.Security;\nusing System.Security.Cryptography.X509Certificates;\n\n/// <summary>\n/// solution for exception\n/// System.Net.WebException: \n/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.\n/// </summary>\npublic static void BypassCertificateError()\n{\n ServicePointManager.ServerCertificateValidationCallback +=\n\n delegate(\n Object sender1,\n X509Certificate certificate,\n X509Chain chain,\n SslPolicyErrors sslPolicyErrors)\n {\n return true;\n };\n}\n" }, { "answer_id": 21782383, "author": "Dinesh Rajan", "author_id": 2049224, "author_profile": "https://Stackoverflow.com/users/2049224", "pm_score": 4, "selected": false, "text": "System.Net.WebClient client = new System.Net.WebClient(); \nServicePointManager.ServerCertificateValidationCallback = delegate { return true; };\nstring sHttpResonse = client.DownloadString(sUrl);\n" }, { "answer_id": 28273881, "author": "hasanaydogar", "author_id": 1696393, "author_profile": "https://Stackoverflow.com/users/1696393", "pm_score": 2, "selected": false, "text": "ServicePointManager.ServerCertificateValidationCallback +=\n (mender, certificate, chain, sslPolicyErrors) => true;\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9540/" ]
109,188
<p>Does anyone know how I can check to see if a directory is writeable in PHP? </p> <p>The function <a href="http://php.net/manual/en/function.is-writable.php" rel="nofollow noreferrer"><code>is_writable</code></a> doesn't work for folders.</p> <blockquote> <p>Edit: It does work. See the accepted answer.</p> </blockquote>
[ { "answer_id": 1561397, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "is_writable() is_writable() is_writable $file $file_directory = dirname($file);\n is_writable($file_directory)" }, { "answer_id": 3783112, "author": "Irfan EVRENS", "author_id": 419500, "author_profile": "https://Stackoverflow.com/users/419500", "pm_score": 5, "selected": false, "text": "<?php \n\n$newFileName = '/var/www/your/file.txt';\n\nif ( ! is_writable(dirname($newFileName))) {\n\n echo dirname($newFileName) . ' must writable!!!';\n} else {\n\n // blah blah blah\n}\n" }, { "answer_id": 6121070, "author": "Griffith", "author_id": 769104, "author_profile": "https://Stackoverflow.com/users/769104", "pm_score": 3, "selected": false, "text": "$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == \"0774\" ? \"true\" : \"false\";\n" }, { "answer_id": 30867243, "author": "Nassim", "author_id": 1035030, "author_profile": "https://Stackoverflow.com/users/1035030", "pm_score": 0, "selected": false, "text": "file_put_contents() $is_writable = file_put_contents('directory/dummy.txt', \"hello\");\n\nif ($is_writable > 0) echo \"yes directory it is writable\";\n\nelse echo \"NO directory it is not writable\";\n unlink('directory/dummy.txt');\n" }, { "answer_id": 45603564, "author": "Studocwho", "author_id": 2358222, "author_profile": "https://Stackoverflow.com/users/2358222", "pm_score": 2, "selected": false, "text": "<?php\n// isWritable.php detects all directories in the same directory the script is in\n// and writes to the page whether each directory is writable or not.\n\n$dirs = array_filter(glob('*'), 'is_dir');\n\nforeach ($dirs as $dir) {\n if (is_writable($dir)) {\n echo $dir.' is writable.<br>';\n } else {\n echo $dir.' is not writable. Permissions may have to be adjusted.<br>';\n } \n}\n?>\n" }, { "answer_id": 55047431, "author": "Andron", "author_id": 284602, "author_profile": "https://Stackoverflow.com/users/284602", "pm_score": 1, "selected": false, "text": "is_writable $dir <?php\n$dir = '/path/to/the/dir';\n\n// try to create this directory if it doesn't exist\n$booExists = is_dir($dir) || (mkdir($dir, 0774, true) && is_dir($dir));\n$booIsWritable = false;\nif ($booExists && is_writable($dir)) {\n $tempFile = tempnam($dir, 'tmp');\n if ($tempFile !== false) {\n $res = file_put_contents($tempFile, 'test');\n\n $booIsWritable = $res !== false;\n @unlink($tempFile);\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
109,210
<p>Normally I use <code>imagecreatefromjpeg()</code> and then <code>getimagesize()</code>, but with Firefox 3 I need to go round this different. So now im using <code>imagecreatefromstring()</code>, but how do I retreive the image dimensions now?</p>
[ { "answer_id": 109299, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": true, "text": "imagesx() imagesy() imagecreatefromstring()" }, { "answer_id": 109301, "author": "Kasper", "author_id": 18671, "author_profile": "https://Stackoverflow.com/users/18671", "pm_score": 3, "selected": false, "text": "$image = imagecreatefromstring($img_str);\n$w = imagesx($image);\n$h = imagesy($image);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
109,232
<p>What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?</p>
[ { "answer_id": 109290, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 10, "selected": true, "text": "SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate\n SELECT COUNT(*) FROM Orders WHERE OrderDate >= '1980-01-01'\n SELECT *\nFROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *\n FROM Orders\n WHERE OrderDate >= '1980-01-01'\n ) AS RowConstrainedResult\nWHERE RowNum >= 1\n AND RowNum < 20\nORDER BY RowNum\n" }, { "answer_id": 980555, "author": "Jalal El-Shaer", "author_id": 95380, "author_profile": "https://Stackoverflow.com/users/95380", "pm_score": 0, "selected": false, "text": " ALTER PROCEDURE [dbo].[RE_ListingReports_SelectSummary] \n\n@CompanyID int,\n@pageNumber int,\n@pageSize int, \n@sort varchar(200)\nAS\n\nDECLARE @sql nvarchar(4000)\nDECLARE @strPageSize nvarchar(20)\nDECLARE @strSkippedRows nvarchar(20)\nDECLARE @strFields nvarchar(4000)\nDECLARE @strFilter nvarchar(4000)\nDECLARE @sortBy nvarchar(4000)\nDECLARE @strFrom nvarchar(4000)\nDECLARE @strID nvarchar(100)\n\nIf(@pageNumber < 0)\n SET @pageNumber = 1\nSET @strPageSize = CAST(@pageSize AS varchar(20)) \nSET @strSkippedRows = CAST(((@pageNumber - 1) * @pageSize) AS varchar(20))-- For example if pageNumber is 5 pageSize is 10, then SkippedRows = 40.\nSET @strID = 'ListingDbID'\nSET @strFields = 'ListingDbID,\nListingID, \n[ExtraRoom]\n'\nSET @strFrom = ' vwListingSummary '\n\nSET @strFilter = ' WHERE\n CompanyID = ' + CAST(@CompanyID As varchar(20)) \nEnd\nSET @sortBy = ''\nif(len(ltrim(rtrim(@sort))) > 0)\nSET @sortBy = ' Order By ' + @sort\n\n-- Total Rows Count\n\nSET @sql = 'SELECT Count(' + @strID + ') FROM ' + @strFROM + @strFilter\nEXEC sp_executesql @sql\n\n--// This technique is used in a Single Table pagination\nSET @sql = 'SELECT ' + @strFields + ' FROM ' + @strFROM +\n ' WHERE ' + @strID + ' IN ' + \n ' (SELECT TOP ' + @strPageSize + ' ' + @strID + ' FROM ' + @strFROM + @strFilter + \n ' AND ' + @strID + ' NOT IN ' + '\n (SELECT TOP ' + @strSkippedRows + ' ' + @strID + ' FROM ' + @strFROM + @strFilter + @SortBy + ') ' \n + @SortBy + ') ' + @SortBy\nPrint @sql \nEXEC sp_executesql @sql\n" }, { "answer_id": 9895345, "author": "Thomas S. Trias", "author_id": 189048, "author_profile": "https://Stackoverflow.com/users/189048", "pm_score": 3, "selected": false, "text": "DECLARE @pageNo int -- 1 based\nDECLARE @pageSize int\nSET @pageNo = 51\nSET @pageSize = 20\n\nDECLARE @firstRecord int\nDECLARE @lastRecord int\nSET @firstRecord = (@pageNo - 1) * @pageSize + 1 -- 1001\nSET @lastRecord = @firstRecord + @pageSize - 1 -- 1020\n\nDECLARE @orderedKeys TABLE (\n rownum int IDENTITY NOT NULL PRIMARY KEY CLUSTERED,\n TableKey int NOT NULL\n)\n\nSET ROWCOUNT @lastRecord\nINSERT INTO @orderedKeys (TableKey) SELECT ID FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate\n\nSET ROWCOUNT 0\n\nSELECT t.*\nFROM Orders t\n INNER JOIN @orderedKeys o ON o.TableKey = t.ID\nWHERE o.rownum >= @firstRecord\nORDER BY o.rownum\n" }, { "answer_id": 10639172, "author": "Jama A.", "author_id": 416996, "author_profile": "https://Stackoverflow.com/users/416996", "pm_score": 9, "selected": false, "text": "SELECT * FROM TableName ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;\n ORDER BY OFFSET ... FETCH OFFSET FETCH ORDER BY ...\nFETCH TOP OFFSET FETCH" }, { "answer_id": 13153631, "author": "Dinesh Rabara", "author_id": 797241, "author_profile": "https://Stackoverflow.com/users/797241", "pm_score": 4, "selected": false, "text": "WITH OrderedOrders AS\n(\n SELECT\n ROW_NUMBER() OVER(ORDER BY FirstName DESC) AS RowNumber, \n FirstName, LastName, ROUND(SalesYTD,2,1) AS \"Sales YTD\"\n FROM [dbo].[vSalesPerson]\n) \nSELECT RowNumber, \n FirstName, LastName, Sales YTD \nFROM OrderedOrders \nWHERE RowNumber > 50 AND RowNumber < 60;\n RowNumber FirstName LastName SalesYTD\n --- ----------- ---------------------- -----------------\n 1 Linda Mitchell 4251368.54\n 2 Jae Pak 4116871.22\n 3 Michael Blythe 3763178.17\n 4 Jillian Carson 3189418.36\n 5 Ranjit Varkey Chudukatil 3121616.32\n 6 José Saraiva 2604540.71\n 7 Shu Ito 2458535.61\n 8 Tsvi Reiter 2315185.61\n 9 Rachel Valdez 1827066.71\n 10 Tete Mensa-Annan 1576562.19\n 11 David Campbell 1573012.93\n 12 Garrett Vargas 1453719.46\n 13 Lynn Tsoflias 1421810.92\n 14 Pamela Ansman-Wolfe 1352577.13\n" }, { "answer_id": 19609938, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 7, "selected": false, "text": "SELECT TOP 10 first_name, last_name, score, COUNT(*) OVER()\nFROM players\nWHERE (score < @previousScore)\n OR (score = @previousScore AND player_id < @previousPlayerId)\nORDER BY score DESC, player_id DESC\n @previousScore @previousPlayerId ORDER BY ASC > COUNT(*) OVER() COUNT(*)" }, { "answer_id": 22368100, "author": "aden", "author_id": 3282216, "author_profile": "https://Stackoverflow.com/users/3282216", "pm_score": 0, "selected": false, "text": " CREATE view vw_sppb_part_listsource as \n select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (\n select \n part.SPPB_PART_ID\n , 0 as is_rev\n , part.part_number \n , part.init_id \n from t_sppb_init_part part \n left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )\n where prev.SPPB_PART_ID is null \n union \n select \n part.SPPB_PART_ID\n , 1 as is_rev\n , prev.part_number \n , part.init_id \n from t_sppb_init_part part \n inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )\n ) sppb_part\n" }, { "answer_id": 23935681, "author": "fatlion", "author_id": 3687935, "author_profile": "https://Stackoverflow.com/users/3687935", "pm_score": 2, "selected": false, "text": "SELECT TOP @offset a.*\nFROM (select top @limit b.*, COUNT(*) OVER() totalrows \n from TABLENAME b order by id asc) a\nORDER BY id desc;\n" }, { "answer_id": 27182167, "author": "Thunder", "author_id": 232687, "author_profile": "https://Stackoverflow.com/users/232687", "pm_score": 2, "selected": false, "text": "use AdventureWorks\nDECLARE @RowsPerPage INT = 10, @PageNumber INT = 6;\nwith result as(\nSELECT SalesOrderDetailID, SalesOrderID, ProductID,\nROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum\nFROM Sales.SalesOrderDetail\nwhere 1=1\n)\nselect SalesOrderDetailID, SalesOrderID, ProductID from result\nWHERE result.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1\nAND @RowsPerPage*(@PageNumber)\n use AdventureWorks\nDECLARE @RowsPerPage INT = 10, @PageNumber INT = 6\nSELECT SalesOrderDetailID, SalesOrderID, ProductID\nFROM (\nSELECT SalesOrderDetailID, SalesOrderID, ProductID,\nROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum\nFROM Sales.SalesOrderDetail\nwhere 1=1\n ) AS SOD\nWHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1\nAND @RowsPerPage*(@PageNumber)\n" }, { "answer_id": 34792367, "author": "Mohan", "author_id": 2189263, "author_profile": "https://Stackoverflow.com/users/2189263", "pm_score": 6, "selected": false, "text": "OFFSET FETCH NEXT --CREATING A PAGING WITH OFFSET and FETCH clauses IN \"SQL SERVER 2012\"\nDECLARE @PageNumber AS INT, @RowspPage AS INT\nSET @PageNumber = 2\nSET @RowspPage = 10 \nSELECT ID_EXAMPLE, NM_EXAMPLE, DT_CREATE\nFROM TB_EXAMPLE\nORDER BY ID_EXAMPLE\nOFFSET ((@PageNumber - 1) * @RowspPage) ROWS\nFETCH NEXT @RowspPage ROWS ONLY;\n" }, { "answer_id": 35355293, "author": "tinonetic", "author_id": 919426, "author_profile": "https://Stackoverflow.com/users/919426", "pm_score": 0, "selected": false, "text": "ROW_NUMBER CURRENT_TIMESTAMP SELECT TOP 20 \n col1,\n col2,\n col3,\n col4\nFROM (\n SELECT \n tbl.col1 AS col1\n ,tbl.col2 AS col2\n ,tbl.col3 AS col3\n ,tbl.col4 AS col4\n ,ROW_NUMBER() OVER (\n ORDER BY CURRENT_TIMESTAMP\n ) AS sort_row\n FROM dbo.MyTable tbl\n ) AS query\nWHERE query.sort_row > 10\nORDER BY query.sort_row\n" }, { "answer_id": 40142567, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 2, "selected": false, "text": "Create Table VLT\n(\n ID int IDentity(1,1),\n Name nvarchar(50),\n Tel Varchar(20)\n)\nGO\n\n\nInsert INTO VLT\nVALUES\n ('NAME' + Convert(varchar(10),@@identity),'FAMIL' + Convert(varchar(10),@@identity))\nGO 500000\n DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM\n ( \n SELECT \n ROW_NUMBER() \n OVER( ORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN VLT.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN VLT.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN VLT.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN VLT.Tel END ASC\n ) AS RowNum\n ,* \n FROM VLT \n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID <> @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name <> @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel <> @FilterValue THEN 1 \n\n END\n ) = 1 \n ) AS Data\nWHERE Data.RowNum > @PageSize * (@PageNumber - 1)\n AND Data.RowNum <= @PageSize * @PageNumber\nORDER BY Data.RowNum\n\nGO\n DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\n;WITH\n Data_CTE\n AS\n ( \n SELECT \n ROW_NUMBER() \n OVER( ORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN VLT.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN VLT.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN VLT.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN VLT.Tel END ASC\n ) AS RowNum\n ,* \n FROM VLT\n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID <> @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name <> @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel <> @FilterValue THEN 1 \n\n END\n ) = 1 \n )\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM Data_CTE AS Data\nWHERE Data.RowNum > @PageSize * (@PageNumber - 1)\n AND Data.RowNum <= @PageSize * @PageNumber\nORDER BY Data.RowNum\n DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\n;WITH\n Data_CTE\n AS\n ( \n SELECT \n * \n FROM VLT\n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID <> @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name <> @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel <> @FilterValue THEN 1 \n\n END\n ) = 1 \n )\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM Data_CTE AS Data\nORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN Data.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN Data.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN Data.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN Data.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN Data.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN Data.Tel END ASC\nOFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;\n" }, { "answer_id": 48257328, "author": "Debendra Dash", "author_id": 5418530, "author_profile": "https://Stackoverflow.com/users/5418530", "pm_score": 2, "selected": false, "text": "create procedure sp_paging\n(\n @pageno as int,\n @records as int\n)\nas\nbegin\ndeclare @offsetcount as int\nset @offsetcount=(@pageno-1)*@records\nselect id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only\nend\n exec sp_paging 2,3\n" }, { "answer_id": 50900663, "author": "salem albadawi", "author_id": 7325608, "author_profile": "https://Stackoverflow.com/users/7325608", "pm_score": 0, "selected": false, "text": "create PROCEDURE SP_Company_List (@pagesize int = -1 ,@pageindex int= 0 ) > AS BEGIN SET NOCOUNT ON;\n\n\n select Id , NameEn from Company ORDER by Id ASC \nOFFSET (@pageindex-1 )* @pagesize ROWS FETCH NEXt @pagesize ROWS ONLY END GO\n DECLARE @return_value int\n\nEXEC @return_value = [dbo].[SP_Company_List] @pagesize = 1 , > @pageindex = 2\n\nSELECT 'Return Value' = @return_value\n\nGO\n" }, { "answer_id": 55382053, "author": "Alex M", "author_id": 5705766, "author_profile": "https://Stackoverflow.com/users/5705766", "pm_score": 0, "selected": false, "text": "WITH T AS\n( \n SELECT TABLE_ID, ROW_NUMBER() OVER (ORDER BY TABLE_ID) AS RN\n , (SELECT COUNT(TABLE_ID) FROM TABLE) AS TOTAL \n FROM TABLE (NOLOCK)\n)\n\nSELECT T2.FIELD1, T2.FIELD2, T2.FIELD3, T.TOTAL \nFROM TABLE T2 (NOLOCK)\nINNER JOIN T ON T2.TABLE_ID=T.TABLE_ID\nWHERE T.RN >= 100\nAND T.RN < 200\n" }, { "answer_id": 59785217, "author": "Damitha", "author_id": 2074778, "author_profile": "https://Stackoverflow.com/users/2074778", "pm_score": 2, "selected": false, "text": "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331/" ]
109,249
<p>Why doesn't have the c standard a memswap function, which would probably look like:</p> <pre><code>int memswap(void *ptr1, void *ptr2, size_t nbytes)? </code></pre> <p>I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.</p>
[ { "answer_id": 109302, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 4, "selected": false, "text": "#include <algorithm>\n\nswap_ranges(ptr1, ptr1 + nbytes, ptr2)\n #include <algorithm>\n\nswap_ranges(ptr1, ptr1 + num_items, ptr2)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18687/" ]
109,251
<p>Whats the best way to bind variable column names to a report field in Access when using a crosstab query? </p>
[ { "answer_id": 109302, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 4, "selected": false, "text": "#include <algorithm>\n\nswap_ranges(ptr1, ptr1 + nbytes, ptr2)\n #include <algorithm>\n\nswap_ranges(ptr1, ptr1 + num_items, ptr2)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
109,262
<p>I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form.</p> <p>If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar. </p> <ol> <li><p>How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form.</p></li> <li><p>If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this.</p></li> </ol>
[ { "answer_id": 109333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Point clientPos = this.PointToClient(Form.MousePosition);\nControl control = this.GetChildAtPoint(clientPos);\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,280
<p>I'm working with DotNetNuke's scheduler to schedule tasks and I'm looking to get the physical file path of a email template that I created. The problem is that HttpContext is NULL because the scheduled task is on a different thread and there is not http request. How would you go about getting the file's physical path?</p>
[ { "answer_id": 109311, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 0, "selected": false, "text": "Imports System.Reflection\nImports System.IO\n...\nPath.GetDirectoryName( Assembly.GetExecutingAssembly().CodeBase ) \n Log.Write ( Assembly.GetExecutingAssembly().CodeBase )\nLog.Write ( Assembly.GetExecutingAssembly().Location )\nLog.Write ( Path.GetFullPath(\".\") )\nLog.Write ( Application.StartupPath )\n... and so on, whatever you can think of ...\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19490/" ]
109,281
<p>I have converted one of my VS2006 projects into VS2008 and when trying to build the project in VS2008 I get the above error. What is .sbr file ? and how can I fix the compile error? Any help is hugely appreciated.</p>
[ { "answer_id": 4816239, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 3, "selected": false, "text": "Enable Browse Information No" }, { "answer_id": 12987365, "author": "Keith D", "author_id": 1761300, "author_profile": "https://Stackoverflow.com/users/1761300", "pm_score": 3, "selected": false, "text": "<BrowseFileInformation></BrowseFileInformation> <BrowseFileInformation></BrowseFileInformation>" }, { "answer_id": 38123198, "author": "RJo", "author_id": 6493156, "author_profile": "https://Stackoverflow.com/users/6493156", "pm_score": 1, "selected": false, "text": "namespace ns\n{ \n class Name\n {\n };\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,284
<p>Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:</p> <pre><code>response.should use_layout('my_layout_name') </code></pre> <p>I found a use_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.</p>
[ { "answer_id": 110301, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 4, "selected": true, "text": "use_layout # in spec_helper.rb\n\nclass UseLayout\n def initialize(expected)\n @expected = 'layouts/' + expected\n end\n def matches?(controller)\n @actual = controller.layout\n #@actual.equal?(@expected)\n @actual == @expected\n end\n def failure_message\n return \"use_layout expected #{@expected.inspect}, got # \n{@actual.inspect}\", @expected, @actual\n end\n def negeative_failure_message\n return \"use_layout expected #{@expected.inspect} not to equal # \n{@actual.inspect}\", @expected, @actual\n end\nend\n\n\ndef use_layout(expected)\n UseLayout.new(expected)\nend\n\n# in controller spec\n response.should use_layout(\"application\")\n" }, { "answer_id": 143967, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": false, "text": "response.layout.should == 'layouts/application'\n" }, { "answer_id": 1316482, "author": "dmcnally", "author_id": 32777, "author_profile": "https://Stackoverflow.com/users/32777", "pm_score": 2, "selected": false, "text": "# in spec_helper.rb\n\nclass UseLayout\n attr_reader :expected\n attr_reader :actual\n\n def initialize(expected)\n @expected = 'layouts/' + expected\n end\n\n def matches?(controller)\n if controller.is_a?(ActionController::Base)\n @actual = 'layouts/' + controller.class.read_inheritable_attribute(:layout)\n else\n @actual = controller.layout\n end\n @actual ||= \"layouts/application\"\n @actual == @expected\n end\n\n def description\n \"Determines if a controller uses a layout\"\n end\n\n def failure_message\n return \"use_layout expected #{@expected.inspect}, got #{@actual.inspect}\"\n end\n\n def negeative_failure_message\n return \"use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}\"\n end\nend\n\ndef use_layout(expected)\n UseLayout.new(expected)\nend\n class PostsController < ApplicationController\n layout \"posts\"\nend\n it { should use_layout(\"posts\") }\n" }, { "answer_id": 1319506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "controller.active_layout.name" }, { "answer_id": 2484251, "author": "Martin Pain", "author_id": 1216210, "author_profile": "https://Stackoverflow.com/users/1216210", "pm_score": 0, "selected": false, "text": "class UseLayout\n def initialize(expected = nil)\n if expected.nil?\n @expected = nil\n else\n @expected = 'layouts/' + expected\n end\n end\n def matches?(controller)\n @actual = controller.layout\n #@actual.equal?(@expected)\n if @expected.nil?\n @actual\n else\n @actual == @expected\n end\n end\n def failure_message\n if @expected.nil?\n return 'use_layout expected a layout to be used, but none was', 'any', @actual\n else\n return \"use_layout expected #{@expected.inspect}, got #{@actual.inspect}\", @expected, @actual\n end\n end\n def negative_failure_message\n if @expected.nil?\n return \"use_layout expected no layout to be used, but #{@actual.inspect} found\", 'any', @actual\n else\n return \"use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}\", @expected, @actual\n end\n end\nend\n\n\ndef use_layout(expected = nil)\n UseLayout.new(expected)\nend\n" }, { "answer_id": 3813372, "author": "Kevin Ansfield", "author_id": 1163866, "author_profile": "https://Stackoverflow.com/users/1163866", "pm_score": 6, "selected": false, "text": "response.should render_template(\"layouts/some_layout\")\n" }, { "answer_id": 6012622, "author": "jacklin", "author_id": 215708, "author_profile": "https://Stackoverflow.com/users/215708", "pm_score": 2, "selected": false, "text": "# spec/support/matchers/render_layout.rb\n\nActionView::Base.class_eval do\n unless instance_methods.include?('_render_layout_with_tracking')\n def _render_layout_with_tracking(layout, locals, &block)\n controller.instance_variable_set(:@_rendered_layout, layout)\n _render_layout_without_tracking(layout, locals, &block)\n end\n alias_method_chain :_render_layout, :tracking\n end\nend\n\n# You can use this matcher anywhere that you have access to the controller instance,\n# like in controller or integration specs.\n#\n# == Example Usage\n#\n# Expects no layout to be rendered:\n# controller.should_not render_layout\n# Expects any layout to be rendered:\n# controller.should render_layout\n# Expects app/views/layouts/application.html.erb to be rendered:\n# controller.should render_layout('application')\n# Expects app/views/layouts/application.html.erb not to be rendered:\n# controller.should_not render_layout('application')\n# Expects app/views/layouts/mobile/application.html.erb to be rendered:\n# controller.should_not render_layout('mobile/application')\nRSpec::Matchers.define :render_layout do |*args|\n expected = args.first\n match do |c|\n actual = get_layout(c)\n if expected.nil?\n !actual.nil? # actual must be nil for the test to pass. Usage: should_not render_layout\n elsif actual\n actual == expected.to_s\n else\n false\n end\n end\n\nfailure_message_for_should do |c|\n actual = get_layout(c)\n if actual.nil? && expected.nil?\n \"expected a layout to be rendered but none was\"\n elsif actual.nil?\n \"expected layout #{expected.inspect} but no layout was rendered\"\n else\n \"expected layout #{expected.inspect} but #{actual.inspect} was rendered\"\n end\n end\n\nfailure_message_for_should_not do |c|\n actual = get_layout(c)\n if expected.nil?\n \"expected no layout but #{actual.inspect} was rendered\"\n else\n \"expected #{expected.inspect} not to be rendered but it was\"\n end\n end\n\n def get_layout(controller)\n if template = controller.instance_variable_get(:@_rendered_layout)\n template.virtual_path.sub(/layouts\\//, '')\n end\n end\nend\n" }, { "answer_id": 8790824, "author": "nathanvda", "author_id": 216513, "author_profile": "https://Stackoverflow.com/users/216513", "pm_score": 3, "selected": false, "text": "response.should render_template(\"layouts/some_folder/some_layout\", \"template-name\")\n" }, { "answer_id": 10646477, "author": "lidaobing", "author_id": 156285, "author_profile": "https://Stackoverflow.com/users/156285", "pm_score": 1, "selected": false, "text": "\nresponse.should render_template(\"layouts/some_folder/some_layout\")\nresponse.should render_template(\"template-name\")\n" }, { "answer_id": 10786526, "author": "Will Tomlins", "author_id": 690904, "author_profile": "https://Stackoverflow.com/users/690904", "pm_score": 4, "selected": false, "text": "response.should render_template(:layout => 'fooo')\n" }, { "answer_id": 31754355, "author": "tgf", "author_id": 1760776, "author_profile": "https://Stackoverflow.com/users/1760776", "pm_score": 1, "selected": false, "text": " expect(response).to render_with_layout('my_layout')\n rails 4.2 rspec 3.3 shoulda-matchers 2.8.0" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
109,305
<p>I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or <em>n</em> records in the grid. The header and the footer should remain in the same position regardless of the amount of data in the grid. Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView? Ideally I would like this to be a reusable control.</p>
[ { "answer_id": 109496, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 1, "selected": false, "text": "<table><tr><td style=\"width:100px\">Header 1</td><td style=\"width:200px\">Header 2</td></table>\n<div style=\"width:300px;height:400px\">\n<asp:GridView>.....</asp:GridView>\n</div>\n<table><tr><td style=\"width:100px\">Footer 1</td><td style=\"width:200px\">Footer 2</td></table>\n" }, { "answer_id": 13683625, "author": "sreejithsdev", "author_id": 905389, "author_profile": "https://Stackoverflow.com/users/905389", "pm_score": 0, "selected": false, "text": "<div style=\"width:100px; height:100px; overflow:scroll;\">\n <asp:GridView ID=\"GridView1\" runat=\"server\">\n </asp:GridView>\n</div>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
109,317
<p>Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string.</p>
[ { "answer_id": 109341, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 6, "selected": true, "text": "c_str()" }, { "answer_id": 109375, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 1, "selected": false, "text": "char* std::string std::fstream std::string c_str() std::string" }, { "answer_id": 111224, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": false, "text": "std::string main() std::string std::string std::string std::string std::string std::string" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
109,318
<p>Using .Net what limitations (if any) are there in using the XmlSerializer? For example, can you serialize Images to XML?</p>
[ { "answer_id": 323530, "author": "Tomer Pintel", "author_id": 15556, "author_profile": "https://Stackoverflow.com/users/15556", "pm_score": 2, "selected": false, "text": " <system.diagnostics>\n <switches>\n <add name=\"XmlSerialization.Compilation\" value=\"4\"/>\n </switches>\n </system.diagnostics>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
109,325
<p>How do you perform the equivalent of Oracle's <code>DESCRIBE TABLE</code> in PostgreSQL (using the psql command)?</p>
[ { "answer_id": 109329, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 5, "selected": false, "text": "DESCRIBE TABLE \\d table" }, { "answer_id": 109331, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 6, "selected": false, "text": " \\d myTable describe table\n \\d myView describe view\n \\d myIndex describe index\n \\d mySequence describe sequence\n" }, { "answer_id": 109334, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 13, "selected": true, "text": "psql \\d+ tablename\n" }, { "answer_id": 109337, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": false, "text": "select column_name, data_type, character_maximum_length, column_default, is_nullable\nfrom INFORMATION_SCHEMA.COLUMNS where table_name = '<name of table>';\n" }, { "answer_id": 118245, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 6, "selected": false, "text": "SELECT \n f.attnum AS number, \n f.attname AS name, \n f.attnum, \n f.attnotnull AS notnull, \n pg_catalog.format_type(f.atttypid,f.atttypmod) AS type, \n CASE \n WHEN p.contype = 'p' THEN 't' \n ELSE 'f' \n END AS primarykey, \n CASE \n WHEN p.contype = 'u' THEN 't' \n ELSE 'f'\n END AS uniquekey,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreignkey,\n CASE\n WHEN p.contype = 'f' THEN p.confkey\n END AS foreignkey_fieldnum,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreignkey,\n CASE\n WHEN p.contype = 'f' THEN p.conkey\n END AS foreignkey_connnum,\n CASE\n WHEN f.atthasdef = 't' THEN d.adsrc\n END AS default\nFROM pg_attribute f \n JOIN pg_class c ON c.oid = f.attrelid \n JOIN pg_type t ON t.oid = f.atttypid \n LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum \n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace \n LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) \n LEFT JOIN pg_class AS g ON p.confrelid = g.oid \nWHERE c.relkind = 'r'::char \n AND n.nspname = '%s' -- Replace with Schema name \n AND c.relname = '%s' -- Replace with table name \n AND f.attnum > 0 ORDER BY number\n;\n" }, { "answer_id": 16841210, "author": "Ryan", "author_id": 2437411, "author_profile": "https://Stackoverflow.com/users/2437411", "pm_score": 5, "selected": false, "text": "\\d *search pattern *" }, { "answer_id": 20408274, "author": "YATK", "author_id": 1911345, "author_profile": "https://Stackoverflow.com/users/1911345", "pm_score": 4, "selected": false, "text": "SELECT attname \nFROM pg_attribute,pg_class \nWHERE attrelid=pg_class.oid \nAND relname='TableName' \nAND attstattarget <>0; \n" }, { "answer_id": 35621545, "author": "Mushahid Khan", "author_id": 4636600, "author_profile": "https://Stackoverflow.com/users/4636600", "pm_score": 4, "selected": false, "text": "\\d+ <table_name> SELECT *\nFROM info_schema.columns\nWHERE table_schema = 'your_schema'\nAND table_name = 'your_table'\n" }, { "answer_id": 37045464, "author": "Mr.Tananki", "author_id": 3541955, "author_profile": "https://Stackoverflow.com/users/3541955", "pm_score": 4, "selected": false, "text": "SELECT DATA_TYPE \nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE table_name = 'tbl_name' \nAND COLUMN_NAME = 'col_name'\n" }, { "answer_id": 41100953, "author": "Riya Bansal", "author_id": 6721338, "author_profile": "https://Stackoverflow.com/users/6721338", "pm_score": 3, "selected": false, "text": "Select * from schema_name.table_name limit 0;\n" }, { "answer_id": 45216067, "author": "Usman Yaqoob", "author_id": 2196607, "author_profile": "https://Stackoverflow.com/users/2196607", "pm_score": 2, "selected": false, "text": "Use this command \n\n\\d table name\n\nlike \n\n\\d queuerecords\n\n Table \"public.queuerecords\"\n Column | Type | Modifiers\n-----------+-----------------------------+-----------\n id | uuid | not null\n endtime | timestamp without time zone |\n payload | text |\n queueid | text |\n starttime | timestamp without time zone |\n status | text |\n" }, { "answer_id": 45533525, "author": "Guardian", "author_id": 8241603, "author_profile": "https://Stackoverflow.com/users/8241603", "pm_score": 2, "selected": false, "text": "\\d+ tablename or \\d tablename\n" }, { "answer_id": 48788746, "author": "anurag2090", "author_id": 1591945, "author_profile": "https://Stackoverflow.com/users/1591945", "pm_score": 3, "selected": false, "text": "SELECT\n COLUMN_NAME\nFROM\n information_schema.COLUMNS\nWHERE\n TABLE_NAME = 'city';\n" }, { "answer_id": 49440385, "author": "paulg", "author_id": 7899140, "author_profile": "https://Stackoverflow.com/users/7899140", "pm_score": -1, "selected": false, "text": "'CREATE TABLE ' || 'yourschema.yourtable' || E'\\n(\\n' ||\narray_to_string(\narray_agg(\n' ' || column_expr\n)\n, E',\\n'\n) || E'\\n);\\n'\nfrom\n(\nSELECT ' ' || column_name || ' ' || data_type || \ncoalesce('(' || character_maximum_length || ')', '') || \ncase when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr\nFROM information_schema.columns\nWHERE table_schema || '.' || table_name = 'yourschema.yourtable'\nORDER BY ordinal_position\n) column_list;\n" }, { "answer_id": 49749357, "author": "MisterJoyson", "author_id": 7519321, "author_profile": "https://Stackoverflow.com/users/7519321", "pm_score": 3, "selected": false, "text": "SELECT\n a.attname AS Field,\n t.typname || '(' || a.atttypmod || ')' AS Type,\n CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,\n CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,\n (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\\'(.*)\\'')\n FROM\n pg_catalog.pg_attrdef d\n WHERE\n d.adrelid = a.attrelid\n AND d.adnum = a.attnum\n AND a.atthasdef) AS Default,\n '' as Extras\nFROM\n pg_class c \n JOIN pg_attribute a ON a.attrelid = c.oid\n JOIN pg_type t ON a.atttypid = t.oid\n LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid \n AND r.conname = a.attname\nWHERE\n c.relname = 'tablename'\n AND a.attnum > 0\n\nORDER BY a.attnum\n" }, { "answer_id": 50906124, "author": "meenal", "author_id": 8142051, "author_profile": "https://Stackoverflow.com/users/8142051", "pm_score": 2, "selected": false, "text": "\\d schema_name.table_name \\d+ schema_name.table_name\n" }, { "answer_id": 52614714, "author": "Howard Elton", "author_id": 7588326, "author_profile": "https://Stackoverflow.com/users/7588326", "pm_score": 3, "selected": false, "text": "SELECT\n n.nspname as schema,\n c.relname as table,\n f.attname as column, \n f.attnum as column_id, \n f.attnotnull as not_null,\n f.attislocal not_inherited,\n f.attinhcount inheritance_count,\n pg_catalog.format_type(f.atttypid,f.atttypmod) AS data_type_full,\n t.typname AS data_type_name,\n CASE \n WHEN f.atttypmod >= 0 AND t.typname <> 'numeric'THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data\n END AS data_type_length, \n CASE \n WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) >> 16) & 65535)\n END AS numeric_precision, \n CASE \n WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)& 65535 )\n END AS numeric_scale, \n CASE \n WHEN p.contype = 'p' THEN 't' \n ELSE 'f' \n END AS is_primary_key, \n CASE\n WHEN p.contype = 'p' THEN p.conname\n END AS primary_key_name,\n CASE \n WHEN p.contype = 'u' THEN 't' \n ELSE 'f'\n END AS is_unique_key,\n CASE\n WHEN p.contype = 'u' THEN p.conname\n END AS unique_key_name,\n CASE\n WHEN p.contype = 'f' THEN 't'\n ELSE 'f'\n END AS is_foreign_key,\n CASE\n WHEN p.contype = 'f' THEN p.conname\n END AS foreignkey_name,\n CASE\n WHEN p.contype = 'f' THEN p.confkey\n END AS foreign_key_columnid,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreign_key_table,\n CASE\n WHEN p.contype = 'f' THEN p.conkey\n END AS foreign_key_local_column_id,\n CASE\n WHEN f.atthasdef = 't' THEN d.adsrc\n END AS default_value\nFROM pg_attribute f \n JOIN pg_class c ON c.oid = f.attrelid \n JOIN pg_type t ON t.oid = f.atttypid \n LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum \n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace \n LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) \n LEFT JOIN pg_class AS g ON p.confrelid = g.oid \nWHERE c.relkind = 'r'::char \n AND f.attisdropped = false\n AND n.nspname = '%s' -- Replace with Schema name \n AND c.relname = '%s' -- Replace with table name \n AND f.attnum > 0 \nORDER BY f.attnum\n;\n" }, { "answer_id": 54107940, "author": "LeYAUable", "author_id": 9210263, "author_profile": "https://Stackoverflow.com/users/9210263", "pm_score": 5, "selected": false, "text": "SELECT * FROM information_schema.columns\nWHERE table_schema = 'your_schema'\n AND table_name = 'your_table'\n" }, { "answer_id": 63752212, "author": "zmerr", "author_id": 4621188, "author_profile": "https://Stackoverflow.com/users/4621188", "pm_score": 2, "selected": false, "text": "\\d+ schema_name.table_name\n\n" }, { "answer_id": 69942312, "author": "Daywalker", "author_id": 2617354, "author_profile": "https://Stackoverflow.com/users/2617354", "pm_score": 1, "selected": false, "text": "# sudo -u postgres pg_dump --table=my_table_name --schema-only mydb" }, { "answer_id": 72168740, "author": "Mistico", "author_id": 11670863, "author_profile": "https://Stackoverflow.com/users/11670863", "pm_score": 2, "selected": false, "text": "\\d \"Users\"" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657951/" ]
109,343
<p>With web services it is considered a good practice to batch several service calls into one message to reduce a number of remote calls. Is there any way to do this with RESTful services?</p>
[ { "answer_id": 115026, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 3, "selected": true, "text": "POST /folders/ROOT/the/folder/name/users?userId=56&userId=87&userId=45\n PUT /folders/ROOT/the/folder/name/users/56\nPUT /folders/ROOT/the/folder/name/users/87\nPUT /folders/ROOT/the/folder/name/users/45\n GET /some/list/of/resources?startIndex=10&pageSize=50\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ]
109,383
<p>I am relatively new to Java, and often find that I need to sort a <code>Map&lt;Key, Value&gt;</code> on the values.</p> <p>Since the values are not unique, I find myself converting the <code>keySet</code> into an <code>array</code>, and sorting that array through <strong>array sort</strong> with a <strong>custom comparator</strong> that sorts on the value associated with the key.</p> <p>Is there an easier way?</p>
[ { "answer_id": 109389, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 8, "selected": false, "text": "private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {\n List<Entry<K, V>> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator<Object>() {\n @SuppressWarnings(\"unchecked\")\n public int compare(Object o1, Object o2) {\n return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());\n }\n });\n\n Map<K, V> result = new LinkedHashMap<>();\n for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {\n Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();\n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n}\n" }, { "answer_id": 109396, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 3, "selected": false, "text": "java.util.LinkedHashMap<T> Collections.sort()" }, { "answer_id": 109407, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": -1, "selected": false, "text": "Map<Object, String> map = new HashMap<Object, String>();\n// Populate the Map\nList<String> mapValues = new ArrayList<String>(map.values());\nCollections.sort(mapValues);\n Collections.sort(mapValues, comparable);\n" }, { "answer_id": 109495, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": -1, "selected": false, "text": "public static void main(String[] args) {\n Map<String, String> unsorted = new HashMap<String, String>();\n unsorted.put(\"Cde\", \"Cde_Value\");\n unsorted.put(\"Abc\", \"Abc_Value\");\n unsorted.put(\"Bcd\", \"Bcd_Value\");\n\n Comparator<String> comparer = new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }};\n\n Map<String, String> sorted = new TreeMap<String, String>(comparer);\n sorted.putAll(unsorted);\n System.out.println(sorted);\n}\n" }, { "answer_id": 109787, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 5, "selected": false, "text": "public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {\n final int size = map.size();\n final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);\n list.addAll(map.entrySet());\n final ValueComparator<V> cmp = new ValueComparator<V>();\n Collections.sort(list, cmp);\n final List<K> keys = new ArrayList<K>(size);\n for (int i = 0; i < size; i++) {\n keys.set(i, list.get(i).getKey());\n }\n return keys;\n}\n\nprivate static final class ValueComparator<V extends Comparable<? super V>>\n implements Comparator<Map.Entry<?, V>> {\n public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n}\n public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue2(Map<K, V> map) {\n final int size = map.size();\n final List reusedList = new ArrayList(size);\n final List<Map.Entry<K, V>> meView = reusedList;\n meView.addAll(map.entrySet());\n Collections.sort(meView, SINGLE);\n final List<K> keyView = reusedList;\n for (int i = 0; i < size; i++) {\n keyView.set(i, meView.get(i).getKey());\n }\n return keyView;\n}\n\nprivate static final Comparator SINGLE = new ValueComparator();\n" }, { "answer_id": 109958, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": -1, "selected": false, "text": "public static void main(String[] args) {\n Map<String, String> unsorted = new HashMap<String, String>();\n unsorted.put(\"Cde\", \"Cde_Value\");\n unsorted.put(\"Abc\", \"Abc_Value\");\n unsorted.put(\"Bcd\", \"Bcd_Value\");\n\n Comparator<String> comparer = new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }};\n\n System.out.println(sortByValue(unsorted, comparer));\n\n}\n\npublic static <K, V> Map<K,V> sortByValue(Map<K, V> in, Comparator<? super V> compare) {\n Map<V, K> swapped = new TreeMap<V, K>(compare);\n for(Entry<K,V> entry: in.entrySet()) {\n if (entry.getValue() != null) {\n swapped.put(entry.getValue(), entry.getKey());\n }\n }\n LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();\n for(Entry<V,K> entry: swapped.entrySet()) {\n if (entry.getValue() != null) {\n result.put(entry.getValue(), entry.getKey());\n }\n }\n return result;\n}\n" }, { "answer_id": 111183, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": false, "text": "package com.javadude.sample;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class SortedValueHashMap<K, V> implements Map<K, V> {\n private Map<K, V> map_ = new HashMap<K, V>();\n private List<V> valueList_ = new ArrayList<V>();\n private boolean needsSort_ = false;\n private Comparator<V> comparator_;\n\n public SortedValueHashMap() {\n }\n public SortedValueHashMap(List<V> valueList) {\n valueList_ = valueList;\n }\n\n public List<V> sortedValues() {\n if (needsSort_) {\n needsSort_ = false;\n Collections.sort(valueList_, comparator_);\n }\n return valueList_;\n }\n\n // mutators\n public void clear() {\n map_.clear();\n valueList_.clear();\n needsSort_ = false;\n }\n\n public V put(K key, V value) {\n valueList_.add(value);\n needsSort_ = true;\n return map_.put(key, value);\n }\n\n public void putAll(Map<? extends K, ? extends V> m) {\n map_.putAll(m);\n valueList_.addAll(m.values());\n needsSort_ = true;\n }\n\n public V remove(Object key) {\n V value = map_.remove(key);\n valueList_.remove(value);\n return value;\n }\n\n // accessors\n public boolean containsKey(Object key) { return map_.containsKey(key); }\n public boolean containsValue(Object value) { return map_.containsValue(value); }\n public Set<java.util.Map.Entry<K, V>> entrySet() { return map_.entrySet(); }\n public boolean equals(Object o) { return map_.equals(o); }\n public V get(Object key) { return map_.get(key); }\n public int hashCode() { return map_.hashCode(); }\n public boolean isEmpty() { return map_.isEmpty(); }\n public Set<K> keySet() { return map_.keySet(); }\n public int size() { return map_.size(); }\n public Collection<V> values() { return map_.values(); }\n}\n" }, { "answer_id": 119143, "author": "Lyudmil", "author_id": 13121, "author_profile": "https://Stackoverflow.com/users/13121", "pm_score": 4, "selected": false, "text": "public class MapUtilities {\n\npublic static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValue(Map<K, V> map) {\n List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());\n Collections.sort(entries, new ByValue<K, V>());\n return entries;\n}\n\nprivate static class ByValue<K, V extends Comparable<V>> implements Comparator<Entry<K, V>> {\n public int compare(Entry<K, V> o1, Entry<K, V> o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n}\n public class MapUtilitiesTest extends TestCase {\npublic void testSorting() {\n HashMap<String, Integer> map = new HashMap<String, Integer>();\n map.put(\"One\", 1);\n map.put(\"Two\", 2);\n map.put(\"Three\", 3);\n\n List<Map.Entry<String, Integer>> sorted = MapUtilities.sortByValue(map);\n assertEquals(\"First\", \"One\", sorted.get(0).getKey());\n assertEquals(\"Second\", \"Two\", sorted.get(1).getKey());\n assertEquals(\"Third\", \"Three\", sorted.get(2).getKey());\n}\n" }, { "answer_id": 747627, "author": "Maxim Veksler", "author_id": 48062, "author_profile": "https://Stackoverflow.com/users/48062", "pm_score": 2, "selected": false, "text": "/**\n * Sort a map by it's keys in ascending order. \n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static <K, V> LinkedHashMap<K, V> sortMapByKey(final Map<K, V> map) {\n return sortMapByKey(map, SortingOrder.ASCENDING);\n}\n\n/**\n * Sort a map by it's values in ascending order.\n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static <K, V> LinkedHashMap<K, V> sortMapByValue(final Map<K, V> map) {\n return sortMapByValue(map, SortingOrder.ASCENDING);\n}\n\n/**\n * Sort a map by it's keys.\n * \n * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order. \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static <K, V> LinkedHashMap<K, V> sortMapByKey(final Map<K, V> map, final SortingOrder sortingOrder) {\n Comparator<Map.Entry<K, V>> comparator = new Comparator<Entry<K,V>>() {\n public int compare(Entry<K, V> o1, Entry<K, V> o2) {\n return comparableCompare(o1.getKey(), o2.getKey(), sortingOrder);\n }\n };\n\n return sortMap(map, comparator);\n}\n\n/**\n * Sort a map by it's values.\n * \n * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order. \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static <K, V> LinkedHashMap<K, V> sortMapByValue(final Map<K, V> map, final SortingOrder sortingOrder) {\n Comparator<Map.Entry<K, V>> comparator = new Comparator<Entry<K,V>>() {\n public int compare(Entry<K, V> o1, Entry<K, V> o2) {\n return comparableCompare(o1.getValue(), o2.getValue(), sortingOrder);\n }\n };\n\n return sortMap(map, comparator);\n}\n\n@SuppressWarnings(\"unchecked\")\nprivate static <T> int comparableCompare(T o1, T o2, SortingOrder sortingOrder) {\n int compare = ((Comparable<T>)o1).compareTo(o2);\n\n switch (sortingOrder) {\n case ASCENDING:\n return compare;\n case DESCENDING:\n return (-1) * compare;\n }\n\n return 0;\n}\n\n/**\n * Sort a map by supplied comparator logic.\n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static <K, V> LinkedHashMap<K, V> sortMap(final Map<K, V> map, final Comparator<Map.Entry<K, V>> comparator) {\n // Convert the map into a list of key,value pairs.\n List<Map.Entry<K, V>> mapEntries = new LinkedList<Map.Entry<K, V>>(map.entrySet());\n\n // Sort the converted list according to supplied comparator.\n Collections.sort(mapEntries, comparator);\n\n // Build a new ordered map, containing the same entries as the old map. \n LinkedHashMap<K, V> result = new LinkedHashMap<K, V>(map.size() + (map.size() / 20));\n for(Map.Entry<K, V> entry : mapEntries) {\n // We iterate on the mapEntries list which is sorted by the comparator putting new entries into \n // the targeted result which is a sorted map. \n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n}\n\n/**\n * Sorting order enum, specifying request result sort behavior.\n * @author Maxim Veksler\n *\n */\npublic static enum SortingOrder {\n /**\n * Resulting sort will be from smaller to biggest.\n */\n ASCENDING,\n /**\n * Resulting sort will be from biggest to smallest.\n */\n DESCENDING\n}\n" }, { "answer_id": 1283722, "author": "user157196", "author_id": 157196, "author_profile": "https://Stackoverflow.com/users/157196", "pm_score": 9, "selected": false, "text": "get null public class Testing {\n public static void main(String[] args) {\n HashMap<String, Double> map = new HashMap<String, Double>();\n ValueComparator bvc = new ValueComparator(map);\n TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);\n\n map.put(\"A\", 99.5);\n map.put(\"B\", 67.4);\n map.put(\"C\", 67.4);\n map.put(\"D\", 67.3);\n\n System.out.println(\"unsorted map: \" + map);\n sorted_map.putAll(map);\n System.out.println(\"results: \" + sorted_map);\n }\n}\n\nclass ValueComparator implements Comparator<String> {\n Map<String, Double> base;\n\n public ValueComparator(Map<String, Double> base) {\n this.base = base;\n }\n\n // Note: this comparator imposes orderings that are inconsistent with\n // equals.\n public int compare(String a, String b) {\n if (base.get(a) >= base.get(b)) {\n return -1;\n } else {\n return 1;\n } // returning 0 would merge keys\n }\n}\n unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4}\nresults: {D=67.3, B=67.4, C=67.4, A=99.5}\n" }, { "answer_id": 2112659, "author": "Anthony", "author_id": 236152, "author_profile": "https://Stackoverflow.com/users/236152", "pm_score": 5, "selected": false, "text": "public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {\n Comparator<K> valueComparator = new Comparator<K>() {\n public int compare(K k1, K k2) {\n int compare = map.get(k2).compareTo(map.get(k1));\n if (compare == 0) return 1;\n else return compare;\n }\n };\n Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);\n sortedByValues.putAll(map);\n return sortedByValues;\n}\n" }, { "answer_id": 2581754, "author": "Carter Page", "author_id": 309596, "author_profile": "https://Stackoverflow.com/users/309596", "pm_score": 10, "selected": false, "text": "public class MapUtil {\n public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {\n List<Entry<K, V>> list = new ArrayList<>(map.entrySet());\n list.sort(Entry.comparingByValue());\n\n Map<K, V> result = new LinkedHashMap<>();\n for (Entry<K, V> entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n }\n}\n" }, { "answer_id": 2797784, "author": "Darkless", "author_id": 336642, "author_profile": "https://Stackoverflow.com/users/336642", "pm_score": 3, "selected": false, "text": "Map<Driver driver, Float time> map = new TreeMap<Driver driver, Float time>(*);\n ResultComparator rc = new ResultComparator();\nSet<Results> set = new TreeSet<Results>(rc);\n Results public class Results {\n private Driver driver;\n private Float time;\n\n public Results(Driver driver, Float time) {\n this.driver = driver;\n this.time = time;\n }\n\n public Float getTime() {\n return time;\n }\n\n public void setTime(Float time) {\n this.time = time;\n }\n\n public Driver getDriver() {\n return driver;\n }\n\n public void setDriver (Driver driver) {\n this.driver = driver;\n }\n}\n public class ResultsComparator implements Comparator<Results> {\n public int compare(Results t, Results t1) {\n if (t.getTime() < t1.getTime()) {\n return 1;\n } else if (t.getTime() == t1.getTime()) {\n return 0;\n } else {\n return -1;\n }\n }\n}\n Iterator it = set.iterator();\nwhile (it.hasNext()) {\n Results r = (Results)it.next();\n System.out.println( r.getDriver().toString\n //or whatever that is related to Driver class -getName() getSurname()\n + \" \"\n + r.getTime()\n );\n}\n" }, { "answer_id": 3420912, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": 8, "selected": false, "text": "Comparable valueComparator = Ordering.natural().onResultOf(Functions.forMap(map))\n valueComparator = Ordering.from(comparator).onResultOf(Functions.forMap(map)) \n Ordering Comparator Comparable valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)).compound(Ordering.natural())\n comparable hashCode equals compareTo map = ImmutableSortedMap.copyOf(myOriginalMap, valueComparator);\n TreeMap TreeMap.get() compare() compare() get() import static org.junit.Assert.assertEquals;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.TreeMap;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.Ordering;\n\nclass ValueComparableMap<K extends Comparable<K>,V> extends TreeMap<K,V> {\n //A map for doing lookups on the keys for comparison so we don't get infinite loops\n private final Map<K, V> valueMap;\n\n ValueComparableMap(final Ordering<? super V> partialValueOrdering) {\n this(partialValueOrdering, new HashMap<K,V>());\n }\n\n private ValueComparableMap(Ordering<? super V> partialValueOrdering,\n HashMap<K, V> valueMap) {\n super(partialValueOrdering //Apply the value ordering\n .onResultOf(Functions.forMap(valueMap)) //On the result of getting the value for the key from the map\n .compound(Ordering.natural())); //as well as ensuring that the keys don't get clobbered\n this.valueMap = valueMap;\n }\n\n public V put(K k, V v) {\n if (valueMap.containsKey(k)){\n //remove the key in the sorted set before adding the key again\n remove(k);\n }\n valueMap.put(k,v); //To get \"real\" unsorted values for the comparator\n return super.put(k, v); //Put it in value order\n }\n\n public static void main(String[] args){\n TreeMap<String, Integer> map = new ValueComparableMap<String, Integer>(Ordering.natural());\n map.put(\"a\", 5);\n map.put(\"b\", 1);\n map.put(\"c\", 3);\n assertEquals(\"b\",map.firstKey());\n assertEquals(\"a\",map.lastKey());\n map.put(\"d\",0);\n assertEquals(\"d\",map.firstKey());\n //ensure it's still a map (by overwriting a key, but with a new value) \n map.put(\"d\", 2);\n assertEquals(\"b\", map.firstKey());\n //Ensure multiple values do not clobber keys\n map.put(\"e\", 2);\n assertEquals(5, map.size());\n assertEquals(2, (int) map.get(\"e\"));\n assertEquals(2, (int) map.get(\"d\"));\n }\n }\n Map<V,K> new ValueComparableMap(Ordering.natural());\n //or\n new ValueComparableMap(Ordering.from(comparator));\n" }, { "answer_id": 4577336, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 2, "selected": false, "text": "static import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class SortableValueMap<K, V extends Comparable<V>>\n extends LinkedHashMap<K, V> {\n public SortableValueMap() { }\n\n public SortableValueMap( Map<K, V> map ) {\n super( map );\n }\n\n public void sortByValue() {\n List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( entrySet() );\n\n Collections.sort( list, new Comparator<Map.Entry<K, V>>() {\n public int compare( Map.Entry<K, V> entry1, Map.Entry<K, V> entry2 ) {\n return entry1.getValue().compareTo( entry2.getValue() );\n }\n });\n\n clear();\n\n for( Map.Entry<K, V> entry : list ) {\n put( entry.getKey(), entry.getValue() );\n }\n }\n\n private static void print( String text, Map<String, Double> map ) {\n System.out.println( text );\n\n for( String key : map.keySet() ) {\n System.out.println( \"key/value: \" + key + \"/\" + map.get( key ) );\n }\n }\n\n public static void main( String[] args ) {\n SortableValueMap<String, Double> map =\n new SortableValueMap<String, Double>();\n\n map.put( \"A\", 67.5 );\n map.put( \"B\", 99.5 );\n map.put( \"C\", 82.4 );\n map.put( \"D\", 42.0 );\n\n print( \"Unsorted map\", map );\n map.sortByValue();\n print( \"Sorted map\", map );\n }\n}\n" }, { "answer_id": 4943507, "author": "Roger", "author_id": 558193, "author_profile": "https://Stackoverflow.com/users/558193", "pm_score": 3, "selected": false, "text": "public static <K, V extends Comparable<V>> Map<K, V> sortMapByValues(final Map<K, V> map) {\n Comparator<K> valueComparator = new Comparator<K>() {\n public int compare(K k1, K k2) {\n final V v1 = map.get(k1);\n final V v2 = map.get(k2);\n\n /* Not sure how to handle nulls ... */\n if (v1 == null) {\n return (v2 == null) ? 0 : 1;\n }\n\n int compare = v2.compareTo(v1);\n if (compare != 0)\n {\n return compare;\n }\n else\n {\n Integer h1 = k1.hashCode();\n Integer h2 = k2.hashCode();\n return h2.compareTo(h1);\n }\n }\n };\n Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);\n sortedByValues.putAll(map);\n return sortedByValues;\n}\n" }, { "answer_id": 5041615, "author": "Sunil Kumar Sahoo", "author_id": 111988, "author_profile": "https://Stackoverflow.com/users/111988", "pm_score": -1, "selected": false, "text": "public class SortedMapExample {\n\n public static void main(String[] args) {\n Map<String, String> map = new HashMap<String, String>();\n\n map.put(\"Cde\", \"C\");\n map.put(\"Abc\", \"A\");\n map.put(\"Cbc\", \"Z\");\n map.put(\"Dbc\", \"D\");\n map.put(\"Bcd\", \"B\");\n map.put(\"sfd\", \"Bqw\");\n map.put(\"DDD\", \"Bas\");\n map.put(\"BGG\", \"Basd\");\n\n System.out.println(sort(map, new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }}));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <K, V> Map<K,V> sort(Map<K, V> in, Comparator<? super V> compare) {\n Map<K, V> result = new LinkedHashMap<K, V>();\n V[] array = (V[])in.values().toArray();\n for(int i=0;i<array.length;i++)\n {\n\n }\n Arrays.sort(array, compare);\n for (V item : array) {\n K key= (K) getKey(in, item);\n result.put(key, item);\n }\n return result;\n }\n\n public static <K, V> Object getKey(Map<K, V> in,V value)\n {\n Set<K> key= in.keySet();\n Iterator<K> keyIterator=key.iterator();\n while (keyIterator.hasNext()) {\n K valueObject = (K) keyIterator.next();\n if(in.get(valueObject).equals(value))\n {\n return valueObject;\n }\n }\n return null;\n }\n" }, { "answer_id": 6281263, "author": "lisak", "author_id": 306488, "author_profile": "https://Stackoverflow.com/users/306488", "pm_score": 3, "selected": false, "text": "Map<String, Long> map = new HashMap<String, Long>();\n// populate with data to sort on Value\n// use datastructure designed for sorting\n\nQueue queue = new PriorityQueue( map.size(), new MapComparable() );\nqueue.addAll( map.entrySet() );\n\n// get a sorted map\nLinkedHashMap<String, Long> linkedMap = new LinkedHashMap<String, Long>();\n\nfor (Map.Entry<String, Long> entry; (entry = queue.poll())!=null;) {\n linkedMap.put(entry.getKey(), entry.getValue());\n}\n\npublic static class MapComparable implements Comparator<Map.Entry<String, Long>>{\n\n public int compare(Entry<String, Long> e1, Entry<String, Long> e2) {\n return e1.getValue().compareTo(e2.getValue());\n }\n}\n" }, { "answer_id": 6584631, "author": "RoyalBigorno", "author_id": 829939, "author_profile": "https://Stackoverflow.com/users/829939", "pm_score": 4, "selected": false, "text": "final class MapValueComparator<K,V extends Comparable<V>> implements Comparator<K> {\n private final Map<K,V> map;\n \n private MapValueComparator() {\n super();\n }\n \n public MapValueComparator(Map<K,V> map) {\n this();\n this.map = map;\n }\n \n public int compare(K o1, K o2) {\n return map.get(o1).compareTo(map.get(o2));\n }\n}\n" }, { "answer_id": 6705027, "author": "michel.iamit", "author_id": 369060, "author_profile": "https://Stackoverflow.com/users/369060", "pm_score": 4, "selected": false, "text": "if((Double)base.get(a) < (Double)base.get(b)) {\n return 1;\n} else if((Double)base.get(a) == (Double)base.get(b)) {\n return -1;\n} else {\n return -1;\n}\n package nl.iamit.util;\n\nimport java.util.Comparator;\nimport java.util.Map;\n\npublic class Comparators {\n\n\n public static class MapIntegerStringComparator implements Comparator {\n\n Map<Integer, String> base;\n\n public MapIntegerStringComparator(Map<Integer, String> base) {\n this.base = base;\n }\n\n public int compare(Object a, Object b) {\n\n int compare = ((String) base.get(a))\n .compareTo((String) base.get(b));\n if (compare == 0) {\n return -1;\n }\n return compare;\n }\n }\n\n\n}\n package test.nl.iamit.util;\n\nimport java.util.HashMap;\nimport java.util.TreeMap;\nimport nl.iamit.util.Comparators;\nimport org.junit.Test;\nimport static org.junit.Assert.assertArrayEquals;\n\npublic class TestComparators {\n\n\n @Test\n public void testMapIntegerStringComparator(){\n HashMap<Integer, String> unSoretedMap = new HashMap<Integer, String>();\n Comparators.MapIntegerStringComparator bvc = new Comparators.MapIntegerStringComparator(\n unSoretedMap);\n TreeMap<Integer, String> sorted_map = new TreeMap<Integer, String>(bvc);\n //the testdata:\n unSoretedMap.put(new Integer(1), \"E\");\n unSoretedMap.put(new Integer(2), \"A\");\n unSoretedMap.put(new Integer(3), \"E\");\n unSoretedMap.put(new Integer(4), \"B\");\n unSoretedMap.put(new Integer(5), \"F\");\n\n sorted_map.putAll(unSoretedMap);\n\n Object[] targetKeys={new Integer(2),new Integer(4),new Integer(3),new Integer(1),new Integer(5) };\n Object[] currecntKeys=sorted_map.keySet().toArray();\n\n assertArrayEquals(targetKeys,currecntKeys);\n }\n}\n public static class MapStringDoubleComparator implements Comparator {\n\n Map<String, Double> base;\n\n public MapStringDoubleComparator(Map<String, Double> base) {\n this.base = base;\n }\n\n //note if you want decending in stead of ascending, turn around 1 and -1\n public int compare(Object a, Object b) {\n if ((Double) base.get(a) == (Double) base.get(b)) {\n return 0;\n } else if((Double) base.get(a) < (Double) base.get(b)) {\n return -1;\n }else{\n return 1;\n }\n }\n}\n @Test\npublic void testMapStringDoubleComparator(){\n HashMap<String, Double> unSoretedMap = new HashMap<String, Double>();\n Comparators.MapStringDoubleComparator bvc = new Comparators.MapStringDoubleComparator(\n unSoretedMap);\n TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);\n //the testdata:\n unSoretedMap.put(\"D\",new Double(67.3));\n unSoretedMap.put(\"A\",new Double(99.5));\n unSoretedMap.put(\"B\",new Double(67.4));\n unSoretedMap.put(\"C\",new Double(67.5));\n unSoretedMap.put(\"E\",new Double(99.5));\n\n sorted_map.putAll(unSoretedMap);\n\n Object[] targetKeys={\"D\",\"B\",\"C\",\"E\",\"A\"};\n Object[] currecntKeys=sorted_map.keySet().toArray();\n\n assertArrayEquals(targetKeys,currecntKeys);\n}\n" }, { "answer_id": 7166058, "author": "didxga", "author_id": 231010, "author_profile": "https://Stackoverflow.com/users/231010", "pm_score": 2, "selected": false, "text": " /**\n\n * Sort a map according to values.\n\n * @param <K> the key of the map.\n * @param <V> the value to sort according to.\n * @param mapToSort the map to sort.\n\n * @return a map sorted on the values.\n\n */ \npublic static <K, V extends Comparable< ? super V>> Map<K, V>\nsortMapByValues(final Map <K, V> mapToSort)\n{\n List<Map.Entry<K, V>> entries =\n new ArrayList<Map.Entry<K, V>>(mapToSort.size()); \n\n entries.addAll(mapToSort.entrySet());\n\n Collections.sort(entries,\n new Comparator<Map.Entry<K, V>>()\n {\n @Override\n public int compare(\n final Map.Entry<K, V> entry1,\n final Map.Entry<K, V> entry2)\n {\n return entry1.getValue().compareTo(entry2.getValue());\n }\n }); \n\n Map<K, V> sortedMap = new LinkedHashMap<K, V>(); \n\n for (Map.Entry<K, V> entry : entries)\n {\n sortedMap.put(entry.getKey(), entry.getValue());\n\n } \n\n return sortedMap;\n\n}\n" }, { "answer_id": 7263116, "author": "malix", "author_id": 856468, "author_profile": "https://Stackoverflow.com/users/856468", "pm_score": 3, "selected": false, "text": "private <K, V extends Comparable<? super V>> List<Entry<K, V>> sort(Map<K, V> map) {\n List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());\n Collections.sort(list, new Comparator<Map.Entry<K, V>>() {\n public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n });\n\n return list;\n}\n" }, { "answer_id": 7268690, "author": "dimkar", "author_id": 923190, "author_profile": "https://Stackoverflow.com/users/923190", "pm_score": 2, "selected": false, "text": " public int compare(Object a, Object b) {\n\n if((Double)base.get(a) < (Double)base.get(b)) {\n return 1;\n } else if((Double)base.get(a) == (Double)base.get(b)) {\n return ((String)a).compareTo((String)b);\n } else {\n return -1;\n }\n }\n }\n" }, { "answer_id": 7561661, "author": "nibor", "author_id": 965886, "author_profile": "https://Stackoverflow.com/users/965886", "pm_score": 2, "selected": false, "text": "Map<String,Integer> tempMap=new HashMap<String,Integer>(inputUnsortedMap);\nLinkedHashMap<String,Integer> sortedOutputMap=new LinkedHashMap<String,Integer>();\n\nfor(int i=0;i<inputUnsortedMap.size();i++){\n Map.Entry<String,Integer> maxEntry=null;\n Integer maxValue=-1;\n for(Map.Entry<String,Integer> entry:tempMap.entrySet()){\n if(entry.getValue()>maxValue){\n maxValue=entry.getValue();\n maxEntry=entry;\n }\n }\n tempMap.remove(maxEntry.getKey());\n sortedOutputMap.put(maxEntry.getKey(),maxEntry.getValue());\n}\n" }, { "answer_id": 8647597, "author": "Sebastien Lorber", "author_id": 82609, "author_profile": "https://Stackoverflow.com/users/82609", "pm_score": 2, "selected": false, "text": "// If you want to sort a map by value, and if there can be twice the same value:\n\n// here is your original map\nMap<String,Integer> mapToSortByValue = new HashMap<String, Integer>();\nmapToSortByValue.put(\"A\", 3);\nmapToSortByValue.put(\"B\", 1);\nmapToSortByValue.put(\"C\", 3);\nmapToSortByValue.put(\"D\", 5);\nmapToSortByValue.put(\"E\", -1);\nmapToSortByValue.put(\"F\", 1000);\nmapToSortByValue.put(\"G\", 79);\nmapToSortByValue.put(\"H\", 15);\n\n// Sort all the map entries by value\nSet<Map.Entry<String,Integer>> set = new TreeSet<Map.Entry<String,Integer>>(\n new Comparator<Map.Entry<String,Integer>>(){\n @Override\n public int compare(Map.Entry<String,Integer> obj1, Map.Entry<String,Integer> obj2) {\n Integer val1 = obj1.getValue();\n Integer val2 = obj2.getValue();\n // DUPLICATE VALUE CASE\n // If the values are equals, we can't return 0 because the 2 entries would be considered\n // as equals and one of them would be deleted (because we use a set, no duplicate, remember!)\n int compareValues = val1.compareTo(val2);\n if ( compareValues == 0 ) {\n String key1 = obj1.getKey();\n String key2 = obj2.getKey();\n int compareKeys = key1.compareTo(key2);\n if ( compareKeys == 0 ) {\n // what you return here will tell us if you keep REAL KEY-VALUE duplicates in your set\n // if you want to, do whatever you want but do not return 0 (but don't break the comparator contract!)\n return 0;\n }\n return compareKeys;\n }\n return compareValues;\n }\n }\n);\nset.addAll(mapToSortByValue.entrySet());\n\n\n// OK NOW OUR SET IS SORTED COOL!!!!\n\n// And there's nothing more to do: the entries are sorted by value!\nfor ( Map.Entry<String,Integer> entry : set ) {\n System.out.println(\"Set entries: \" + entry.getKey() + \" -> \" + entry.getValue());\n}\n\n\n\n\n// But if you add them to an hashmap\nMap<String,Integer> myMap = new HashMap<String,Integer>();\n// When iterating over the set the order is still good in the println...\nfor ( Map.Entry<String,Integer> entry : set ) {\n System.out.println(\"Added to result map entries: \" + entry.getKey() + \" \" + entry.getValue());\n myMap.put(entry.getKey(), entry.getValue());\n}\n\n// But once they are in the hashmap, the order is not kept!\nfor ( Integer value : myMap.values() ) {\n System.out.println(\"Result map values: \" + value);\n}\n// Also this way doesn't work:\n// Logic because the entryset is a hashset for hashmaps and not a treeset\n// (and even if it was a treeset, it would be on the keys only)\nfor ( Map.Entry<String,Integer> entry : myMap.entrySet() ) {\n System.out.println(\"Result map entries: \" + entry.getKey() + \" -> \" + entry.getValue());\n}\n\n\n// CONCLUSION:\n// If you want to iterate on a map ordered by value, you need to remember:\n// 1) Maps are only sorted by keys, so you can't sort them directly by value\n// 2) So you simply CAN'T return a map to a sortMapByValue function\n// 3) You can't reverse the keys and the values because you have duplicate values\n// This also means you can't neither use Guava/Commons bidirectionnal treemaps or stuff like that\n\n// SOLUTIONS\n// So you can:\n// 1) only sort the values which is easy, but you loose the key/value link (since you have duplicate values)\n// 2) sort the map entries, but don't forget to handle the duplicate value case (like i did)\n// 3) if you really need to return a map, use a LinkedHashMap which keep the insertion order\n Set entries: E -> -1\nSet entries: B -> 1\nSet entries: A -> 3\nSet entries: C -> 3\nSet entries: D -> 5\nSet entries: H -> 15\nSet entries: G -> 79\nSet entries: F -> 1000\nAdded to result map entries: E -1\nAdded to result map entries: B 1\nAdded to result map entries: A 3\nAdded to result map entries: C 3\nAdded to result map entries: D 5\nAdded to result map entries: H 15\nAdded to result map entries: G 79\nAdded to result map entries: F 1000\nResult map values: 5\nResult map values: -1\nResult map values: 1000\nResult map values: 79\nResult map values: 3\nResult map values: 1\nResult map values: 3\nResult map values: 15\nResult map entries: D -> 5\nResult map entries: E -> -1\nResult map entries: F -> 1000\nResult map entries: G -> 79\nResult map entries: A -> 3\nResult map entries: B -> 1\nResult map entries: C -> 3\nResult map entries: H -> 15\n" }, { "answer_id": 10808650, "author": "ciamej", "author_id": 821497, "author_profile": "https://Stackoverflow.com/users/821497", "pm_score": 3, "selected": false, "text": "Collections.sort Arrays.sort Collections.sort public static <T extends Comparable<? super T>> void sort(List<T> list) {\n Object[] a = list.toArray();\n Arrays.sort(a);\n ListIterator<T> i = list.listIterator();\n for (int j=0; j<a.length; j++) {\n i.next();\n i.set((T)a[j]);\n }\n}\n toArray Arrays.sort public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) \n{\n @SuppressWarnings(\"unchecked\")\n Map.Entry<K,V>[] array = map.entrySet().toArray(new Map.Entry[map.size()]);\n\n Arrays.sort(array, new Comparator<Map.Entry<K, V>>() \n {\n public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) \n {\n return e1.getValue().compareTo(e2.getValue());\n }\n });\n\n Map<K, V> result = new LinkedHashMap<K, V>();\n for (Map.Entry<K, V> entry : array)\n result.put(entry.getKey(), entry.getValue());\n\n return result;\n}\n" }, { "answer_id": 12172924, "author": "Rashid C Y", "author_id": 1619400, "author_profile": "https://Stackoverflow.com/users/1619400", "pm_score": -1, "selected": false, "text": " Map<String, String> unsortedMap = new HashMap<String, String>();\n\n unsortedMap.put(\"E\", \"E Val\");\n unsortedMap.put(\"F\", \"F Val\");\n unsortedMap.put(\"H\", \"H Val\");\n unsortedMap.put(\"B\", \"B Val\");\n unsortedMap.put(\"C\", \"C Val\");\n unsortedMap.put(\"A\", \"A Val\");\n unsortedMap.put(\"G\", \"G Val\");\n unsortedMap.put(\"D\", \"D Val\");\n\n Map<String, String> sortedMap = new TreeMap<String, String>(unsortedMap);\n\n System.out.println(\"\\nAfter sorting..\");\n for (Map.Entry <String, String> mapEntry : sortedMap.entrySet()) {\n System.out.println(mapEntry.getKey() + \" \\t\" + mapEntry.getValue());\n" }, { "answer_id": 13438052, "author": "cuneyt", "author_id": 1833089, "author_profile": "https://Stackoverflow.com/users/1833089", "pm_score": 3, "selected": false, "text": "public int compare(String a, String b) {\n if (base.get(a) > base.get(b)) {\n return 1;\n } else if (base.get(a) < base.get(b)){\n return -1;\n } \n\n return 0;\n // returning 0 would merge keys\n }\n" }, { "answer_id": 14795215, "author": "Sujan Reddy A", "author_id": 2056362, "author_profile": "https://Stackoverflow.com/users/2056362", "pm_score": 4, "selected": false, "text": "class MyComparator implements Comparator<Object> {\n\n Map<String, Integer> map;\n\n public MyComparator(Map<String, Integer> map) {\n this.map = map;\n }\n\n public int compare(Object o1, Object o2) {\n\n if (map.get(o2) == map.get(o1))\n return 1;\n else\n return ((Integer) map.get(o2)).compareTo((Integer) \n map.get(o1));\n\n }\n}\n Map<String, Integer> lMap = new HashMap<String, Integer>();\n lMap.put(\"A\", 35);\n lMap.put(\"B\", 75);\n lMap.put(\"C\", 50);\n lMap.put(\"D\", 50);\n\n MyComparator comparator = new MyComparator(lMap);\n\n Map<String, Integer> newMap = new TreeMap<String, Integer>(comparator);\n newMap.putAll(lMap);\n System.out.println(newMap);\n {B=75, D=50, C=50, A=35}\n" }, { "answer_id": 17904414, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 2, "selected": false, "text": "TreeMap<Integer, Collection<String>> sortedMap = new TreeMap<>(\n Multimaps.invertFrom(Multimaps.forMap(originalMap), \n ArrayListMultimap.<Integer, String>create()).asMap());\n" }, { "answer_id": 19563077, "author": "rohan kamat", "author_id": 2335562, "author_profile": "https://Stackoverflow.com/users/2335562", "pm_score": -1, "selected": false, "text": "Map<String, String> map= new TreeMap<String, String>(unsortMap);\n" }, { "answer_id": 20089342, "author": "gdejohn", "author_id": 464306, "author_profile": "https://Stackoverflow.com/users/464306", "pm_score": 4, "selected": false, "text": "import static java.util.Map.Entry.comparingByValue;\nimport static java.util.stream.Collectors.toList;\n\n<K, V> List<Entry<K, V>> sort(Map<K, V> map, Comparator<? super V> comparator) {\n return map.entrySet().stream().sorted(comparingByValue(comparator)).collect(toList());\n}\n <K, V extends Comparable<? super V>> List<Entry<K, V>> sort(Map<K, V> map) {\n return map.entrySet().stream().sorted(comparingByValue()).collect(toList());\n}\n <K, V extends Comparable<? super V>> Iterable<Entry<K, V>> sort(Map<K, V> map) {\n return () -> map.entrySet().stream().sorted(comparingByValue()).iterator();\n}\n" }, { "answer_id": 22132422, "author": "assylias", "author_id": 829571, "author_profile": "https://Stackoverflow.com/users/829571", "pm_score": 7, "selected": false, "text": "Map<K, V> sortedMap = map.entrySet().stream()\n .sorted(Entry.comparingByValue())\n .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n" }, { "answer_id": 23215184, "author": "RobotMan", "author_id": 2491301, "author_profile": "https://Stackoverflow.com/users/2491301", "pm_score": 2, "selected": false, "text": "class MapUtil {\n\n public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ){\n ValueComparator<K,V> bvc = new ValueComparator<K,V>(map);\n TreeMap<K,V> sorted_map = new TreeMap<K,V>(bvc);\n sorted_map.putAll(map);\n return sorted_map;\n }\n\n}\n\nclass ValueComparator<K, V extends Comparable<? super V>> implements Comparator<K> {\n\n Map<K, V> base;\n public ValueComparator(Map<K, V> base) {\n this.base = base;\n }\n\n public int compare(K a, K b) {\n int result = (base.get(a).compareTo(base.get(b)));\n if (result == 0) result=1;\n // returning 0 would merge keys\n return result;\n }\n}\n" }, { "answer_id": 23846961, "author": "Brian Goetz", "author_id": 3553087, "author_profile": "https://Stackoverflow.com/users/3553087", "pm_score": 9, "selected": false, "text": "Stream<Map.Entry<K,V>> sorted =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue());\n Stream<Map.Entry<K,V>> sorted =\n map.entrySet().stream()\n .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));\n Stream<Map.Entry<K,V>> sorted =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue(comparator));\n Map<K,V> topTen =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n .limit(10)\n .collect(Collectors.toMap(\n Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n LinkedHashMap System.out map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue())\n .forEach(System.out::println);\n" }, { "answer_id": 33801276, "author": "Nilesh Jadav", "author_id": 3966892, "author_profile": "https://Stackoverflow.com/users/3966892", "pm_score": 3, "selected": false, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry; \n\npublic class OrderByValue {\n\n public static void main(String a[]){\n Map<String, Integer> map = new HashMap<String, Integer>();\n map.put(\"java\", 20);\n map.put(\"C++\", 45);\n map.put(\"Unix\", 67);\n map.put(\"MAC\", 26);\n map.put(\"Why this kolavari\", 93);\n Set<Entry<String, Integer>> set = map.entrySet();\n List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);\n Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()\n {\n public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )\n {\n return (o1.getValue()).compareTo( o2.getValue() );//Ascending order\n //return (o2.getValue()).compareTo( o1.getValue() );//Descending order\n }\n } );\n for(Map.Entry<String, Integer> entry:list){\n System.out.println(entry.getKey()+\" ==== \"+entry.getValue());\n }\n }}\n java ==== 20\n\nMAC ==== 26\n\nC++ ==== 45\n\nUnix ==== 67\n\nWhy this kolavari ==== 93\n" }, { "answer_id": 34295647, "author": "Uxío", "author_id": 724991, "author_profile": "https://Stackoverflow.com/users/724991", "pm_score": -1, "selected": false, "text": "public List<String> getList(Map<String, Integer> myMap) {\n String[] copyArray = new String[myMap.size()];\n for (Entry<String, Integer> entry : myMap.entrySet()) {\n copyArray[entry.getValue()] = entry.getKey();\n }\n return Arrays.asList(copyArray);\n}\n" }, { "answer_id": 34802755, "author": "Bruce Zu", "author_id": 913717, "author_profile": "https://Stackoverflow.com/users/913717", "pm_score": -1, "selected": false, "text": " static <K extends Comparable<? super K>, V extends Comparable<? super V>>\n Map sortByValueInDescendingOrder(final Map<K, V> map) {\n Map re = new TreeMap(new Comparator<K>() {\n @Override\n public int compare(K o1, K o2) {\n if (map.get(o1) == null || map.get(o2) == null) {\n return -o1.compareTo(o2);\n }\n int result = -map.get(o1).compareTo(map.get(o2));\n if (result != 0) {\n return result;\n }\n return -o1.compareTo(o2);\n }\n });\n re.putAll(map);\n return re;\n }\n @Test(timeout = 3000l, expected = Test.None.class)\n public void testSortByValueInDescendingOrder() {\n char[] arr = \"googler\".toCharArray();\n Map<Character, Integer> charToTimes = new HashMap();\n for (int i = 0; i < arr.length; i++) {\n Integer times = charToTimes.get(arr[i]);\n charToTimes.put(arr[i], times == null ? 1 : times + 1);\n }\n Map sortedByTimes = sortByValueInDescendingOrder(charToTimes);\n Assert.assertEquals(charToTimes.toString(), \"{g=2, e=1, r=1, o=2, l=1}\");\n Assert.assertEquals(sortedByTimes.toString(), \"{o=2, g=2, r=1, l=1, e=1}\");\n Assert.assertEquals(sortedByTimes.containsKey('a'), false);\n Assert.assertEquals(sortedByTimes.get('a'), null);\n Assert.assertEquals(sortedByTimes.get('g'), 2);\n Assert.assertEquals(sortedByTimes.equals(charToTimes), true);\n }\n" }, { "answer_id": 36819520, "author": "David Bleckmann", "author_id": 1760575, "author_profile": "https://Stackoverflow.com/users/1760575", "pm_score": 3, "selected": false, "text": "import java.util.*;\n\n/**\n * A map where {@link #keySet()} and {@link #entrySet()} return sets ordered\n * by associated values based on the the comparator provided at construction\n * time. The order of two or more keys with identical values is not defined.\n * <p>\n * Several contracts of the Map interface are not satisfied by this minimal\n * implementation.\n */\npublic class ValueSortedMap<K, V> extends HashMap<K, V> {\n protected Map<V, Collection<K>> valueToKeysMap;\n\n // uses natural order of value object, if any\n public ValueSortedMap() {\n this((Comparator<? super V>) null);\n }\n\n public ValueSortedMap(Comparator<? super V> valueComparator) {\n this.valueToKeysMap = new TreeMap<V, Collection<K>>(valueComparator);\n }\n\n public boolean containsValue(Object o) {\n return valueToKeysMap.containsKey(o);\n }\n\n public V put(K k, V v) {\n V oldV = null;\n if (containsKey(k)) {\n oldV = get(k);\n valueToKeysMap.get(oldV).remove(k);\n }\n super.put(k, v);\n if (!valueToKeysMap.containsKey(v)) {\n Collection<K> keys = new ArrayList<K>();\n keys.add(k);\n valueToKeysMap.put(v, keys);\n } else {\n valueToKeysMap.get(v).add(k);\n }\n return oldV;\n }\n\n public void putAll(Map<? extends K, ? extends V> m) {\n for (Map.Entry<? extends K, ? extends V> e : m.entrySet())\n put(e.getKey(), e.getValue());\n }\n\n public V remove(Object k) {\n V oldV = null;\n if (containsKey(k)) {\n oldV = get(k);\n super.remove(k);\n valueToKeysMap.get(oldV).remove(k);\n }\n return oldV;\n }\n\n public void clear() {\n super.clear();\n valueToKeysMap.clear();\n }\n\n public Set<K> keySet() {\n LinkedHashSet<K> ret = new LinkedHashSet<K>(size());\n for (V v : valueToKeysMap.keySet()) {\n Collection<K> keys = valueToKeysMap.get(v);\n ret.addAll(keys);\n }\n return ret;\n }\n\n public Set<Map.Entry<K, V>> entrySet() {\n LinkedHashSet<Map.Entry<K, V>> ret = new LinkedHashSet<Map.Entry<K, V>>(size());\n for (Collection<K> keys : valueToKeysMap.values()) {\n for (final K k : keys) {\n final V v = get(k);\n ret.add(new Map.Entry<K,V>() {\n public K getKey() {\n return k;\n }\n\n public V getValue() {\n return v;\n }\n\n public V setValue(V v) {\n throw new UnsupportedOperationException();\n }\n });\n }\n }\n return ret;\n }\n}\n" }, { "answer_id": 39659333, "author": "Alexander", "author_id": 4525620, "author_profile": "https://Stackoverflow.com/users/4525620", "pm_score": 1, "selected": false, "text": "public static void main(String[] args) {\n HashMap<String, String> map = new HashMap<>();\n map.put(\"Z\", \"E\");\n map.put(\"G\", \"A\");\n map.put(\"D\", \"C\");\n map.put(\"E\", null);\n map.put(\"O\", \"C\");\n map.put(\"L\", \"D\");\n map.put(\"Q\", \"B\");\n map.put(\"A\", \"F\");\n map.put(null, \"X\");\n MapEntryComparator mapEntryComparator = new MapEntryComparator();\n\n List<Entry<String,String>> entryList = new ArrayList<>(map.entrySet());\n Collections.sort(entryList, mapEntryComparator);\n\n for (Entry<String, String> entry : entryList) {\n System.out.println(entry.getKey() + \" : \" + entry.getValue());\n }\n\n}\n" }, { "answer_id": 40852723, "author": "user_3380739", "author_id": 3380739, "author_profile": "https://Stackoverflow.com/users/3380739", "pm_score": 2, "selected": false, "text": "Map<String, Integer> map = N.asMap(\"a\", 2, \"b\", 3, \"c\", 1, \"d\", 2);\nMap<String, Integer> sortedMap = Stream.of(map.entrySet()).sorted(Map.Entry.comparingByValue()).toMap(e -> e.getKey(), e -> e.getValue(),\n LinkedHashMap::new);\nN.println(sortedMap);\n// output: {c=1, a=2, d=2, b=3}\n" }, { "answer_id": 48068780, "author": "Arun Raaj", "author_id": 4334162, "author_profile": "https://Stackoverflow.com/users/4334162", "pm_score": 0, "selected": false, "text": "public class Test {\n public static void main(String[] args) {\n TreeMap<Integer, String> hm=new TreeMap();\n hm.put(3, \"arun singh\");\n hm.put(5, \"vinay singh\");\n hm.put(1, \"bandagi singh\");\n hm.put(6, \"vikram singh\");\n hm.put(2, \"panipat singh\");\n hm.put(28, \"jakarta singh\");\n\n ArrayList<String> al=new ArrayList(hm.values());\n Collections.sort(al, new myComparator());\n\n System.out.println(\"//sort by values \\n\");\n for(String obj: al){\n for(Map.Entry<Integer, String> map2:hm.entrySet()){\n if(map2.getValue().equals(obj)){\n System.out.println(map2.getKey()+\" \"+map2.getValue());\n }\n } \n }\n }\n}\n\nclass myComparator implements Comparator{\n @Override\n public int compare(Object o1, Object o2) {\n String o3=(String) o1;\n String o4 =(String) o2;\n return o3.compareTo(o4);\n } \n}\n //sort by values \n\n3 arun singh\n1 bandagi singh\n28 jakarta singh\n2 panipat singh\n6 vikram singh\n5 vinay singh\n" }, { "answer_id": 50406218, "author": "Pankaj Singhal", "author_id": 820410, "author_profile": "https://Stackoverflow.com/users/820410", "pm_score": 3, "selected": false, "text": "LinkedHashMap sortedByValueMap = map.entrySet().stream()\n .sorted(comparing(Entry<Key,Value>::getValue).thenComparing(Entry::getKey)) //first sorting by Value, then sorting by Key(entries with same value)\n .collect(LinkedHashMap::new,(map,entry) -> map.put(entry.getKey(),entry.getValue()),LinkedHashMap::putAll);\n comparing(Entry<Key,Value>::getValue).thenComparing(Entry::getKey)\n comparing(Entry<Key,Value>::getValue).thenComparing(Entry::getKey).reversed()\n" }, { "answer_id": 51457226, "author": "Kenston Choi", "author_id": 241379, "author_profile": "https://Stackoverflow.com/users/241379", "pm_score": 1, "selected": false, "text": "Map as all the code here is in the public domain // required to access LinkEntry.before and LinkEntry.after\npackage org.apache.commons.collections.map;\n\n// SNIP: imports\n\n/**\n* map implementation based on LinkedMap that maintains a sorted list of\n* values for iteration\n*/\npublic class ValueSortedHashMap extends LinkedMap {\n private final boolean _asc;\n\n // don't use super()!\n public ValueSortedHashMap(final boolean asc) {\n super(DEFAULT_CAPACITY);\n _asc = asc;\n }\n\n // SNIP: some more constructors with initial capacity and the like\n\n protected void addEntry(final HashEntry entry, final int hashIndex) {\n final LinkEntry link = (LinkEntry) entry;\n insertSorted(link);\n data[hashIndex] = entry;\n }\n\n protected void updateEntry(final HashEntry entry, final Object newValue) {\n entry.setValue(newValue);\n final LinkEntry link = (LinkEntry) entry;\n link.before.after = link.after;\n link.after.before = link.before;\n link.after = link.before = null;\n insertSorted(link);\n }\n\n private void insertSorted(final LinkEntry link) {\n LinkEntry cur = header;\n // iterate whole list, could (should?) be replaced with quicksearch\n // start at end to optimize speed for in-order insertions\n while ((cur = cur.before) != header & amp; & amp; !insertAfter(cur, link)) {}\n link.after = cur.after;\n link.before = cur;\n cur.after.before = link;\n cur.after = link;\n }\n\n protected boolean insertAfter(final LinkEntry cur, final LinkEntry link) {\n if (_asc) {\n return ((Comparable) cur.getValue())\n .compareTo((V) link.getValue()) & lt; = 0;\n } else {\n return ((Comparable) cur.getValue())\n .compareTo((V) link.getValue()) & gt; = 0;\n }\n }\n\n public boolean isAscending() {\n return _asc;\n }\n}\n Map LinkedHashMap values() keyset() entryset() put public class SortByValueMap<K, V> implements Map<K, V> {\n\n private boolean isSortingNeeded = false;\n\n private final Map<K, V> map = new LinkedHashMap<>();\n\n @Override\n public V put(K key, V value) {\n isSortingNeeded = true;\n return map.put(key, value);\n }\n\n @Override\n public void putAll(Map<? extends K, ? extends V> map) {\n isSortingNeeded = true;\n map.putAll(map);\n }\n\n @Override\n public Set<K> keySet() {\n sort();\n return map.keySet();\n }\n\n @Override\n public Set<Entry<K, V>> entrySet() {\n sort();\n return map.entrySet();\n }\n\n @Override\n public Collection<V> values() {\n sort();\n return map.values();\n }\n\n private void sort() {\n if (!isSortingNeeded) {\n return;\n }\n\n List<Entry<K, V>> list = new ArrayList<>(size());\n\n for (Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); it.hasNext();) {\n Map.Entry<K, V> entry = it.next();\n list.add(entry);\n it.remove();\n }\n\n Collections.sort(list);\n\n for (Entry<K, V> entry : list) {\n map.put(entry.getKey(), entry.getValue());\n }\n\n isSortingNeeded = false;\n }\n\n @Override\n public String toString() {\n sort();\n return map.toString();\n }\n}\n" }, { "answer_id": 51971086, "author": "smart-developer", "author_id": 5218673, "author_profile": "https://Stackoverflow.com/users/5218673", "pm_score": 1, "selected": false, "text": "public static Map<K, V> sortMapByValue(Map<K, V> inputMap) {\n\n Set<Entry<K, V>> set = inputMap.entrySet();\n List<Entry<K, V>> list = new ArrayList<Entry<K, V>>(set);\n\n Collections.sort(list, new Comparator<Map.Entry<K, V>>()\n {\n @Override\n public int compare(Entry<K, V> o1, Entry<K, V> o2) {\n return (o1.getValue()).compareTo( o2.getValue() ); //Ascending order\n }\n } );\n\n Map<K, V> sortedMap = new LinkedHashMap<>();\n\n for(Map.Entry<K, V> entry : list){\n sortedMap.put(entry.getKey(), entry.getValue());\n }\n\n return sortedMap;\n}\n Note: LinkedHashMap TreeMap public static void main(String[] args) {\n Map<String, String> map = new HashMap<>();\n map.put(\"3\", \"three\");\n map.put(\"1\", \"one\");\n map.put(\"5\", \"five\");\n System.out.println(\"Input Map:\" + map);\n System.out.println(\"Sorted Map:\" + sortMapByValue(map));\n}\n Input Map:{1=one, 3=three, 5=five}\nSorted Map:{5=five, 1=one, 3=three}\n" }, { "answer_id": 52688845, "author": "parsecer", "author_id": 4759176, "author_profile": "https://Stackoverflow.com/users/4759176", "pm_score": 2, "selected": false, "text": "sortHashMap HashMap<String, Long> public class Test {\n public static void main(String[] args) {\n HashMap<String, Long> hashMap = new HashMap<>();\n hashMap.put(\"Cat\", (long) 4);\n hashMap.put(\"Human\", (long) 2);\n hashMap.put(\"Dog\", (long) 4);\n hashMap.put(\"Fish\", (long) 0);\n hashMap.put(\"Tree\", (long) 1);\n hashMap.put(\"Three-legged-human\", (long) 3);\n hashMap.put(\"Monkey\", (long) 2);\n\n System.out.println(hashMap); //{Human=2, Cat=4, Three-legged-human=3, Monkey=2, Fish=0, Tree=1, Dog=4}\n System.out.println(sortHashMap(hashMap)); //{Cat=4, Dog=4, Three-legged-human=3, Human=2, Monkey=2, Tree=1, Fish=0}\n }\n\n public LinkedHashMap<String, Long> sortHashMap(HashMap<String, Long> unsortedMap) {\n LinkedHashMap<String, Long> result = new LinkedHashMap<>();\n\n //add String keys to an array: the array would get sorted, based on those keys' values\n ArrayList<String> sortedKeys = new ArrayList<>();\n for (String key: unsortedMap.keySet()) {\n sortedKeys.add(key);\n }\n\n //sort the ArrayList<String> of keys \n for (int i=0; i<unsortedMap.size(); i++) {\n for (int j=1; j<sortedKeys.size(); j++) {\n if (unsortedMap.get(sortedKeys.get(j)) > unsortedMap.get(sortedKeys.get(j-1))) {\n String temp = sortedKeys.get(j);\n sortedKeys.set(j, sortedKeys.get(j-1));\n sortedKeys.set(j-1, temp);\n }\n }\n }\n\n // construct the result Map\n for (String key: sortedKeys) {\n result.put(key, unsortedMap.get(key));\n }\n\n return result;\n }\n}\n" }, { "answer_id": 57164142, "author": "Praveen Kumar Mekala", "author_id": 4675109, "author_profile": "https://Stackoverflow.com/users/4675109", "pm_score": 2, "selected": false, "text": "List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());\n Collections.sort(list, (obj1, obj2) -> obj2.getValue().compareTo(obj1.getValue()));\n Map<String, Integer> resultMap = new LinkedHashMap<>();\n list.forEach(arg0 -> {\n resultMap.put(arg0.getKey(), arg0.getValue());\n });\n System.out.println(resultMap);\n" }, { "answer_id": 57682518, "author": "Stanislav Levental", "author_id": 942689, "author_profile": "https://Stackoverflow.com/users/942689", "pm_score": 1, "selected": false, "text": "public static <K,V extends Comparable<V>>SortedMap<K,V> sortByValue(Map<K,V> original){\n var comparator = Ordering.natural()\n .reverse() // highest first\n .nullsLast()\n .onResultOf(Functions.forMap(original, null))\n .compound(Ordering.usingToString());\n return ImmutableSortedMap.copyOf(original, comparator);\n}\n" }, { "answer_id": 58824564, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 1, "selected": false, "text": "Map<Double,List<Entry<String,Double>>> sorted =\nmap.entrySet().stream().collect( Collectors.groupingBy( Entry::getValue, TreeMap::new,\n Collectors.mapping( Function.identity(), Collectors.toList() ) ) );\n {67.3=[D=67.3], 67.4=[B=67.4, C=67.4], 99.5=[A=99.5]} sorted.entrySet().forEach( e -> e.getValue().forEach( l -> System.out.println( l ) ) );\n D=67.3 B=67.4 C=67.4 A=99.5" }, { "answer_id": 58970003, "author": "Arpan Saini", "author_id": 7353562, "author_profile": "https://Stackoverflow.com/users/7353562", "pm_score": 4, "selected": false, "text": " Map<String, Integer> wordCounts = new HashMap<>();\n wordCounts.put(\"USA\", 100);\n wordCounts.put(\"jobs\", 200);\n wordCounts.put(\"software\", 50);\n wordCounts.put(\"technology\", 70);\n wordCounts.put(\"opportunity\", 200);\n Map<String,Integer> sortedMap = wordCounts.entrySet().\n stream().\n sorted(Map.Entry.comparingByValue()).\n collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n System.out.println(sortedMap);\n \n Map<String,Integer> sortedMapReverseOrder = wordCounts.entrySet().\n stream().\n sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).\n collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));\n System.out.println(sortedMapReverseOrder);\n" }, { "answer_id": 59212736, "author": "Mimu Saha Tishan", "author_id": 6109034, "author_profile": "https://Stackoverflow.com/users/6109034", "pm_score": 2, "selected": false, "text": "//Create a list by HashMap\nList<Map.Entry<String, Double>> list = new LinkedList<>(hashMap.entrySet());\n\n//Sorting the list\nCollections.sort(list, new Comparator<Map.Entry<String, Double>>() {\n public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {\n return (o1.getValue()).compareTo(o2.getValue());\n }\n});\n\n//put data from sorted list to hashmap\nHashMap<String, Double> sortedData = new LinkedHashMap<>();\nfor (Map.Entry<String, Double> data : list) {\n sortedData.put(data.getKey(), data.getValue());\n}\n\nSystem.out.print(sortedData);\n" }, { "answer_id": 60056821, "author": "JGFMK", "author_id": 495157, "author_profile": "https://Stackoverflow.com/users/495157", "pm_score": 2, "selected": false, "text": "import static java.util.Comparator.comparingInt;\nimport static java.util.stream.Collectors.toMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nclass Utils {\n public static Map<String, Integer> sortMapBasedOnValues(Map<String, Integer> map, boolean descending) {\n int multiplyBy = (descending) ? -1: 1;\n Map<String, Integer> sorted = map.entrySet().stream()\n .sorted(comparingInt(e -> multiplyBy * e.getValue() ))\n .collect(toMap(\n Map.Entry::getKey, \n Map.Entry::getValue,\n (a, b) -> { throw new AssertionError();},\n LinkedHashMap::new\n ));\n return sorted;\n }\n}\n" }, { "answer_id": 60676473, "author": "avi", "author_id": 10908536, "author_profile": "https://Stackoverflow.com/users/10908536", "pm_score": 3, "selected": false, "text": "Map<String, Object> mapToSort = new HashMap<>();\n\nList<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());\n\nCollections.sort(list, Comparator.comparing(o -> o.getValue().getAttribute()));\n\nHashMap<String, Object> sortedMap = new LinkedHashMap<>();\nfor (Map.Entry<String, Object> map : list) {\n sortedMap.put(map.getKey(), map.getValue());\n}\n Map<String, Object> mapToSort = new HashMap<>();\n\nList<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());\n\nCollections.sort(list, new Comparator<Map.Entry<String, Object>>() {\n @Override\n public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {\n return o1.getValue().getAttribute().compareTo(o2.getValue().getAttribute()); \n }\n});\n\nHashMap<String, Object> sortedMap = new LinkedHashMap<>();\nfor (Map.Entry<String, Object> map : list) {\n sortedMap.put(map.getKey(), map.getValue());\n}\n" }, { "answer_id": 60932599, "author": "thenish", "author_id": 4088988, "author_profile": "https://Stackoverflow.com/users/4088988", "pm_score": 2, "selected": false, "text": "map = your hashmap;\n\nList<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());\nCollections.sort(list, new cm());//IMP\n\nHashMap<String, Integer> sorted = new LinkedHashMap<String, Integer>();\nfor(Map.Entry<String, Integer> en: list){\n sorted.put(en.getKey(),en.getValue());\n}\n\nSystem.out.println(sorted);//sorted hashmap\n class cm implements Comparator<Map.Entry<String, Integer>>{\n @Override\n public int compare(Map.Entry<String, Integer> a, \n Map.Entry<String, Integer> b)\n {\n return (a.getValue()).compareTo(b.getValue());\n }\n}\n" }, { "answer_id": 63848163, "author": "BlueJapan", "author_id": 8288930, "author_profile": "https://Stackoverflow.com/users/8288930", "pm_score": 1, "selected": false, "text": "map = {10 = 3, 11 = 1,12 = 2} \n PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (map.get(a) - map.get(b));\nfor(int key: map.keySets()) {\n pq.add(key);\n if(pq.size() > 2) {\n pq.poll();\n }\n}\n// Now pq has the top 2 most frequent key based on value. It sorts the value. \n" }, { "answer_id": 65917002, "author": "Supreet Singh", "author_id": 6856020, "author_profile": "https://Stackoverflow.com/users/6856020", "pm_score": 3, "selected": false, "text": "public static LinkedHashMap<Integer, String> sortByValue(HashMap<Integer, String> map) {\n\n List<Map.Entry<Integer, String>> list = new ArrayList<>(map.entrySet());\n list.sort(Map.Entry.comparingByValue());\n LinkedHashMap<Integer, String> sortedMap = new LinkedHashMap<>();\n list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));\n return sortedMap;\n }\n" }, { "answer_id": 68509369, "author": "djklicks-dhananjay", "author_id": 11597506, "author_profile": "https://Stackoverflow.com/users/11597506", "pm_score": 2, "selected": false, "text": "Map<String, Integer> mp= new HashMap<>();\nmp.put(\"zebra\", 1);\nmp.put(\"blossom\", 2);\nmp.put(\"gemini\", 3);\nmp.put(\"opera\", 7);\nmp.put(\"adelaide\", 10);\n\nMap<String, Integer> resultMap= mp.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1, LinkedHashMap::new));\n Map<String, Integer> resultMap= mp.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1, LinkedHashMap::new));\n User u1= new User(\"hi\", 135);\nUser u2= new User(\"bismuth\", 900);\nUser u3= new User(\"alloy\", 675);\nUser u4= new User(\"jupiter\", 342);\nUser u5= new User(\"lily\", 941);\n\nMap<String, User> map2= new HashMap<>();\nmap2.put(\"zebra\", u3);\nmap2.put(\"blossom\", u5);\nmap2.put(\"gemini\", u1);\nmap2.put(\"opera\", u2);\nmap2.put(\"adelaide\", u4);\n\n\nMap<String, User> resultMap= \n map2.entrySet().stream().sorted(Map.Entry.<String, User>comparingByValue( (User o1, User o2)-> o1.getName().compareTo(o2.getName()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e2, LinkedHashMap::new));\n\n\n\nclass User\n {\n String name;\n int id;\n \n\npublic User(String name, int id) {\n super();\n this.name = name;\n this.id = id;\n}\npublic String getName() {\n return name;\n}\npublic void setName(String name) {\n this.name = name;\n}\npublic int getId() {\n return id;\n}\npublic void setId(int id) {\n this.id = id;\n}\n@Override\npublic String toString() {\n return \"User [name=\" + name + \", id=\" + id + \"]\";\n}\n@Override\npublic int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + id;\n result = prime * result + ((name == null) ? 0 : name.hashCode());\n return result;\n}\n@Override\npublic boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n User other = (User) obj;\n if (id != other.id)\n return false;\n if (name == null) {\n if (other.name != null)\n return false;\n } else if (!name.equals(other.name))\n return false;\n return true;\n\n\n }\n }\n" }, { "answer_id": 69993629, "author": "Jayavinoth", "author_id": 761348, "author_profile": "https://Stackoverflow.com/users/761348", "pm_score": 1, "selected": false, "text": "4 {0=0, 10=10, 20=20, 30=30, 4=4, 50=50, 60=60, 70=70} Map<String, String> sortedMap = new TreeMap<>Comparator.comparingInt(String::length)\n.thenComparing(Function.identity()));\n {0=0, 4=4, 10=10, 20=20, 30=30, 50=50, 60=60, 70=70}" }, { "answer_id": 70401747, "author": "Praveen Kishor", "author_id": 2680024, "author_profile": "https://Stackoverflow.com/users/2680024", "pm_score": 2, "selected": false, "text": " Map<String, Integer> map = new HashMap<>();\n map.put(\"b\", 2);\n map.put(\"a\", 1);\n map.put(\"d\", 4);\n map.put(\"c\", 3);\n \n // ----- Using Java 7 -------------------\n List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());\n Collections.sort(entries, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));\n System.out.println(entries); // [a=1, b=2, c=3, d=4]\n\n\n // ----- Using Java 8 Stream API --------\n map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println); // {a=1, b=2, c=3, d=4}\n\n \n" }, { "answer_id": 73163197, "author": "ADITYA AHLAWAT", "author_id": 15142774, "author_profile": "https://Stackoverflow.com/users/15142774", "pm_score": 0, "selected": false, "text": "Input : Key = Math, Value = 98\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Operating System, Value = 79\n Key = Networking, Value = 80\n\nOutput : Key = Operating System, Value = 79\n Key = Networking, Value = 80\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Math, Value = 98\nSolution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.\nBelow is the implementation of the above idea: \n\n\n\n\n// Java program to sort hashmap by values\nimport java.util.*;\nimport java.lang.*;\n \npublic class GFG {\n \n // function to sort hashmap by values\n public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)\n {\n // Create a list from elements of HashMap\n List<Map.Entry<String, Integer> > list =\n new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());\n \n // Sort the list\n Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {\n public int compare(Map.Entry<String, Integer> o1,\n Map.Entry<String, Integer> o2)\n {\n return (o1.getValue()).compareTo(o2.getValue());\n }\n });\n \n // put data from sorted list to hashmap\n HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();\n for (Map.Entry<String, Integer> aa : list) {\n temp.put(aa.getKey(), aa.getValue());\n }\n return temp;\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n \n HashMap<String, Integer> hm = new HashMap<String, Integer>();\n \n // enter data into hashmap\n hm.put(\"Math\", 98);\n hm.put(\"Data Structure\", 85);\n hm.put(\"Database\", 91);\n hm.put(\"Java\", 95);\n hm.put(\"Operating System\", 79);\n hm.put(\"Networking\", 80);\n Map<String, Integer> hm1 = sortByValue(hm);\n \n // print the sorted hashmap\n for (Map.Entry<String, Integer> en : hm1.entrySet()) {\n System.out.println(\"Key = \" + en.getKey() +\n \", Value = \" + en.getValue());\n }\n }\n}\nOutput\nKey = Operating System, Value = 79\nKey = Networking, Value = 80\nKey = Data Structure, Value = 85\nKey = Database, Value = 91\nKey = Java, Value = 95\nKey = Math, Value = 98\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9466/" ]
109,399
<p>I know there's JScript.NET, but it isn't the same as the JavaScript we know from the web.</p> <p>Does anyone know if there are any JavaScript based platforms/compilers for desktop development? Most specifically Windows desktop development.</p>
[ { "answer_id": 110861, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 3, "selected": false, "text": ".hta" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
109,417
<p>I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?</p>
[ { "answer_id": 109452, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 3, "selected": true, "text": "BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;\n//substitute your business object type for T \nT entity = bindingSource.Current as T;\n var table = dataGridView1.DataSource as DataTable;\n\n foreach(DataRow row in table.Rows)\n {\n foreach(DataColumn column in table.Columns)\n {\n Console.WriteLine(row[column]);\n }\n }\n" }, { "answer_id": 109477, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 1, "selected": false, "text": "for(int i =0; i < DataGridView.Rows.Count; i++){\n DataGridView.Rows.Columns[\"columnName\"].Text= \"\";\n} \n" }, { "answer_id": 109484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "namespace WindowsFormsApplication2\n{\n public partial class Form1 : Form\n {\n public static DataTable objDataTable = new DataTable(\"UpdateAddress\");\n\n public Form1()\n {\n InitializeComponent();\n\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Stream myStream = null;\n OpenFileDialog openFileDialog1 = new OpenFileDialog();\n\n openFileDialog1.InitialDirectory = \"c:\\\\\";\n openFileDialog1.Filter = \"csv files (*.csv)|*.txt|All files (*.*)|*.*\";\n openFileDialog1.FilterIndex = 2;\n openFileDialog1.RestoreDirectory = true;\n\n if (openFileDialog1.ShowDialog() == DialogResult.OK)\n {\n try\n {\n if ((myStream = openFileDialog1.OpenFile()) != null)\n {\n string fileName = openFileDialog1.FileName;\n\n List<string> dataFile = new List<string>();\n dataFile = ReadList(fileName);\n foreach (string item in dataFile)\n {\n string[] temp = item.Split(',');\n DataRow objDR = objDataTable.NewRow();\n objDR[\"EmployeeID\"] = temp[0].ToString();\n objDR[\"Street\"] = temp[1].ToString();\n objDR[\"POBox\"] = temp[2].ToString();\n objDR[\"City\"] = temp[3].ToString();\n objDR[\"State\"] = temp[4].ToString();\n objDR[\"Zip\"] = temp[5].ToString();\n objDR[\"Country\"] = temp[6].ToString();\n objDataTable.Rows.Add(objDR);\n\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error: Could not read file from disk. Original error: \" + ex.Message);\n }\n }\n }\n\n public static List<string> ReadList(string filename)\n {\n List<string> fileData = new List<string>();\n StreamReader sr = new StreamReader(filename);\n while (!sr.EndOfStream)\n fileData.Add(sr.ReadLine());\n return fileData;\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n objDataTable.Columns.Add(\"EmployeeID\", typeof(int));\n objDataTable.Columns.Add(\"Street\", typeof(string));\n objDataTable.Columns.Add(\"POBox\", typeof(string));\n objDataTable.Columns.Add(\"City\", typeof(string));\n objDataTable.Columns.Add(\"State\", typeof(string));\n objDataTable.Columns.Add(\"Zip\", typeof(string));\n objDataTable.Columns.Add(\"Country\", typeof(string));\n objDataTable.Columns.Add(\"Status\", typeof(string));\n\n dataGridView1.DataSource = objDataTable;\n dataGridView1.Refresh();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n // Displays a SaveFileDialog so the user can save the backup of AD address before the update\n // assigned to Button2.\n SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n saveFileDialog1.Filter = \"BAK Files|*.BAK\";\n saveFileDialog1.Title = \"Save AD Backup\";\n saveFileDialog1.ShowDialog();\n\n if (saveFileDialog1.FileName != \"\")\n {\n TextWriter fileOut = new StreamWriter(saveFileDialog1.FileName); \n //This is where I want read from the datagridview the EmployeeID column and use it in my BackupAddress method.\n }\n\n }\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,444
<p>Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:</p> <pre><code>C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg </code></pre> <p>This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.</p>
[ { "answer_id": 109454, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 3, "selected": true, "text": "stripslashes" }, { "answer_id": 109624, "author": "moltenform", "author_id": 18506, "author_profile": "https://Stackoverflow.com/users/18506", "pm_score": 2, "selected": false, "text": "\\\\" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
109,449
<p>Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?</p> <p>The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.</p>
[ { "answer_id": 109522, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": true, "text": "std::fstream FILE* std::fstream std::fstream FILE* funopen() std::stream FILE *funopen(\n const void *cookie,\n int (*readfn )(void *, char *, int),\n int (*writefn)(void *, const char *, int),\n fpos_t (*seekfn) (void *, fpos_t, int),\n int (*closefn)(void *)\n );\n FILE std::fstream" }, { "answer_id": 19749019, "author": "alfC", "author_id": 225186, "author_profile": "https://Stackoverflow.com/users/225186", "pm_score": 4, "selected": false, "text": "GCC clang #include<fstream>\n#include<ext/stdio_filebuf.h>\n\ntypedef std::basic_ofstream<char>::__filebuf_type buffer_t;\ntypedef __gnu_cxx::stdio_filebuf<char> io_buffer_t; \nFILE* cfile_impl(buffer_t* const fb){\n return (static_cast<io_buffer_t* const>(fb))->file(); //type std::__c_file\n}\n\nFILE* cfile(std::ofstream const& ofs){return cfile_impl(ofs.rdbuf());}\nFILE* cfile(std::ifstream const& ifs){return cfile_impl(ifs.rdbuf());}\n int main(){\n std::ofstream ofs(\"file.txt\");\n fprintf(cfile(ofs), \"sample1\");\n fflush(cfile(ofs)); // ofs << std::flush; doesn't help \n ofs << \"sample2\\n\";\n}\n stdio_filebuf static_cast<>() dynamic_cast<>() nullptr stdio_sync_filebuf file() fflush fprintf std::ofstream fflush ofs << flush std::stringstream stderr std::cerr fprintf(stderr, \"sample\") fprintf(cfile(std::cerr), \"sample\") FILE* cfile(std::ostream const& os){\n if(std::ofstream const* ofsP = dynamic_cast<std::ofstream const*>(&os)) return cfile(*ofsP);\n if(&os == &std::cerr) return stderr;\n if(&os == &std::cout) return stdout;\n if(&os == &std::clog) return stderr;\n if(dynamic_cast<std::ostringstream const*>(&os) != 0){\n throw std::runtime_error(\"don't know cannot extract FILE pointer from std::ostringstream\");\n }\n return 0; // stream not recognized\n}\nFILE* cfile(std::istream const& is){\n if(std::ifstream const* ifsP = dynamic_cast<std::ifstream const*>(&is)) return cfile(*ifsP);\n if(&is == &std::cin) return stdin;\n if(dynamic_cast<std::ostringstream const*>(&is) != 0){\n throw std::runtime_error(\"don't know how to extract FILE pointer from std::istringstream\");\n }\n return 0; // stream not recognized\n}\n iostringstream fscanf istream fmemopen cfile cfile // hack to access the protected member of istreambuf that know the current position\nchar* access_gptr(std::basic_streambuf<char, std::char_traits<char>>& bs){\n struct access_class : std::basic_streambuf<char, std::char_traits<char>>{\n char* access_gptr() const{return this->gptr();}\n };\n return ((access_class*)(&bs))->access_gptr();\n}\n\nint main(){\n std::istringstream iss(\"11 22 33\");\n // read the C++ way\n int j1; iss >> j1;\n std::cout << j1 << std::endl;\n\n // read the C way\n float j2;\n \n char* buf = access_gptr(*iss.rdbuf()); // get current position\n size_t buf_size = iss.rdbuf()->in_avail(); // get remaining characters\n FILE* file = fmemopen(buf, buf_size, \"r\"); // open buffer memory as FILE*\n fscanf(file, \"%f\", &j2); // finally!\n iss.rdbuf()->pubseekoff(ftell(file), iss.cur, iss.in); // update input stream position from current FILE position.\n\n std::cout << \"j2 = \" << j2 << std::endl;\n\n // read again the C++ way\n int j3; iss >> j3;\n std::cout << \"j3 = \" << j3 << std::endl;\n}\n" }, { "answer_id": 26746714, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 2, "selected": false, "text": "int fd = dup(0);\nclose(fd);\n// POSIX requires the next opened file descriptor to be fd.\nstd::fstream file(...);\n// now fd has been opened again and is owned by file\n" }, { "answer_id": 33612982, "author": "Jettatura", "author_id": 5543125, "author_profile": "https://Stackoverflow.com/users/5543125", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <cassert>\n\ntemplate<class STREAM>\nstruct STDIOAdapter\n{\n static FILE* yield(STREAM* stream)\n {\n assert(stream != NULL);\n\n static cookie_io_functions_t Cookies =\n {\n .read = NULL,\n .write = cookieWrite,\n .seek = NULL,\n .close = cookieClose\n };\n\n return fopencookie(stream, \"w\", Cookies);\n }\n\n ssize_t static cookieWrite(void* cookie,\n const char* buf,\n size_t size)\n {\n if(cookie == NULL)\n return -1;\n\n STREAM* writer = static_cast <STREAM*>(cookie);\n\n writer->write(buf, size);\n\n return size;\n }\n\n int static cookieClose(void* cookie)\n {\n return EOF;\n }\n}; // STDIOAdapter\n #include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/bzip2.hpp>\n#include <boost/iostreams/device/file.hpp>\n\nusing namespace boost::iostreams;\n\nint main()\n{ \n filtering_ostream out;\n out.push(boost::iostreams::bzip2_compressor());\n out.push(file_sink(\"my_file.txt\"));\n\n FILE* fp = STDIOAdapter<filtering_ostream>::yield(&out);\n assert(fp > 0);\n\n fputs(\"Was up, Man\", fp);\n\n fflush (fp);\n\n fclose(fp);\n\n return 1;\n}\n" }, { "answer_id": 44577546, "author": "yanpas", "author_id": 4355809, "author_profile": "https://Stackoverflow.com/users/4355809", "pm_score": 2, "selected": false, "text": "fstream FILE* fdopen FILE* dup2 #define private public\n#define protected public\n#include <fstream>\n#undef private\n#undef protected\n\nstd::ifstream file(\"some file\");\nauto fno = file._M_filebuf._M_file.fd();\n .cpp .h int getFdFromFstream(std::basic_ios<char>& fstr);" }, { "answer_id": 72932388, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 0, "selected": false, "text": "isatty() std::basic_filebuf<>() std::cout __gnu_cxx::stdio_sync_filebuf<>() isatty() FILE* ::isatty(fileno(<of FILE*>)) template<typename _CharT\n , typename _Traits = std::char_traits<_CharT>>\nbool isatty(std::basic_ios<_CharT, _Traits> const & s)\n{\n { // cin, cout, cerr, and clog\n typedef __gnu_cxx::stdio_sync_filebuf<_CharT, _Traits> io_sync_buffer_t;\n io_sync_buffer_t * buffer(dynamic_cast<io_sync_buffer_t *>(s.rdbuf()));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer->file()));\n }\n }\n\n { // modern versions\n typedef std::basic_filebuf<_CharT, _Traits> file_buffer_t;\n file_buffer_t * file_buffer(dynamic_cast<file_buffer_t *>(s.rdbuf()));\n if(file_buffer != nullptr)\n {\n typedef detail::our_basic_filebuf<_CharT, _Traits> hack_buffer_t;\n hack_buffer_t * buffer(static_cast<hack_buffer_t *>(file_buffer));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer->file()));\n }\n }\n }\n\n { // older versions\n typedef __gnu_cxx::stdio_filebuf<_CharT, _Traits> io_buffer_t;\n io_buffer_t * buffer(dynamic_cast<io_buffer_t *>(s.rdbuf()));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer->file()));\n }\n }\n\n return false;\n}\n our_basic_filebuf _M_file file() fd() std::basic_filebuf FILE* template<typename _CharT\n , typename _Traits = std::char_traits<_CharT>>\nclass our_basic_filebuf\n : public std::basic_filebuf<_CharT, _Traits>\n{\npublic:\n std::__c_file * file() throw()\n {\n return this->_M_file.file();\n }\n};\n _M_file" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,480
<p>I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.</p> <p>I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get <code>"User::getFavoriteThreads|1471"</code>. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.</p> <p><strong>However, and here comes the problem:</strong></p> <p>I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example</p> <pre><code>"Forum::getThreads|$iForumId|$iLimit|$iOffset". </code></pre> <p>Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under <code>"Forum::getThreads|$iForumId"</code>, no matter what the limit and offset is.</p> <p>What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.</p> <p>Thanks.</p>
[ { "answer_id": 109533, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 1, "selected": false, "text": "Forum::getThreads|$iForumId $page = 2;\n$threads_per_page = 25;\n$start_thread = $page * $threads_per_page;\n\n// Pull threads from cache (assuming $cache class for memcache interface..)\n$threads = $cache->get(\"Forum::getThreads|$iForumId\");\n\n// Only take the ones we need\nfor($i=$start_thread; $i<=$start_thread+$threads_per_page; $i++)\n{\n // Thread display logic here...\n showThread($threads[$i]);\n}\n" }, { "answer_id": 109742, "author": "flungabunga", "author_id": 11000, "author_profile": "https://Stackoverflow.com/users/11000", "pm_score": 3, "selected": false, "text": "memcache ExtendedMemcache->set $strGroup $strKey $strValue $strGroup $strKey $strKey $strValue memcache ExtendedMemcache memcache" }, { "answer_id": 438064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "get seqno_mygroup\n23\n\nget mygroup23_mykey\n<mykeydata...>\nget mygroup23_mykey2\n<mykey2data...>\n incr seqno_mygroup\n get seqno_mygroup\n24\n\nget mygroup24_mykey\n...empty\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11167/" ]
109,488
<p>I keep hearing that <code>div</code> tags should be used for layout purposes and not <code>table</code> tags. So does that also apply to form layout? I know a form layout is still a layout, but it seems like creating form layouts with <code>div</code>s requires more <code>html</code> and <code>css</code>. So with that in mind, should forms layouts use <code>div</code> tags instead?</p>
[ { "answer_id": 109516, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 6, "selected": true, "text": "<fieldset>\n <div>\n <label for=\"nameTextBox\">Name:</label>\n <input id=\"nameTextBox\" type=\"text\" />\n </div>\n ...\n</fieldset>\n" }, { "answer_id": 109538, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 4, "selected": false, "text": ".field label {\n float: left;\n width: 20%;\n}\n\n.field.text input {\n width: 75%;\n margin-left: 2%;\n padding: 3px;\n} <div class=\"field text\">\n <label for=\"fieldName\">Field Title</label>\n <input value=\"input value\" type=\"text\" name=\"fieldName\" id=\"fieldName\" />\n</div>" }, { "answer_id": 109573, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 2, "selected": false, "text": "<fieldset>\n <ol>\n <li>\n <label for='text_field'>Text Field</label>\n <input type='text' name='text_field' id='text_field' />\n </li>\n </ol>\n</fieldset>\n" }, { "answer_id": 110200, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 0, "selected": false, "text": "<dl>/<dt>/<dd> <dl>\n <dt><label for=\"nameTextBox\">Name:</label></dt>\n <dd><input value=\"input value\" type=\"text\" name=\"fieldName\" id=\"fieldName\" /></dd>\n</dl>\n <dt> <dd>" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
109,491
<p>I keep getting compiler errors when I try to access flashVars in an AS3 class.</p> <p>Here's a stripped version of the code:</p> <pre><code>package myPackage { import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; public class myClass { public function CTrafficHandler() { var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}} </code></pre> <p>And I get a compilation error:</p> <p><em>1119: Access of possibly undefined property root through a reference with static type source:myClass.</em></p> <p>When I change the class row to</p> <pre><code>public class myClass extends Sprite { </code></pre> <p>I don't get a compiler error, but I do get this in the output window:</p> <p><em>TypeError: Error #1009: Cannot access a property or method of a null object reference.</em></p> <p>Via the debugger (as suggested) I can see that <strong>this.root</strong> is null.</p> <p>How can I solve this problem?</p>
[ { "answer_id": 4268438, "author": "cleverbit", "author_id": 346098, "author_profile": "https://Stackoverflow.com/users/346098", "pm_score": 2, "selected": false, "text": "package\n{\n import flash.display.Sprite;\n import flash.events.Event;\n\n public class MySprite extends Sprite\n {\n // constructor\n public function MySprite()\n {\n super();\n addEventListener( Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true );\n }\n\n private function onAddedToStage( event:Event ):void\n {\n removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );\n\n var paramList:Object = LoaderInfo( this.root.loaderInfo ).parameters;\n var myParam:String = paramList[\"myParam\"];\n }\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18790/" ]
109,553
<p>I need to query existing rules, as well as being able to easily add and delete rules. I haven't found any API's for doing this. Is there something that I'm missing?</p> <p>The closest I've come to a solution is using <code>iptables-save | iptables-xml</code> for querying and manually calling the iptables command itself to add/delete rules. Another solution I've considered is simply regenerating the entire ruleset out of my application's database and flushing the whole chain, then applying it again. But I want to avoid this as I don't want to drop any packets -- unless there's a way to atomically do this. I'm wondering if there's a better way.</p> <p>An API in C would be great; however, as I'm planning to build this into a stand-alone suid program, libraries that do this in ANY language are fine too.</p>
[ { "answer_id": 109586, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "iptables-restore COMMIT iptables iptc_commit libiptc setsockopt(SO_SET_REPLACE) iptables-restore" }, { "answer_id": 109804, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "iptables -A INPUT -s 1.1.1.1 -p tcp -m --dport 22 -j ACCEPT\niptables -A INPUT -s 2.2.2.0/24 -p tcp -m --dport 22 -j ACCEPT\niptables -A INPUT -p tcp -m tcp --dport 22 -j REJECT\n ipset -N ssh_allowed nethash\niptables -A ssh_allowed -m set --set ssh_allowed src -p tcp -m --dport 22 -j ACCEPT\nipset -A ssh_allowed 1.1.1.1\nipset -A ssh_allowed 2.2.2.0/24\n" }, { "answer_id": 16093798, "author": "Patrick", "author_id": 2297056, "author_profile": "https://Stackoverflow.com/users/2297056", "pm_score": 2, "selected": false, "text": "cat **\"output of the logs\"** | php ipchains.php **\"something unique in the logs\"**\n <?php\n\n$ip_arr = array();\n\nwhile(1)\n{\n $line = trim(fgets(STDIN)); // reads one line from STDIN\n $ip = trim( strtok( $line, \" \") );\n\n if( !array_key_exists( $ip, $ip_arr ) )\n $ip_arr[$ip] = 0;\n\n $regex = sprintf( \"/%s/\", $argv[1] );\n\n $cnt = preg_match_all( $regex, $line );\n\n if( $cnt < 1 ) continue;\n\n $ip_arr[$ip] += 1;\n\n if( $ip_arr[$ip] == 1 )\n {\n// printf( \"%s\\n\", $argv[1] );\n// printf( \"%d\\n\", $cnt );\n// printf( \"%s\\n\", $line );\n\n printf( \"-A BLOCK1 -s %s/24 -j DROP\\n\", $ip );\n\n $cmd = sprintf( \"/sbin/iptables -I BLOCK1 -d %s/24 -j DROP\", $ip );\n system( $cmd );\n }\n}\n\n?>\n 1) BLOCK1 is a Chain already created. \n2) BLOCK1 is a Chain that is run/called from the INPUT CHAIN \n3) Periodically you will need to run \"ipchains -S BLOCK1\" and put output in /etc/sysconfig file. \n4) You are familiar with PHP \n5) You understand web log line items/fields and output.\n" }, { "answer_id": 18961668, "author": "Andrew", "author_id": 2249641, "author_profile": "https://Stackoverflow.com/users/2249641", "pm_score": 1, "selected": false, "text": "IP=$(awk '/Bye Bye/{print $9}' /var/log/secure |\n sed 's/://g' |sort -u | head -n 1)\n\n[[ \"$IP\" < \"123\" ]] || {\n\n echo \"Found $IP - blocking it...\" >> /var/log/hacker.log\n\n /sbin/iptables -A INPUT -s $IP -j DROP\n\n service iptables save\n\n sed -i \"/$IP/d\" /var/log/secure\n\n}\n" }, { "answer_id": 22647960, "author": "Grzegorz Luczywo", "author_id": 2184341, "author_profile": "https://Stackoverflow.com/users/2184341", "pm_score": 3, "selected": false, "text": "PUT /drop/input/eth0/11.22.33.44\n iptables -I INPUT -i eth0 -s 11.22.33.44 -j DROP\n GET /list/input\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495/" ]
109,580
<p>I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible?</p> <p>Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page.</p>
[ { "answer_id": 109600, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 0, "selected": false, "text": "[Root drive]:\\Documents and Settings\\[username]\\Application Data\\Macromedia\\Flash Player\\#SharedObjects\\\n" }, { "answer_id": 110626, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 0, "selected": false, "text": "getURL('javascript:document.cookie = \"varname=varvalue; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=\"');" }, { "answer_id": 114287, "author": "Simon", "author_id": 15371, "author_profile": "https://Stackoverflow.com/users/15371", "pm_score": 5, "selected": true, "text": "import flash.external.ExternalInterface;\n\npublic class HTTPCookies\n{\n public static function getCookie(key:String):*\n {\n return ExternalInterface.call(\"getCookie\", key);\n }\n\n public static function setCookie(key:String, val:*):void\n {\n ExternalInterface.call(\"setCookie\", key, val);\n }\n}\n function getCookie(key)\n{\n var cookieValue = null;\n\n if (key)\n {\n var cookieSearch = key + \"=\";\n\n if (document.cookie)\n {\n var cookieArray = document.cookie.split(\";\");\n for (var i = 0; i < cookieArray.length; i++)\n {\n var cookieString = cookieArray[i];\n\n // skip past leading spaces\n while (cookieString.charAt(0) == ' ')\n {\n cookieString = cookieString.substr(1);\n }\n\n // extract the actual value\n if (cookieString.indexOf(cookieSearch) == 0)\n {\n cookieValue = cookieString.substr(cookieSearch.length);\n }\n }\n }\n }\n\n return cookieValue;\n}\n\nfunction setCookie(key, val)\n{\n if (key)\n {\n var date = new Date();\n\n if (val != null)\n {\n // expires in one year\n date.setTime(date.getTime() + (365*24*60*60*1000));\n document.cookie = key + \"=\" + val + \"; expires=\" + date.toGMTString();\n }\n else\n {\n // expires yesterday\n date.setTime(date.getTime() - (24*60*60*1000));\n document.cookie = key + \"=; expires=\" + date.toGMTString();\n }\n }\n}\n" }, { "answer_id": 159007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import flash.external.ExternalInterface;\npublic class HTTPCookies\n{ \n public static function getCookie(key:String):* \n {\n return ExternalInterface.call(\"getCookie\", key); \n }\n public static function setCookie(key:String, val:*):void \n {\n ExternalInterface.call(\"setCookie\", key, val); \n }\n}\n" }, { "answer_id": 50107487, "author": "Eddie", "author_id": 654499, "author_profile": "https://Stackoverflow.com/users/654499", "pm_score": 0, "selected": false, "text": "import flash.net.*\n\nvar _loader:URLLoader = new URLLoader();\nvar _req:URLRequest = new URLRequest('https://stackoverflow.com');\n_loader.addEventListener(Event.COMPLETE, _onComplete);\n_loader.load(_req);\n\nfunction _onComplete(e:Event):void{\n var wantedData:RegExp = /<div class=\"cool-data\">(.*?)</div>/ig;\n var result:Object = wantedData.exec(String(_loader.data));\n trace(result[0].split('<div class=\"cool-data\">').join('')\n .split('</div>').join(''));\n\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497/" ]
109,608
<p>When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml:</p> <pre><code>&lt;System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="0" Margin="0"&gt; &lt;System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left"&gt; &lt;ContentControl&gt; &lt;Grid Width="400" Height="200" Background="White"/&gt; &lt;/ContentControl&gt; &lt;/System_Windows_Controls:TabItem&gt; &lt;/System_Windows_Controls:TabControl&gt; </code></pre> <p>will produce:</p> <p><img src="https://i.stack.imgur.com/y5LuN.jpg" alt="alt text"></p> <p>How do I position the content at 0,0?</p>
[ { "answer_id": 159396, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left=\"0\" Canvas.Top=\"75\" Width=\"800\" Height=\"525\" Background=\"Red\" HorizontalContentAlignment=\"Left\" VerticalContentAlignment=\"Top\" Padding=\"0\" Margin=\"0\">\n <System_Windows_Controls:TabItem Header=\"Test\" VerticalContentAlignment=\"Top\" BorderThickness=\"0\" Margin=\"0\" Padding=\"0\" HorizontalContentAlignment=\"Left\">\n <ContentControl>\n <Grid Width=\"400\" Height=\"200\" Margin=\"-9,-9,-9,-9\" Background=\"White\"/>\n </ContentControl>\n </System_Windows_Controls:TabItem> \n</System_Windows_Controls:TabControl>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4244/" ]
109,618
<p>I want the following layout to appear on the screen:</p> <pre><code>FieldName 1 [Field input 1] FieldName 2 is longer [Field input 2] . . . . FieldName N [Field input N] </code></pre> <p>Requirements:</p> <ul> <li>Field names and field inputs must align on the left edges</li> <li>Both columns must dynamically size themselves to their content</li> <li>Must work cross-browsers</li> </ul> <p>I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.</p>
[ { "answer_id": 109628, "author": "Héctor Ramos", "author_id": 19617, "author_profile": "https://Stackoverflow.com/users/19617", "pm_score": -1, "selected": false, "text": "<div style=\"clear: both\"/> <br/> <span style=\"float: left; width: 200px\">FieldName1</span><span style=\"float: left\"><input/><br/>\n\n<span style=\"float: left; width: 200px\">FieldName2</span><span style=\"float: left\"><input/><br/>\n\n<span style=\"float: left\">FieldName3</span><span style=\"float: left\"><input/><br/>\n" }, { "answer_id": 109656, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 2, "selected": false, "text": " <fieldset class=\"classname\">\n <ul>\n <li>\n <label>Title:</label>\n <input type=\"text\" name=\"title\" value=\"\" />\n </li>\n </ul>\n </fieldset>\n" }, { "answer_id": 109714, "author": "robertc", "author_id": 8655, "author_profile": "https://Stackoverflow.com/users/8655", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <title>Form layout</title>\n <style type=\"text/css\">\n fieldset {width: 60%; margin: 0 auto;}\n div.row {clear: both;}\n div.row label {float: left; width: 60%;}\n div.row span {float: right; width: 35%;}\n </style>\n</head>\n<body>\n <form action=\"#\" method=\"post\">\n <fieldset>\n <legend>Section one</legend>\n <div class=\"row\">\n <label for=\"first-field\">The first field</label>\n <span><input type=\"text\" id=\"first-field\" size=\"15\" /></span>\n </div>\n <div class=\"row\">\n <label for=\"second-field\">The second field with a longer label</label>\n <span><input type=\"text\" id=\"second-field\" size=\"10\" /></span>\n </div>\n <div class=\"row\">\n <label for=\"third-field\">The third field</label>\n <span><input type=\"text\" id=\"third-field\" size=\"5\" /></span>\n </div>\n <div class=\"row\">\n <input type=\"submit\" value=\"Go\" />\n </div>\n </fieldset>\n </form>\n</body>\n</html>\n" }, { "answer_id": 109756, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 4, "selected": true, "text": "<th> <table>\n <tr><th scope=\"row\"><label for=\"field1\">FieldName 1</label></th>\n <td><input id=\"field1\" name=\"field1\"></td></tr>\n <tr><th scope=\"row\"><label for=\"field2\">FieldName 2 is longer</label></th>\n <td><input id=\"field2\" name=\"field2\"></td></tr>\n <!-- ....... -->\n</table>\n" }, { "answer_id": 167263, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n <head>\n <title>My Form</title>\n <style type=\"text/css\">\n #frm1 div {float: left;}\n #frm1 div.go {clear: both; }\n #frm1 label, #frm1 input { float: left; clear: left; }\n </style>\n </head>\n <body>\n <form id=\"frm1\" action=\"#\" method=\"post\">\n <fieldset>\n <legend>Section One</legend>\n <div>\n <label for=\"field1\">Name</label>\n <label for=\"field2\">Address, City, State, Zip</label>\n <label for=\"field3\">Country</label>\n </div>\n <div>\n <input type=\"text\" id=\"field1\" size=\"15\" />\n <input type=\"text\" id=\"field2\" size=\"20\" />\n <input type=\"text\" id=\"field3\" size=\"10\" />\n </div>\n <div class=\"go\">\n <input type=\"submit\" value=\"Go\" />\n </div>\n </fieldset>\n </form>\n </body>\n</html>\n for=\"\"" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284/" ]
109,644
<p><code>temp2</code>, <code>temp1</code> are pointers to some struct x:</p> <pre><code>struct FunkyStruct x; struct FunkyStruct *temp1 = &amp;x, *temp2 = &amp;x; </code></pre> <p>Now, after execution of following lines:</p> <pre><code>temp2=temp1; temp1=temp1-&gt;nxt; </code></pre> <p>...Will <code>temp2</code> and <code>temp1</code> still point to the same memory location? If not, please explain why they would be different. </p>
[ { "answer_id": 109655, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 1, "selected": false, "text": "temp2 = temp1;\n*temp1 = temp1->foo;\n" }, { "answer_id": 109678, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 3, "selected": false, "text": "temp1 temp2 x temp2 = temp1 temp1 temp2 temp1->next temp1 next temp1 = temp1->next temp1->next temp1 temp1 next" }, { "answer_id": 109789, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": " int temp1 = 1;\n int temp2;\n temp2=temp1;\n temp1=temp1 + 1;\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19790/" ]
109,668
<p>I'm using castle windsor for a pet-project I'm working on. I'm starting to notice that I need to call the IoC container in different places in my code to create new objects. This dependency on the container makes my code harder to maintain.</p> <p>There are two solutions I've used to solve this problem</p> <p>I tried to create abstract factories as wrappers around the container that I could inject into parts of my application that need to create objects. This works but has some drawbacks because castle has a hard time injecting it's own container as a dependency. So I have to do that by hand, this kind of defeats the whole purpose of the IoC container.</p> <p>I have used the main applicationcontroller class to wrap the IoC container and work as a central factory/repository. This was quite succesfull but this class is getting too big and acts like a central god-object, almost every other objects has a reference to it.</p> <p>Both solutions sort of work but both have their drawbacks. So I'm curious if other people had the same problem and have found better solutions.</p> <hr> <p><em>edit</em> The problem isn't for object A that depends on object B. Here I usually just use constructor injection and everything works. Sometimes I have objects of type A that need to create a variable number of other objects of type B during their lifetime. I'm not sure how to do this.</p> <p>@Blair Conrad: The maintenance issues are not severe until now. I had some classes depend on the container object calling container.Resolve&lt;>. And I don't want to have my code depending on what I think is infrastructure. I'm still trying things out so I noticed I had to change a lot of code when switching from ninject to castle for this project.</p> <p>@flowers: Hmm. I like your fists solution. It combines the things that work from both solutions I've tried. I think I was still thinking too much in objects and not enough in interfaces/responsibilities. I tried purpose built factories but I would like to have them use the container behind the scenes to create the objects and I havn't found out how I can DI the container into objects in a clean way.</p>
[ { "answer_id": 121114, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 2, "selected": false, "text": "IServiceLocator container = ContainerFactory.GetContainer(); \nwhile( keepLooping )\n{\n IExample example = container.GetInstance<IExample>();\n keepLooping = example.DoWork();\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
109,705
<p>The following program is very simple: it outputs a single dot each half a second. If it recieves a <strong>SIGQUIT</strong>, it proceeds to output ten <strong>Q</strong>s. If it recieves a <strong>SIGTSTP</strong> <em>(<kbd>Ctrl</kbd>-<kbd>Z</kbd>)</em>, it outputs ten <strong>Z</strong>s.</p> <p>If it recieves a <strong>SIGTSTP</strong> while printing <strong>Q</strong>s, it will print ten <strong>Z</strong>s after it's done with the ten <strong>Q</strong>s. This is a good thing.</p> <p>However, if it recieves a <strong>SIGQUIT</strong> while printing <strong>Z</strong>s, it fails to print <strong>Q</strong>s after them. Instead, it prints them out only after I manually terminate execution via a KeyboardInterrupt. I want the <strong>Q</strong>s to be printed immediately after the <strong>Z</strong>s.</p> <p>This happens using Python2.3.</p> <p>What am I doing wrong?</p> <pre><code>#!/usr/bin/python from signal import * from time import sleep from sys import stdout def write(text): stdout.write(text) stdout.flush() def process_quit(signum, frame): for i in range(10): write(&quot;Q&quot;) sleep(0.5) def process_tstp(signum, frame): for i in range(10): write(&quot;Z&quot;) sleep(0.5) signal(SIGQUIT, process_quit) signal(SIGTSTP, process_tstp) while 1: write('.') sleep(0.5) </code></pre>
[ { "answer_id": 109783, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 4, "selected": true, "text": "#!/usr/bin/python\n\nfrom signal import *\nfrom time import sleep\nfrom sys import stdout\n\nprint_Qs = 0\nprint_Zs = 0\n\ndef write(text):\n stdout.write(text)\n stdout.flush()\n\ndef process_quit(signum, frame):\n global print_Qs\n print_Qs = 10\n\ndef process_tstp(signum, frame):\n global print_Zs\n print_Zs = 10\n\nsignal(SIGQUIT, process_quit)\nsignal(SIGTSTP, process_tstp)\n\nwhile 1:\n if print_Zs:\n print_Zs -= 1\n c = 'Z'\n elif print_Qs:\n print_Qs -= 1\n c = 'Q'\n else:\n c = '.'\n write(c)\n sleep(0.5)\n while 1: for i in range(60):" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
109,710
<p>I've been digging through some parts of the Linux kernel, and found calls like this:</p> <pre><code>if (unlikely(fd &lt; 0)) { /* Do something */ } </code></pre> <p>or</p> <pre><code>if (likely(!err)) { /* Do something */ } </code></pre> <p>I've found the definition of them:</p> <pre><code>#define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) </code></pre> <p>I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).</p>
[ { "answer_id": 109732, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 6, "selected": false, "text": "if (unlikely(x)) {\n dosomething();\n}\n\nreturn x;\n if (!x) {\n return x;\n}\n\ndosomething();\nreturn x;\n" }, { "answer_id": 9594973, "author": "Finaldie", "author_id": 992917, "author_profile": "https://Stackoverflow.com/users/992917", "pm_score": 2, "selected": false, "text": "compiler.h /usr/linux/ if ( likely( ... ) ) {\n doSomething();\n}\n" }, { "answer_id": 21391535, "author": "artless noise", "author_id": 1880339, "author_profile": "https://Stackoverflow.com/users/1880339", "pm_score": 2, "selected": false, "text": "hot cold dump_stack() cold if(unlikely(err)) {\n printk(\"Driver error found. %d\\n\", err);\n dump_stack();\n }\n gcc boolean cold" }, { "answer_id": 31133787, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 7, "selected": false, "text": "__builtin_expect #include \"stdio.h\"\n#include \"time.h\"\n\nint main() {\n /* Use time to prevent it from being optimized away. */\n int i = !time(NULL);\n if (i)\n printf(\"%d\\n\", i);\n puts(\"a\");\n return 0;\n}\n gcc -c -O3 -std=gnu11 main.c\nobjdump -dr main.o\n 0000000000000000 <main>:\n 0: 48 83 ec 08 sub $0x8,%rsp\n 4: 31 ff xor %edi,%edi\n 6: e8 00 00 00 00 callq b <main+0xb>\n 7: R_X86_64_PC32 time-0x4\n b: 48 85 c0 test %rax,%rax\n e: 75 14 jne 24 <main+0x24>\n 10: ba 01 00 00 00 mov $0x1,%edx\n 15: be 00 00 00 00 mov $0x0,%esi\n 16: R_X86_64_32 .rodata.str1.1\n 1a: bf 01 00 00 00 mov $0x1,%edi\n 1f: e8 00 00 00 00 callq 24 <main+0x24>\n 20: R_X86_64_PC32 __printf_chk-0x4\n 24: bf 00 00 00 00 mov $0x0,%edi\n 25: R_X86_64_32 .rodata.str1.1+0x4\n 29: e8 00 00 00 00 callq 2e <main+0x2e>\n 2a: R_X86_64_PC32 puts-0x4\n 2e: 31 c0 xor %eax,%eax\n 30: 48 83 c4 08 add $0x8,%rsp\n 34: c3 retq\n printf puts retq __builtin_expect if (i) if (__builtin_expect(i, 0))\n 0000000000000000 <main>:\n 0: 48 83 ec 08 sub $0x8,%rsp\n 4: 31 ff xor %edi,%edi\n 6: e8 00 00 00 00 callq b <main+0xb>\n 7: R_X86_64_PC32 time-0x4\n b: 48 85 c0 test %rax,%rax\n e: 74 11 je 21 <main+0x21>\n 10: bf 00 00 00 00 mov $0x0,%edi\n 11: R_X86_64_32 .rodata.str1.1+0x4\n 15: e8 00 00 00 00 callq 1a <main+0x1a>\n 16: R_X86_64_PC32 puts-0x4\n 1a: 31 c0 xor %eax,%eax\n 1c: 48 83 c4 08 add $0x8,%rsp\n 20: c3 retq\n 21: ba 01 00 00 00 mov $0x1,%edx\n 26: be 00 00 00 00 mov $0x0,%esi\n 27: R_X86_64_32 .rodata.str1.1\n 2b: bf 01 00 00 00 mov $0x1,%edi\n 30: e8 00 00 00 00 callq 35 <main+0x35>\n 31: R_X86_64_PC32 __printf_chk-0x4\n 35: eb d9 jmp 10 <main+0x10>\n printf __printf_chk puts int main() {\n int i = !time(NULL);\n if (i)\n goto printf;\nputs:\n puts(\"a\");\n return 0;\nprintf:\n printf(\"%d\\n\", i);\n goto puts;\n}\n -O0 __builtin_expect [[likely]] [[unlikely]]" }, { "answer_id": 40765708, "author": "Ashish Maurya", "author_id": 3263654, "author_profile": "https://Stackoverflow.com/users/3263654", "pm_score": 3, "selected": false, "text": "long __builtin_expect(long EXP, long C);\n #define unlikely(expr) __builtin_expect(!!(expr), 0)\n#define likely(expr) __builtin_expect(!!(expr), 1)\n if (likely(a > 1))\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9232/" ]
109,717
<p>In C#, if you have multiple constructors, you can do something like this:</p> <pre><code>public MyClass(Guid inputId, string inputName){ // do something } public MyClass(Guid inputId): this(inputId, "foo") {} </code></pre> <p>The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor:</p> <pre><code>public MyClass(MyOtherClass inputObject) { Guid inputId = inputObject.ID; MyThirdClass mc = inputObject.CreateHelper(); string inputText = mc.Text; mc.Dispose(); // Need to call the main Constructor now with inputId and inputText } </code></pre> <p>The caveat here is that I need to create an object that <strong>has</strong> to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)</p> <p>However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?</p> <p>Or is it possible to use</p> <pre><code>public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.CreateHelper().Text) {} </code></pre> <p>Would this automatically Dispose the generated Object from CreateHelper()?</p> <p><strong>Edit:</strong> Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach.</p>
[ { "answer_id": 109728, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "using using (MyThirdClass mc = inputObject.CreateHelper())\n{\n // do something with mc\n}\n" }, { "answer_id": 109729, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 5, "selected": true, "text": "public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {}\n\nprivate static string GetHelperText(MyOtherClass o)\n{\n using (var helper = o.CreateHelper())\n return helper.Text;\n}\n" }, { "answer_id": 109737, "author": "Nathan", "author_id": 541, "author_profile": "https://Stackoverflow.com/users/541", "pm_score": 2, "selected": false, "text": "public class MyOtherClass\n{\n //...\n public string GetText()\n {\n using (var h = CreateHelper())\n return h.Text;\n }\n}\n public static class MyOtherClassExtensions\n{\n public static string GetText(this MyOtherClass parent)\n {\n using(var helper = parent.CreateHelper())\n {\n return helper.Text;\n }\n }\n}\n public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.GetText()) {}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
109,753
<p>I would like to programmatically create a gloss effect on an Image, kinda like on the Apple-inspired design that the Web has adopted when it was updated to 2.0 Beta.</p> <p>Essentially this:</p> <p><a href="http://nhc.hcmuns.googlepages.com/web2_icons.jpg" rel="nofollow noreferrer">example icons http://nhc.hcmuns.googlepages.com/web2_icons.jpg</a></p> <p>Now, I see two approaches here: I create one image which has an Alpha channel with the gloss effect, and then I just combine the input and the gloss alpha icon to create this.</p> <p>The second approach: Create the Alpha Gloss Image in code and then merge it with the input graphic.</p> <p>I would prefer the second solution, but I'm not much of a graphics person and I don't know what the algorhithm is called to create such effects. Can someone give me some pointers* for what I am actually looking here? is there a "gloss algorhitm" that has a name? or even a .net Implementation already?</p> <p>*No, not <a href="http://xkcd.com/138/" rel="nofollow noreferrer">those type</a> of pointers.</p>
[ { "answer_id": 109868, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "Image img = Image.FromFile(\"rss-icon.jpg\");\npictureBox1.Image = AddCircularGloss(img, 30,25,255,255,255);\n\npublic static Image AddCircularGloss(Image inputImage, int exposurePercentage, int transparency, int fillColorR, int fillColorG, int fillColorB)\n{\n Bitmap outputImage = new Bitmap(inputImage);\n using (Graphics g = Graphics.FromImage(outputImage))\n {\n using (Pen p = new Pen(Color.FromArgb(transparency, fillColorR, fillColorG, fillColorB)))\n {\n // Looks jaggy otherwise\n g.SmoothingMode = SmoothingMode.HighQuality;\n g.CompositingQuality = CompositingQuality.HighQuality;\n int x, y;\n\n // 3 * Height looks best\n int diameter = outputImage.Height * 3;\n double imgPercent = (double)outputImage.Height / 100;\n x = 0 - outputImage.Width;\n\n // How many percent of the image to expose\n y = (0 - diameter) + (int)(imgPercent * exposurePercentage);\n g.FillEllipse(p.Brush, x, y, diameter, diameter);\n }\n }\n return outputImage;\n}\n" }, { "answer_id": 110709, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "// Experiment with this value\nint exposurePercentage = 40;\n\nusing (Image img = Image.FromFile(\"rss-icon.jpg\"))\n{\n using (Graphics g = Graphics.FromImage(img))\n { \n // First Number = Alpha, Experiment with this value.\n using (Pen p = new Pen(Color.FromArgb(75, 255, 255, 255)))\n {\n // Looks jaggy otherwise\n g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n\n int x, y;\n\n // 3 * Height looks best\n int diameter = img.Height * 3;\n double imgPercent = (double)img.Height / 100;\n x = 0 - img.Width;\n\n // How many percent of the image to expose\n y = (0 - diameter) + (int)(imgPercent * exposurePercentage);\n\n g.FillEllipse(p.Brush, x, y, diameter, diameter);\n\n pictureBox1.Image = img;\n }\n }\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
109,759
<p>I've just switched an application to use ar_mailer and when I run ar_sendmail (after a long pause) I get the following error:</p> <pre><code>Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4 </code></pre> <p>I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp_settings just installed ar_mailer.</p> <p>Versions: </p> <p>Rails: 2.1, ar_mailer: 1.3.1</p>
[ { "answer_id": 985034, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "smtp_tls enable_startls_auto ActionMailer::Base.smtp_settings = {\n :enable_starttls_auto => true,\n ...\n ...\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
109,769
<p>I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located <a href="http://www.thomasfrank.se/classier_json.html" rel="nofollow noreferrer">ClassyJSON</a>. Any thoughts?</p>
[ { "answer_id": 109786, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "[DataContract]\npublic class Foo\n{\n [DataMember]\n public string FooName {get;set;}\n [DataMember]\n public FooItem[] FooItems {get;set;}\n}\n\n\n[DataContract]\npublic class FooItem\n{\n [DataMember]\n public string Name {get;set;}\n}\n" }, { "answer_id": 109788, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 2, "selected": true, "text": "\"f = \"+function() {} var test = \"f = \" + function() { alert(\"Hello\"); };\neval(test)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19799/" ]
109,776
<p>What's the best way to create recurring tasks?</p> <p>Should I create some special syntax and parse it, kind of similar to Cronjobs on Linux or should I much rather just use a cronjob that runs every hour to create more of those recurring tasks with no end?</p> <p>Keep in mind, that you can have endless recurring tasks and tasks with an enddate.</p>
[ { "answer_id": 109786, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "[DataContract]\npublic class Foo\n{\n [DataMember]\n public string FooName {get;set;}\n [DataMember]\n public FooItem[] FooItems {get;set;}\n}\n\n\n[DataContract]\npublic class FooItem\n{\n [DataMember]\n public string Name {get;set;}\n}\n" }, { "answer_id": 109788, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 2, "selected": true, "text": "\"f = \"+function() {} var test = \"f = \" + function() { alert(\"Hello\"); };\neval(test)\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535/" ]
109,781
<p>What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?</p> <p>These objects are stored in ActiveRecord so using AR's methods would be fine too. </p>
[ { "answer_id": 109794, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 3, "selected": false, "text": "select [1, 2, 3, 4, 5, 6, 7].select{|e| e%2 == 0} [2,4,6] detect [1, 2, 3, 4, 5, 6, 7].detect{|e| e>3} 4" }, { "answer_id": 109828, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": 2, "selected": false, "text": "class Foo\n attr_accessor :foo, :bar, :baz\n\n def initialize(foo,bar,baz)\n @foo = foo\n @bar = bar\n @baz = baz\n end\nend\n\nobjs = [Foo.new(1,2,3),Foo.new(1,2,3),Foo.new(2,3,4)]\n\n# find objects that are uniq with respect to attributes\nobjs.inject([]) do |uniqs,obj|\n if uniqs.all? { |e| Marshal.dump(e) != Marshal.dump(obj) }\n uniqs << obj\n end\n uniqs\nend\n" }, { "answer_id": 109911, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 0, "selected": false, "text": "class A\n attr_accessor :val\n def initialize(v); self.val = v; end\nend\n\nobjs = [1,2,6,3,7,7,8,2,8].map{|i| A.new(i)}\n\nobjs.sort_by{|a| a.val}.inject([]) do |uniqs, a|\n uniqs << a if uniqs.empty? || a.val != uniqs.last.val\n uniqs\nend\n" }, { "answer_id": 109969, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": false, "text": "YourModel.find(:all, :group => \"status\")\n" }, { "answer_id": 109983, "author": "jmah", "author_id": 3948, "author_profile": "https://Stackoverflow.com/users/3948", "pm_score": 2, "selected": false, "text": "Hash[*recs.map{|ar| [ar[attr],ar]}.flatten].values\n" }, { "answer_id": 113770, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 5, "selected": false, "text": "uniq_by sort_by uniq_by uniq sort_by sort uniq_array = my_array.uniq_by {|obj| obj.id}\n class Array\n def uniq_by(&blk)\n transforms = []\n self.select do |el|\n should_keep = !transforms.include?(t=blk[el])\n transforms << t\n should_keep\n end\n end\nend\n uniq_by! class Array\n def uniq_by(&blk)\n transforms = {}\n select do |el|\n t = blk[el]\n should_keep = !transforms[t]\n transforms[t] = true\n should_keep\n end\n end\nend\n" }, { "answer_id": 231549, "author": "Head", "author_id": 30951, "author_profile": "https://Stackoverflow.com/users/30951", "pm_score": 3, "selected": false, "text": "objs.inject({}) {|h,e| h[e.attr]=e; h}.values\n h = {}\nobjs.each {|e| h[e.attr]=e}\nh.values\n" }, { "answer_id": 5945378, "author": "apb", "author_id": 374873, "author_profile": "https://Stackoverflow.com/users/374873", "pm_score": 2, "selected": false, "text": "#uniq_by" }, { "answer_id": 9656625, "author": "TKH", "author_id": 458244, "author_profile": "https://Stackoverflow.com/users/458244", "pm_score": 1, "selected": false, "text": "h = Set.new\nobjs.select{|el| h.add?(el.attr)}\n" }, { "answer_id": 10083791, "author": "Lane", "author_id": 639040, "author_profile": "https://Stackoverflow.com/users/639040", "pm_score": 9, "selected": true, "text": "Array#uniq @photos = @photos.uniq { |p| p.album_id }\n" }, { "answer_id": 11551341, "author": "grosser", "author_id": 110333, "author_profile": "https://Stackoverflow.com/users/110333", "pm_score": 1, "selected": false, "text": "def uniq_by\n hash, array = {}, []\n each { |i| hash[yield(i)] ||= (array << i) }\n array\nend\n" }, { "answer_id": 37705197, "author": "yauhenininjia", "author_id": 6128896, "author_profile": "https://Stackoverflow.com/users/6128896", "pm_score": 4, "selected": false, "text": "@photos = @photos.uniq { |p| [p.album_id, p.author_id] }\n" }, { "answer_id": 46332903, "author": "Igbanam", "author_id": 393021, "author_profile": "https://Stackoverflow.com/users/393021", "pm_score": 2, "selected": false, "text": "Array#uniq enumerable_collection.uniq(&:property)\n" }, { "answer_id": 58033851, "author": "7mode", "author_id": 3129011, "author_profile": "https://Stackoverflow.com/users/3129011", "pm_score": 3, "selected": false, "text": "objects.uniq {|obj| obj.attribute}\n objects.uniq(&:attribute)\n" }, { "answer_id": 68949632, "author": "Vasanth Saminathan", "author_id": 5634603, "author_profile": "https://Stackoverflow.com/users/5634603", "pm_score": 0, "selected": false, "text": "set = Set.new\nset << obj1\nset << obj2\nset.inspect\n eql? hash" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
109,815
<p>Ok, I get the basics of video format - there are some container formats and then you have core video/audio formats. I would like to write a web based application that determines what video/audio codec a file is using.</p> <p>How best can I programmatically determine a video codec? Would it be best to use a standard library via system calls and parse its output? (eg ffmpeg, transcode, etc?)</p>
[ { "answer_id": 109827, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 3, "selected": false, "text": "mplayer -identify ffmpeg" }, { "answer_id": 119897, "author": "AdamB", "author_id": 20134, "author_profile": "https://Stackoverflow.com/users/20134", "pm_score": 3, "selected": false, "text": "$info = `ffmpeg -i $path$file 2>&1 /dev/null`;\n@fields = split(/\\n/, $info);\n" }, { "answer_id": 19110879, "author": "mente", "author_id": 51966, "author_profile": "https://Stackoverflow.com/users/51966", "pm_score": 0, "selected": false, "text": "ffprobe $meta = json_decode(join(' ', `ffprobe -v quiet -print_format json -show_format -show_streams /path/to/file 2>&1`));\n null $file = '/path/to/file';\n$cmd = 'ffprobe -v quiet -print_format json -show_format -show_streams ' . escapeshellarg($file).' 2>&1';\n\nexec($cmd, $output, $code);\nif ($code != 0) {\n throw new ErrorException(\"ffprobe returned non-zero code\", $code, $output);\n}\n\n$joinedOutput = join(' ', $output);\n$parsedOutput = json_decode($joinedOutput);\nif (null === $parsedOutput) {\n throw new ErrorException(\"Unable to parse ffprobe output\", $code, $output);\n}\n\n//here we can use $parsedOutput as simple stdClass\n" }, { "answer_id": 23657328, "author": "Dima L.", "author_id": 610060, "author_profile": "https://Stackoverflow.com/users/610060", "pm_score": 0, "selected": false, "text": "sudo apt-get install mediainfo\n $videoCodec = `mediainfo --Inform=\"Video;%Format%\" $filename`;\n$audioCodec = `mediainfo --Inform=\"Audio;%Format%\" $filename`;\n function getCodecInfo($inputFile)\n{\n $cmdLine = 'mediainfo --Output=XML ' . escapeshellarg($inputFile);\n\n exec($cmdLine, $output, $retcode);\n if($retcode != 0)\n return null;\n\n try\n {\n $xml = new SimpleXMLElement(join(\"\\n\",$output));\n $videoCodec = $xml->xpath('//track[@type=\"Video\"]/Format');\n $audioCodec = $xml->xpath('//track[@type=\"Audio\"]/Format');\n }\n catch(Exception $e)\n {\n return null;\n }\n\n if(empty($videoCodec[0]) || empty($audioCodec[0]))\n return null;\n\n return array(\n 'videoCodec' => (string)$videoCodec[0],\n 'audioCodec' => (string)$audioCodec[0],\n );\n}\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19805/" ]